Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

1,996 lines · 53.6 KiB · Python

Last changed by

Break reference cycle created by default in Flask instances.Bogdan Opanchukbefore adoption8efea0c

History of this file

Take it

1import gc2import re3import sys4import time5import uuid6import weakref7from datetime import datetime8from platform import python_implementation9from threading import Thread1011import pytest12import werkzeug.serving13from werkzeug.exceptions import BadRequest14from werkzeug.exceptions import Forbidden15from werkzeug.exceptions import NotFound16from werkzeug.http import parse_date17from werkzeug.routing import BuildError1819import flask202122require_cpython_gc = pytest.mark.skipif(23    python_implementation() != "CPython", reason="Requires CPython GC behavior",24)252627def test_options_work(app, client):28    @app.route("/", methods=["GET", "POST"])29    def index():30        return "Hello World"3132    rv = client.open("/", method="OPTIONS")33    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]34    assert rv.data == b""353637def test_options_on_multiple_rules(app, client):38    @app.route("/", methods=["GET", "POST"])39    def index():40        return "Hello World"4142    @app.route("/", methods=["PUT"])43    def index_put():44        return "Aha!"4546    rv = client.open("/", method="OPTIONS")47    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST", "PUT"]484950def test_provide_automatic_options_attr():51    app = flask.Flask(__name__)5253    def index():54        return "Hello World!"5556    index.provide_automatic_options = False57    app.route("/")(index)58    rv = app.test_client().open("/", method="OPTIONS")59    assert rv.status_code == 4056061    app = flask.Flask(__name__)6263    def index2():64        return "Hello World!"6566    index2.provide_automatic_options = True67    app.route("/", methods=["OPTIONS"])(index2)68    rv = app.test_client().open("/", method="OPTIONS")69    assert sorted(rv.allow) == ["OPTIONS"]707172def test_provide_automatic_options_kwarg(app, client):73    def index():74        return flask.request.method7576    def more():77        return flask.request.method7879    app.add_url_rule("/", view_func=index, provide_automatic_options=False)80    app.add_url_rule(81        "/more",82        view_func=more,83        methods=["GET", "POST"],84        provide_automatic_options=False,85    )86    assert client.get("/").data == b"GET"8788    rv = client.post("/")89    assert rv.status_code == 40590    assert sorted(rv.allow) == ["GET", "HEAD"]9192    rv = client.open("/", method="OPTIONS")93    assert rv.status_code == 4059495    rv = client.head("/")96    assert rv.status_code == 20097    assert not rv.data  # head truncates98    assert client.post("/more").data == b"POST"99    assert client.get("/more").data == b"GET"100101    rv = client.delete("/more")102    assert rv.status_code == 405103    assert sorted(rv.allow) == ["GET", "HEAD", "POST"]104105    rv = client.open("/more", method="OPTIONS")106    assert rv.status_code == 405107108109def test_request_dispatching(app, client):110    @app.route("/")111    def index():112        return flask.request.method113114    @app.route("/more", methods=["GET", "POST"])115    def more():116        return flask.request.method117118    assert client.get("/").data == b"GET"119    rv = client.post("/")120    assert rv.status_code == 405121    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]122    rv = client.head("/")123    assert rv.status_code == 200124    assert not rv.data  # head truncates125    assert client.post("/more").data == b"POST"126    assert client.get("/more").data == b"GET"127    rv = client.delete("/more")128    assert rv.status_code == 405129    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]130131132def test_disallow_string_for_allowed_methods(app):133    with pytest.raises(TypeError):134135        @app.route("/", methods="GET POST")136        def index():137            return "Hey"138139140def test_url_mapping(app, client):141    random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"142143    def index():144        return flask.request.method145146    def more():147        return flask.request.method148149    def options():150        return random_uuid4151152    app.add_url_rule("/", "index", index)153    app.add_url_rule("/more", "more", more, methods=["GET", "POST"])154155    # Issue 1288: Test that automatic options are not added156    #             when non-uppercase 'options' in methods157    app.add_url_rule("/options", "options", options, methods=["options"])158159    assert client.get("/").data == b"GET"160    rv = client.post("/")161    assert rv.status_code == 405162    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]163    rv = client.head("/")164    assert rv.status_code == 200165    assert not rv.data  # head truncates166    assert client.post("/more").data == b"POST"167    assert client.get("/more").data == b"GET"168    rv = client.delete("/more")169    assert rv.status_code == 405170    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]171    rv = client.open("/options", method="OPTIONS")172    assert rv.status_code == 200173    assert random_uuid4 in rv.data.decode("utf-8")174175176def test_werkzeug_routing(app, client):177    from werkzeug.routing import Submount, Rule178179    app.url_map.add(180        Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])181    )182183    def bar():184        return "bar"185186    def index():187        return "index"188189    app.view_functions["bar"] = bar190    app.view_functions["index"] = index191192    assert client.get("/foo/").data == b"index"193    assert client.get("/foo/bar").data == b"bar"194195196def test_endpoint_decorator(app, client):197    from werkzeug.routing import Submount, Rule198199    app.url_map.add(200        Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])201    )202203    @app.endpoint("bar")204    def bar():205        return "bar"206207    @app.endpoint("index")208    def index():209        return "index"210211    assert client.get("/foo/").data == b"index"212    assert client.get("/foo/bar").data == b"bar"213214215def test_session(app, client):216    @app.route("/set", methods=["POST"])217    def set():218        assert not flask.session.accessed219        assert not flask.session.modified220        flask.session["value"] = flask.request.form["value"]221        assert flask.session.accessed222        assert flask.session.modified223        return "value set"224225    @app.route("/get")226    def get():227        assert not flask.session.accessed228        assert not flask.session.modified229        v = flask.session.get("value", "None")230        assert flask.session.accessed231        assert not flask.session.modified232        return v233234    assert client.post("/set", data={"value": "42"}).data == b"value set"235    assert client.get("/get").data == b"42"236237238def test_session_using_server_name(app, client):239    app.config.update(SERVER_NAME="example.com")240241    @app.route("/")242    def index():243        flask.session["testing"] = 42244        return "Hello World"245246    rv = client.get("/", "http://example.com/")247    assert "domain=.example.com" in rv.headers["set-cookie"].lower()248    assert "httponly" in rv.headers["set-cookie"].lower()249250251def test_session_using_server_name_and_port(app, client):252    app.config.update(SERVER_NAME="example.com:8080")253254    @app.route("/")255    def index():256        flask.session["testing"] = 42257        return "Hello World"258259    rv = client.get("/", "http://example.com:8080/")260    assert "domain=.example.com" in rv.headers["set-cookie"].lower()261    assert "httponly" in rv.headers["set-cookie"].lower()262263264def test_session_using_server_name_port_and_path(app, client):265    app.config.update(SERVER_NAME="example.com:8080", APPLICATION_ROOT="/foo")266267    @app.route("/")268    def index():269        flask.session["testing"] = 42270        return "Hello World"271272    rv = client.get("/", "http://example.com:8080/foo")273    assert "domain=example.com" in rv.headers["set-cookie"].lower()274    assert "path=/foo" in rv.headers["set-cookie"].lower()275    assert "httponly" in rv.headers["set-cookie"].lower()276277278def test_session_using_application_root(app, client):279    class PrefixPathMiddleware:280        def __init__(self, app, prefix):281            self.app = app282            self.prefix = prefix283284        def __call__(self, environ, start_response):285            environ["SCRIPT_NAME"] = self.prefix286            return self.app(environ, start_response)287288    app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, "/bar")289    app.config.update(APPLICATION_ROOT="/bar")290291    @app.route("/")292    def index():293        flask.session["testing"] = 42294        return "Hello World"295296    rv = client.get("/", "http://example.com:8080/")297    assert "path=/bar" in rv.headers["set-cookie"].lower()298299300def test_session_using_session_settings(app, client):301    app.config.update(302        SERVER_NAME="www.example.com:8080",303        APPLICATION_ROOT="/test",304        SESSION_COOKIE_DOMAIN=".example.com",305        SESSION_COOKIE_HTTPONLY=False,306        SESSION_COOKIE_SECURE=True,307        SESSION_COOKIE_SAMESITE="Lax",308        SESSION_COOKIE_PATH="/",309    )310311    @app.route("/")312    def index():313        flask.session["testing"] = 42314        return "Hello World"315316    rv = client.get("/", "http://www.example.com:8080/test/")317    cookie = rv.headers["set-cookie"].lower()318    assert "domain=.example.com" in cookie319    assert "path=/" in cookie320    assert "secure" in cookie321    assert "httponly" not in cookie322    assert "samesite" in cookie323324325def test_session_using_samesite_attribute(app, client):326    @app.route("/")327    def index():328        flask.session["testing"] = 42329        return "Hello World"330331    app.config.update(SESSION_COOKIE_SAMESITE="invalid")332333    with pytest.raises(ValueError):334        client.get("/")335336    app.config.update(SESSION_COOKIE_SAMESITE=None)337    rv = client.get("/")338    cookie = rv.headers["set-cookie"].lower()339    assert "samesite" not in cookie340341    app.config.update(SESSION_COOKIE_SAMESITE="Strict")342    rv = client.get("/")343    cookie = rv.headers["set-cookie"].lower()344    assert "samesite=strict" in cookie345346    app.config.update(SESSION_COOKIE_SAMESITE="Lax")347    rv = client.get("/")348    cookie = rv.headers["set-cookie"].lower()349    assert "samesite=lax" in cookie350351352def test_session_localhost_warning(recwarn, app, client):353    app.config.update(SERVER_NAME="localhost:5000")354355    @app.route("/")356    def index():357        flask.session["testing"] = 42358        return "testing"359360    rv = client.get("/", "http://localhost:5000/")361    assert "domain" not in rv.headers["set-cookie"].lower()362    w = recwarn.pop(UserWarning)363    assert "'localhost' is not a valid cookie domain" in str(w.message)364365366def test_session_ip_warning(recwarn, app, client):367    app.config.update(SERVER_NAME="127.0.0.1:5000")368369    @app.route("/")370    def index():371        flask.session["testing"] = 42372        return "testing"373374    rv = client.get("/", "http://127.0.0.1:5000/")375    assert "domain=127.0.0.1" in rv.headers["set-cookie"].lower()376    w = recwarn.pop(UserWarning)377    assert "cookie domain is an IP" in str(w.message)378379380def test_missing_session(app):381    app.secret_key = None382383    def expect_exception(f, *args, **kwargs):384        e = pytest.raises(RuntimeError, f, *args, **kwargs)385        assert e.value.args and "session is unavailable" in e.value.args[0]386387    with app.test_request_context():388        assert flask.session.get("missing_key") is None389        expect_exception(flask.session.__setitem__, "foo", 42)390        expect_exception(flask.session.pop, "foo")391392393def test_session_expiration(app, client):394    permanent = True395396    @app.route("/")397    def index():398        flask.session["test"] = 42399        flask.session.permanent = permanent400        return ""401402    @app.route("/test")403    def test():404        return str(flask.session.permanent)405406    rv = client.get("/")407    assert "set-cookie" in rv.headers408    match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])409    expires = parse_date(match.group())410    expected = datetime.utcnow() + app.permanent_session_lifetime411    assert expires.year == expected.year412    assert expires.month == expected.month413    assert expires.day == expected.day414415    rv = client.get("/test")416    assert rv.data == b"True"417418    permanent = False419    rv = client.get("/")420    assert "set-cookie" in rv.headers421    match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])422    assert match is None423424425def test_session_stored_last(app, client):426    @app.after_request427    def modify_session(response):428        flask.session["foo"] = 42429        return response430431    @app.route("/")432    def dump_session_contents():433        return repr(flask.session.get("foo"))434435    assert client.get("/").data == b"None"436    assert client.get("/").data == b"42"437438439def test_session_special_types(app, client):440    now = datetime.utcnow().replace(microsecond=0)441    the_uuid = uuid.uuid4()442443    @app.route("/")444    def dump_session_contents():445        flask.session["t"] = (1, 2, 3)446        flask.session["b"] = b"\xff"447        flask.session["m"] = flask.Markup("<html>")448        flask.session["u"] = the_uuid449        flask.session["d"] = now450        flask.session["t_tag"] = {" t": "not-a-tuple"}451        flask.session["di_t_tag"] = {" t__": "not-a-tuple"}452        flask.session["di_tag"] = {" di": "not-a-dict"}453        return "", 204454455    with client:456        client.get("/")457        s = flask.session458        assert s["t"] == (1, 2, 3)459        assert type(s["b"]) == bytes460        assert s["b"] == b"\xff"461        assert type(s["m"]) == flask.Markup462        assert s["m"] == flask.Markup("<html>")463        assert s["u"] == the_uuid464        assert s["d"] == now465        assert s["t_tag"] == {" t": "not-a-tuple"}466        assert s["di_t_tag"] == {" t__": "not-a-tuple"}467        assert s["di_tag"] == {" di": "not-a-dict"}468469470def test_session_cookie_setting(app):471    is_permanent = True472473    @app.route("/bump")474    def bump():475        rv = flask.session["foo"] = flask.session.get("foo", 0) + 1476        flask.session.permanent = is_permanent477        return str(rv)478479    @app.route("/read")480    def read():481        return str(flask.session.get("foo", 0))482483    def run_test(expect_header):484        with app.test_client() as c:485            assert c.get("/bump").data == b"1"486            assert c.get("/bump").data == b"2"487            assert c.get("/bump").data == b"3"488489            rv = c.get("/read")490            set_cookie = rv.headers.get("set-cookie")491            assert (set_cookie is not None) == expect_header492            assert rv.data == b"3"493494    is_permanent = True495    app.config["SESSION_REFRESH_EACH_REQUEST"] = True496    run_test(expect_header=True)497498    is_permanent = True499    app.config["SESSION_REFRESH_EACH_REQUEST"] = False500    run_test(expect_header=False)501502    is_permanent = False503    app.config["SESSION_REFRESH_EACH_REQUEST"] = True504    run_test(expect_header=False)505506    is_permanent = False507    app.config["SESSION_REFRESH_EACH_REQUEST"] = False508    run_test(expect_header=False)509510511def test_session_vary_cookie(app, client):512    @app.route("/set")513    def set_session():514        flask.session["test"] = "test"515        return ""516517    @app.route("/get")518    def get():519        return flask.session.get("test")520521    @app.route("/getitem")522    def getitem():523        return flask.session["test"]524525    @app.route("/setdefault")526    def setdefault():527        return flask.session.setdefault("test", "default")528529    @app.route("/vary-cookie-header-set")530    def vary_cookie_header_set():531        response = flask.Response()532        response.vary.add("Cookie")533        flask.session["test"] = "test"534        return response535536    @app.route("/vary-header-set")537    def vary_header_set():538        response = flask.Response()539        response.vary.update(("Accept-Encoding", "Accept-Language"))540        flask.session["test"] = "test"541        return response542543    @app.route("/no-vary-header")544    def no_vary_header():545        return ""546547    def expect(path, header_value="Cookie"):548        rv = client.get(path)549550        if header_value:551            # The 'Vary' key should exist in the headers only once.552            assert len(rv.headers.get_all("Vary")) == 1553            assert rv.headers["Vary"] == header_value554        else:555            assert "Vary" not in rv.headers556557    expect("/set")558    expect("/get")559    expect("/getitem")560    expect("/setdefault")561    expect("/vary-cookie-header-set")562    expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")563    expect("/no-vary-header", None)564565566def test_flashes(app, req_ctx):567    assert not flask.session.modified568    flask.flash("Zap")569    flask.session.modified = False570    flask.flash("Zip")571    assert flask.session.modified572    assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]573574575def test_extended_flashing(app):576    # Be sure app.testing=True below, else tests can fail silently.577    #578    # Specifically, if app.testing is not set to True, the AssertionErrors579    # in the view functions will cause a 500 response to the test client580    # instead of propagating exceptions.581582    @app.route("/")583    def index():584        flask.flash("Hello World")585        flask.flash("Hello World", "error")586        flask.flash(flask.Markup("<em>Testing</em>"), "warning")587        return ""588589    @app.route("/test/")590    def test():591        messages = flask.get_flashed_messages()592        assert list(messages) == [593            "Hello World",594            "Hello World",595            flask.Markup("<em>Testing</em>"),596        ]597        return ""598599    @app.route("/test_with_categories/")600    def test_with_categories():601        messages = flask.get_flashed_messages(with_categories=True)602        assert len(messages) == 3603        assert list(messages) == [604            ("message", "Hello World"),605            ("error", "Hello World"),606            ("warning", flask.Markup("<em>Testing</em>")),607        ]608        return ""609610    @app.route("/test_filter/")611    def test_filter():612        messages = flask.get_flashed_messages(613            category_filter=["message"], with_categories=True614        )615        assert list(messages) == [("message", "Hello World")]616        return ""617618    @app.route("/test_filters/")619    def test_filters():620        messages = flask.get_flashed_messages(621            category_filter=["message", "warning"], with_categories=True622        )623        assert list(messages) == [624            ("message", "Hello World"),625            ("warning", flask.Markup("<em>Testing</em>")),626        ]627        return ""628629    @app.route("/test_filters_without_returning_categories/")630    def test_filters2():631        messages = flask.get_flashed_messages(category_filter=["message", "warning"])632        assert len(messages) == 2633        assert messages[0] == "Hello World"634        assert messages[1] == flask.Markup("<em>Testing</em>")635        return ""636637    # Create new test client on each test to clean flashed messages.638639    client = app.test_client()640    client.get("/")641    client.get("/test_with_categories/")642643    client = app.test_client()644    client.get("/")645    client.get("/test_filter/")646647    client = app.test_client()648    client.get("/")649    client.get("/test_filters/")650651    client = app.test_client()652    client.get("/")653    client.get("/test_filters_without_returning_categories/")654655656def test_request_processing(app, client):657    evts = []658659    @app.before_request660    def before_request():661        evts.append("before")662663    @app.after_request664    def after_request(response):665        response.data += b"|after"666        evts.append("after")667        return response668669    @app.route("/")670    def index():671        assert "before" in evts672        assert "after" not in evts673        return "request"674675    assert "after" not in evts676    rv = client.get("/").data677    assert "after" in evts678    assert rv == b"request|after"679680681def test_request_preprocessing_early_return(app, client):682    evts = []683684    @app.before_request685    def before_request1():686        evts.append(1)687688    @app.before_request689    def before_request2():690        evts.append(2)691        return "hello"692693    @app.before_request694    def before_request3():695        evts.append(3)696        return "bye"697698    @app.route("/")699    def index():700        evts.append("index")701        return "damnit"702703    rv = client.get("/").data.strip()704    assert rv == b"hello"705    assert evts == [1, 2]706707708def test_after_request_processing(app, client):709    @app.route("/")710    def index():711        @flask.after_this_request712        def foo(response):713            response.headers["X-Foo"] = "a header"714            return response715716        return "Test"717718    resp = client.get("/")719    assert resp.status_code == 200720    assert resp.headers["X-Foo"] == "a header"721722723def test_teardown_request_handler(app, client):724    called = []725726    @app.teardown_request727    def teardown_request(exc):728        called.append(True)729        return "Ignored"730731    @app.route("/")732    def root():733        return "Response"734735    rv = client.get("/")736    assert rv.status_code == 200737    assert b"Response" in rv.data738    assert len(called) == 1739740741def test_teardown_request_handler_debug_mode(app, client):742    called = []743744    @app.teardown_request745    def teardown_request(exc):746        called.append(True)747        return "Ignored"748749    @app.route("/")750    def root():751        return "Response"752753    rv = client.get("/")754    assert rv.status_code == 200755    assert b"Response" in rv.data756    assert len(called) == 1757758759def test_teardown_request_handler_error(app, client):760    called = []761    app.testing = False762763    @app.teardown_request764    def teardown_request1(exc):765        assert type(exc) == ZeroDivisionError766        called.append(True)767        # This raises a new error and blows away sys.exc_info(), so we can768        # test that all teardown_requests get passed the same original769        # exception.770        try:771            raise TypeError()772        except Exception:773            pass774775    @app.teardown_request776    def teardown_request2(exc):777        assert type(exc) == ZeroDivisionError778        called.append(True)779        # This raises a new error and blows away sys.exc_info(), so we can780        # test that all teardown_requests get passed the same original781        # exception.782        try:783            raise TypeError()784        except Exception:785            pass786787    @app.route("/")788    def fails():789        1 // 0790791    rv = client.get("/")792    assert rv.status_code == 500793    assert b"Internal Server Error" in rv.data794    assert len(called) == 2795796797def test_before_after_request_order(app, client):798    called = []799800    @app.before_request801    def before1():802        called.append(1)803804    @app.before_request805    def before2():806        called.append(2)807808    @app.after_request809    def after1(response):810        called.append(4)811        return response812813    @app.after_request814    def after2(response):815        called.append(3)816        return response817818    @app.teardown_request819    def finish1(exc):820        called.append(6)821822    @app.teardown_request823    def finish2(exc):824        called.append(5)825826    @app.route("/")827    def index():828        return "42"829830    rv = client.get("/")831    assert rv.data == b"42"832    assert called == [1, 2, 3, 4, 5, 6]833834835def test_error_handling(app, client):836    app.testing = False837838    @app.errorhandler(404)839    def not_found(e):840        return "not found", 404841842    @app.errorhandler(500)843    def internal_server_error(e):844        return "internal server error", 500845846    @app.errorhandler(Forbidden)847    def forbidden(e):848        return "forbidden", 403849850    @app.route("/")851    def index():852        flask.abort(404)853854    @app.route("/error")855    def error():856        1 // 0857858    @app.route("/forbidden")859    def error2():860        flask.abort(403)861862    rv = client.get("/")863    assert rv.status_code == 404864    assert rv.data == b"not found"865    rv = client.get("/error")866    assert rv.status_code == 500867    assert b"internal server error" == rv.data868    rv = client.get("/forbidden")869    assert rv.status_code == 403870    assert b"forbidden" == rv.data871872873def test_error_handler_unknown_code(app):874    with pytest.raises(KeyError) as exc_info:875        app.register_error_handler(999, lambda e: ("999", 999))876877    assert "Use a subclass" in exc_info.value.args[0]878879880def test_error_handling_processing(app, client):881    app.testing = False882883    @app.errorhandler(500)884    def internal_server_error(e):885        return "internal server error", 500886887    @app.route("/")888    def broken_func():889        1 // 0890891    @app.after_request892    def after_request(resp):893        resp.mimetype = "text/x-special"894        return resp895896    resp = client.get("/")897    assert resp.mimetype == "text/x-special"898    assert resp.data == b"internal server error"899900901def test_baseexception_error_handling(app, client):902    app.testing = False903904    @app.route("/")905    def broken_func():906        raise KeyboardInterrupt()907908    with pytest.raises(KeyboardInterrupt):909        client.get("/")910911        ctx = flask._request_ctx_stack.top912        assert ctx.preserved913        assert type(ctx._preserved_exc) is KeyboardInterrupt914915916def test_before_request_and_routing_errors(app, client):917    @app.before_request918    def attach_something():919        flask.g.something = "value"920921    @app.errorhandler(404)922    def return_something(error):923        return flask.g.something, 404924925    rv = client.get("/")926    assert rv.status_code == 404927    assert rv.data == b"value"928929930def test_user_error_handling(app, client):931    class MyException(Exception):932        pass933934    @app.errorhandler(MyException)935    def handle_my_exception(e):936        assert isinstance(e, MyException)937        return "42"938939    @app.route("/")940    def index():941        raise MyException()942943    assert client.get("/").data == b"42"944945946def test_http_error_subclass_handling(app, client):947    class ForbiddenSubclass(Forbidden):948        pass949950    @app.errorhandler(ForbiddenSubclass)951    def handle_forbidden_subclass(e):952        assert isinstance(e, ForbiddenSubclass)953        return "banana"954955    @app.errorhandler(403)956    def handle_403(e):957        assert not isinstance(e, ForbiddenSubclass)958        assert isinstance(e, Forbidden)959        return "apple"960961    @app.route("/1")962    def index1():963        raise ForbiddenSubclass()964965    @app.route("/2")966    def index2():967        flask.abort(403)968969    @app.route("/3")970    def index3():971        raise Forbidden()972973    assert client.get("/1").data == b"banana"974    assert client.get("/2").data == b"apple"975    assert client.get("/3").data == b"apple"976977978def test_errorhandler_precedence(app, client):979    class E1(Exception):980        pass981982    class E2(Exception):983        pass984985    class E3(E1, E2):986        pass987988    @app.errorhandler(E2)989    def handle_e2(e):990        return "E2"991992    @app.errorhandler(Exception)993    def handle_exception(e):994        return "Exception"995996    @app.route("/E1")997    def raise_e1():998        raise E19991000    @app.route("/E3")1001    def raise_e3():1002        raise E310031004    rv = client.get("/E1")1005    assert rv.data == b"Exception"10061007    rv = client.get("/E3")1008    assert rv.data == b"E2"100910101011def test_trapping_of_bad_request_key_errors(app, client):1012    @app.route("/key")1013    def fail():1014        flask.request.form["missing_key"]10151016    @app.route("/abort")1017    def allow_abort():1018        flask.abort(400)10191020    rv = client.get("/key")1021    assert rv.status_code == 4001022    assert b"missing_key" not in rv.data1023    rv = client.get("/abort")1024    assert rv.status_code == 40010251026    app.debug = True1027    with pytest.raises(KeyError) as e:1028        client.get("/key")1029    assert e.errisinstance(BadRequest)1030    assert "missing_key" in e.value.get_description()1031    rv = client.get("/abort")1032    assert rv.status_code == 40010331034    app.debug = False1035    app.config["TRAP_BAD_REQUEST_ERRORS"] = True1036    with pytest.raises(KeyError):1037        client.get("/key")1038    with pytest.raises(BadRequest):1039        client.get("/abort")104010411042def test_trapping_of_all_http_exceptions(app, client):1043    app.config["TRAP_HTTP_EXCEPTIONS"] = True10441045    @app.route("/fail")1046    def fail():1047        flask.abort(404)10481049    with pytest.raises(NotFound):1050        client.get("/fail")105110521053def test_error_handler_after_processor_error(app, client):1054    app.testing = False10551056    @app.before_request1057    def before_request():1058        if _trigger == "before":1059            1 // 010601061    @app.after_request1062    def after_request(response):1063        if _trigger == "after":1064            1 // 01065        return response10661067    @app.route("/")1068    def index():1069        return "Foo"10701071    @app.errorhandler(500)1072    def internal_server_error(e):1073        return "Hello Server Error", 50010741075    for _trigger in "before", "after":1076        rv = client.get("/")1077        assert rv.status_code == 5001078        assert rv.data == b"Hello Server Error"107910801081def test_enctype_debug_helper(app, client):1082    from flask.debughelpers import DebugFilesKeyError10831084    app.debug = True10851086    @app.route("/fail", methods=["POST"])1087    def index():1088        return flask.request.files["foo"].filename10891090    # with statement is important because we leave an exception on the1091    # stack otherwise and we want to ensure that this is not the case1092    # to not negatively affect other tests.1093    with client:1094        with pytest.raises(DebugFilesKeyError) as e:1095            client.post("/fail", data={"foo": "index.txt"})1096        assert "no file contents were transmitted" in str(e.value)1097        assert "This was submitted: 'index.txt'" in str(e.value)109810991100def test_response_types(app, client):1101    @app.route("/text")1102    def from_text():1103        return "Hällo Wörld"11041105    @app.route("/bytes")1106    def from_bytes():1107        return "Hällo Wörld".encode()11081109    @app.route("/full_tuple")1110    def from_full_tuple():1111        return (1112            "Meh",1113            400,1114            {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1115        )11161117    @app.route("/text_headers")1118    def from_text_headers():1119        return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}11201121    @app.route("/text_status")1122    def from_text_status():1123        return "Hi, status!", 40011241125    @app.route("/response_headers")1126    def from_response_headers():1127        return (1128            flask.Response(1129                "Hello world", 404, {"Content-Type": "text/html", "X-Foo": "Baz"}1130            ),1131            {"Content-Type": "text/plain", "X-Foo": "Bar", "X-Bar": "Foo"},1132        )11331134    @app.route("/response_status")1135    def from_response_status():1136        return app.response_class("Hello world", 400), 50011371138    @app.route("/wsgi")1139    def from_wsgi():1140        return NotFound()11411142    @app.route("/dict")1143    def from_dict():1144        return {"foo": "bar"}, 20111451146    assert client.get("/text").data == "Hällo Wörld".encode()1147    assert client.get("/bytes").data == "Hällo Wörld".encode()11481149    rv = client.get("/full_tuple")1150    assert rv.data == b"Meh"1151    assert rv.headers["X-Foo"] == "Testing"1152    assert rv.status_code == 4001153    assert rv.mimetype == "text/plain"11541155    rv = client.get("/text_headers")1156    assert rv.data == b"Hello"1157    assert rv.headers["X-Foo"] == "Test"1158    assert rv.status_code == 2001159    assert rv.mimetype == "text/plain"11601161    rv = client.get("/text_status")1162    assert rv.data == b"Hi, status!"1163    assert rv.status_code == 4001164    assert rv.mimetype == "text/html"11651166    rv = client.get("/response_headers")1167    assert rv.data == b"Hello world"1168    assert rv.content_type == "text/plain"1169    assert rv.headers.getlist("X-Foo") == ["Bar"]1170    assert rv.headers["X-Bar"] == "Foo"1171    assert rv.status_code == 40411721173    rv = client.get("/response_status")1174    assert rv.data == b"Hello world"1175    assert rv.status_code == 50011761177    rv = client.get("/wsgi")1178    assert b"Not Found" in rv.data1179    assert rv.status_code == 40411801181    rv = client.get("/dict")1182    assert rv.json == {"foo": "bar"}1183    assert rv.status_code == 201118411851186def test_response_type_errors():1187    app = flask.Flask(__name__)1188    app.testing = True11891190    @app.route("/none")1191    def from_none():1192        pass11931194    @app.route("/small_tuple")1195    def from_small_tuple():1196        return ("Hello",)11971198    @app.route("/large_tuple")1199    def from_large_tuple():1200        return "Hello", 234, {"X-Foo": "Bar"}, "???"12011202    @app.route("/bad_type")1203    def from_bad_type():1204        return True12051206    @app.route("/bad_wsgi")1207    def from_bad_wsgi():1208        return lambda: None12091210    c = app.test_client()12111212    with pytest.raises(TypeError) as e:1213        c.get("/none")1214        assert "returned None" in str(e.value)1215        assert "from_none" in str(e.value)12161217    with pytest.raises(TypeError) as e:1218        c.get("/small_tuple")1219        assert "tuple must have the form" in str(e.value)12201221    pytest.raises(TypeError, c.get, "/large_tuple")12221223    with pytest.raises(TypeError) as e:1224        c.get("/bad_type")1225        assert "it was a bool" in str(e.value)12261227    pytest.raises(TypeError, c.get, "/bad_wsgi")122812291230def test_make_response(app, req_ctx):1231    rv = flask.make_response()1232    assert rv.status_code == 2001233    assert rv.data == b""1234    assert rv.mimetype == "text/html"12351236    rv = flask.make_response("Awesome")1237    assert rv.status_code == 2001238    assert rv.data == b"Awesome"1239    assert rv.mimetype == "text/html"12401241    rv = flask.make_response("W00t", 404)1242    assert rv.status_code == 4041243    assert rv.data == b"W00t"1244    assert rv.mimetype == "text/html"124512461247def test_make_response_with_response_instance(app, req_ctx):1248    rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1249    assert rv.status_code == 4001250    assert rv.data == b'{"msg":"W00t"}\n'1251    assert rv.mimetype == "application/json"12521253    rv = flask.make_response(flask.Response(""), 400)1254    assert rv.status_code == 4001255    assert rv.data == b""1256    assert rv.mimetype == "text/html"12571258    rv = flask.make_response(1259        flask.Response("", headers={"Content-Type": "text/html"}),1260        400,1261        [("X-Foo", "bar")],1262    )1263    assert rv.status_code == 4001264    assert rv.headers["Content-Type"] == "text/html"1265    assert rv.headers["X-Foo"] == "bar"126612671268def test_jsonify_no_prettyprint(app, req_ctx):1269    app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1270    compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1271    uncompressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}12721273    rv = flask.make_response(flask.jsonify(uncompressed_msg), 200)1274    assert rv.data == compressed_msg127512761277def test_jsonify_prettyprint(app, req_ctx):1278    app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1279    compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1280    pretty_response = (1281        b'{\n  "msg": {\n    "submsg": "W00t"\n  }, \n  "msg2": "foobar"\n}\n'1282    )12831284    rv = flask.make_response(flask.jsonify(compressed_msg), 200)1285    assert rv.data == pretty_response128612871288def test_jsonify_mimetype(app, req_ctx):1289    app.config.update({"JSONIFY_MIMETYPE": "application/vnd.api+json"})1290    msg = {"msg": {"submsg": "W00t"}}1291    rv = flask.make_response(flask.jsonify(msg), 200)1292    assert rv.mimetype == "application/vnd.api+json"129312941295@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")1296def test_json_dump_dataclass(app, req_ctx):1297    from dataclasses import make_dataclass12981299    Data = make_dataclass("Data", [("name", str)])1300    value = flask.json.dumps(Data("Flask"), app=app)1301    value = flask.json.loads(value, app=app)1302    assert value == {"name": "Flask"}130313041305def test_jsonify_args_and_kwargs_check(app, req_ctx):1306    with pytest.raises(TypeError) as e:1307        flask.jsonify("fake args", kwargs="fake")1308    assert "behavior undefined" in str(e.value)130913101311def test_url_generation(app, req_ctx):1312    @app.route("/hello/<name>", methods=["POST"])1313    def hello():1314        pass13151316    assert flask.url_for("hello", name="test x") == "/hello/test%20x"1317    assert (1318        flask.url_for("hello", name="test x", _external=True)1319        == "http://localhost/hello/test%20x"1320    )132113221323def test_build_error_handler(app):1324    # Test base case, a URL which results in a BuildError.1325    with app.test_request_context():1326        pytest.raises(BuildError, flask.url_for, "spam")13271328    # Verify the error is re-raised if not the current exception.1329    try:1330        with app.test_request_context():1331            flask.url_for("spam")1332    except BuildError as err:1333        error = err1334    try:1335        raise RuntimeError("Test case where BuildError is not current.")1336    except RuntimeError:1337        pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})13381339    # Test a custom handler.1340    def handler(error, endpoint, values):1341        # Just a test.1342        return "/test_handler/"13431344    app.url_build_error_handlers.append(handler)1345    with app.test_request_context():1346        assert flask.url_for("spam") == "/test_handler/"134713481349def test_build_error_handler_reraise(app):1350    # Test a custom handler which reraises the BuildError1351    def handler_raises_build_error(error, endpoint, values):1352        raise error13531354    app.url_build_error_handlers.append(handler_raises_build_error)13551356    with app.test_request_context():1357        pytest.raises(BuildError, flask.url_for, "not.existing")135813591360def test_url_for_passes_special_values_to_build_error_handler(app):1361    @app.url_build_error_handlers.append1362    def handler(error, endpoint, values):1363        assert values == {1364            "_external": False,1365            "_anchor": None,1366            "_method": None,1367            "_scheme": None,1368        }1369        return "handled"13701371    with app.test_request_context():1372        flask.url_for("/")137313741375def test_static_files(app, client):1376    rv = client.get("/static/index.html")1377    assert rv.status_code == 2001378    assert rv.data.strip() == b"<h1>Hello World!</h1>"1379    with app.test_request_context():1380        assert flask.url_for("static", filename="index.html") == "/static/index.html"1381    rv.close()138213831384def test_static_url_path():1385    app = flask.Flask(__name__, static_url_path="/foo")1386    app.testing = True1387    rv = app.test_client().get("/foo/index.html")1388    assert rv.status_code == 2001389    rv.close()13901391    with app.test_request_context():1392        assert flask.url_for("static", filename="index.html") == "/foo/index.html"139313941395def test_static_url_path_with_ending_slash():1396    app = flask.Flask(__name__, static_url_path="/foo/")1397    app.testing = True1398    rv = app.test_client().get("/foo/index.html")1399    assert rv.status_code == 2001400    rv.close()14011402    with app.test_request_context():1403        assert flask.url_for("static", filename="index.html") == "/foo/index.html"140414051406def test_static_url_empty_path(app):1407    app = flask.Flask(__name__, static_folder="", static_url_path="")1408    rv = app.test_client().open("/static/index.html", method="GET")1409    assert rv.status_code == 2001410    rv.close()141114121413def test_static_url_empty_path_default(app):1414    app = flask.Flask(__name__, static_folder="")1415    rv = app.test_client().open("/static/index.html", method="GET")1416    assert rv.status_code == 2001417    rv.close()141814191420@pytest.mark.skipif(sys.version_info < (3, 6), reason="requires Python >= 3.6")1421def test_static_folder_with_pathlib_path(app):1422    from pathlib import Path14231424    app = flask.Flask(__name__, static_folder=Path("static"))1425    rv = app.test_client().open("/static/index.html", method="GET")1426    assert rv.status_code == 2001427    rv.close()142814291430def test_static_folder_with_ending_slash():1431    app = flask.Flask(__name__, static_folder="static/")14321433    @app.route("/<path:path>")1434    def catch_all(path):1435        return path14361437    rv = app.test_client().get("/catch/all")1438    assert rv.data == b"catch/all"143914401441def test_static_route_with_host_matching():1442    app = flask.Flask(__name__, host_matching=True, static_host="example.com")1443    c = app.test_client()1444    rv = c.get("http://example.com/static/index.html")1445    assert rv.status_code == 2001446    rv.close()1447    with app.test_request_context():1448        rv = flask.url_for("static", filename="index.html", _external=True)1449        assert rv == "http://example.com/static/index.html"1450    # Providing static_host without host_matching=True should error.1451    with pytest.raises(Exception):1452        flask.Flask(__name__, static_host="example.com")1453    # Providing host_matching=True with static_folder1454    # but without static_host should error.1455    with pytest.raises(Exception):1456        flask.Flask(__name__, host_matching=True)1457    # Providing host_matching=True without static_host1458    # but with static_folder=None should not error.1459    flask.Flask(__name__, host_matching=True, static_folder=None)146014611462def test_request_locals():1463    assert repr(flask.g) == "<LocalProxy unbound>"1464    assert not flask.g146514661467def test_server_name_subdomain():1468    app = flask.Flask(__name__, subdomain_matching=True)1469    client = app.test_client()14701471    @app.route("/")1472    def index():1473        return "default"14741475    @app.route("/", subdomain="foo")1476    def subdomain():1477        return "subdomain"14781479    app.config["SERVER_NAME"] = "dev.local:5000"1480    rv = client.get("/")1481    assert rv.data == b"default"14821483    rv = client.get("/", "http://dev.local:5000")1484    assert rv.data == b"default"14851486    rv = client.get("/", "https://dev.local:5000")1487    assert rv.data == b"default"14881489    app.config["SERVER_NAME"] = "dev.local:443"1490    rv = client.get("/", "https://dev.local")14911492    # Werkzeug 1.0 fixes matching https scheme with 443 port1493    if rv.status_code != 404:1494        assert rv.data == b"default"14951496    app.config["SERVER_NAME"] = "dev.local"1497    rv = client.get("/", "https://dev.local")1498    assert rv.data == b"default"14991500    # suppress Werkzeug 1.0 warning about name mismatch1501    with pytest.warns(None):1502        rv = client.get("/", "http://foo.localhost")1503        assert rv.status_code == 40415041505    rv = client.get("/", "http://foo.dev.local")1506    assert rv.data == b"subdomain"150715081509def test_exception_propagation(app, client):1510    def apprunner(config_key):1511        @app.route("/")1512        def index():1513            1 // 015141515        if config_key is not None:1516            app.config[config_key] = True1517            with pytest.raises(Exception):1518                client.get("/")1519        else:1520            assert client.get("/").status_code == 50015211522    # we have to run this test in an isolated thread because if the1523    # debug flag is set to true and an exception happens the context is1524    # not torn down.  This causes other tests that run after this fail1525    # when they expect no exception on the stack.1526    for config_key in "TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None:1527        t = Thread(target=apprunner, args=(config_key,))1528        t.start()1529        t.join()153015311532@pytest.mark.parametrize("debug", [True, False])1533@pytest.mark.parametrize("use_debugger", [True, False])1534@pytest.mark.parametrize("use_reloader", [True, False])1535@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1536def test_werkzeug_passthrough_errors(1537    monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1538):1539    rv = {}15401541    # Mocks werkzeug.serving.run_simple method1542    def run_simple_mock(*args, **kwargs):1543        rv["passthrough_errors"] = kwargs.get("passthrough_errors")15441545    monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1546    app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1547    app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)154815491550def test_max_content_length(app, client):1551    app.config["MAX_CONTENT_LENGTH"] = 6415521553    @app.before_request1554    def always_first():1555        flask.request.form["myfile"]1556        AssertionError()15571558    @app.route("/accept", methods=["POST"])1559    def accept_file():1560        flask.request.form["myfile"]1561        AssertionError()15621563    @app.errorhandler(413)1564    def catcher(error):1565        return "42"15661567    rv = client.post("/accept", data={"myfile": "foo" * 100})1568    assert rv.data == b"42"156915701571def test_url_processors(app, client):1572    @app.url_defaults1573    def add_language_code(endpoint, values):1574        if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1575            endpoint, "lang_code"1576        ):1577            values.setdefault("lang_code", flask.g.lang_code)15781579    @app.url_value_preprocessor1580    def pull_lang_code(endpoint, values):1581        flask.g.lang_code = values.pop("lang_code", None)15821583    @app.route("/<lang_code>/")1584    def index():1585        return flask.url_for("about")15861587    @app.route("/<lang_code>/about")1588    def about():1589        return flask.url_for("something_else")15901591    @app.route("/foo")1592    def something_else():1593        return flask.url_for("about", lang_code="en")15941595    assert client.get("/de/").data == b"/de/about"1596    assert client.get("/de/about").data == b"/foo"1597    assert client.get("/foo").data == b"/en/about"159815991600def test_inject_blueprint_url_defaults(app):1601    bp = flask.Blueprint("foo.bar.baz", __name__, template_folder="template")16021603    @bp.url_defaults1604    def bp_defaults(endpoint, values):1605        values["page"] = "login"16061607    @bp.route("/<page>")1608    def view(page):1609        pass16101611    app.register_blueprint(bp)16121613    values = dict()1614    app.inject_url_defaults("foo.bar.baz.view", values)1615    expected = dict(page="login")1616    assert values == expected16171618    with app.test_request_context("/somepage"):1619        url = flask.url_for("foo.bar.baz.view")1620    expected = "/login"1621    assert url == expected162216231624def test_nonascii_pathinfo(app, client):1625    @app.route("/киртест")1626    def index():1627        return "Hello World!"16281629    rv = client.get("/киртест")1630    assert rv.data == b"Hello World!"163116321633def test_debug_mode_complains_after_first_request(app, client):1634    app.debug = True16351636    @app.route("/")1637    def index():1638        return "Awesome"16391640    assert not app.got_first_request1641    assert client.get("/").data == b"Awesome"1642    with pytest.raises(AssertionError) as e:16431644        @app.route("/foo")1645        def broken():1646            return "Meh"16471648    assert "A setup function was called" in str(e.value)16491650    app.debug = False16511652    @app.route("/foo")1653    def working():1654        return "Meh"16551656    assert client.get("/foo").data == b"Meh"1657    assert app.got_first_request165816591660def test_before_first_request_functions(app, client):1661    got = []16621663    @app.before_first_request1664    def foo():1665        got.append(42)16661667    client.get("/")1668    assert got == [42]1669    client.get("/")1670    assert got == [42]1671    assert app.got_first_request167216731674def test_before_first_request_functions_concurrent(app, client):1675    got = []16761677    @app.before_first_request1678    def foo():1679        time.sleep(0.2)1680        got.append(42)16811682    def get_and_assert():1683        client.get("/")1684        assert got == [42]16851686    t = Thread(target=get_and_assert)1687    t.start()1688    get_and_assert()1689    t.join()1690    assert app.got_first_request169116921693def test_routing_redirect_debugging(app, client):1694    app.debug = True16951696    @app.route("/foo/", methods=["GET", "POST"])1697    def foo():1698        return "success"16991700    with client:1701        with pytest.raises(AssertionError) as e:1702            client.post("/foo", data={})1703        assert "http://localhost/foo/" in str(e.value)1704        assert "Make sure to directly send your POST-request to this URL" in str(1705            e.value1706        )17071708        rv = client.get("/foo", data={}, follow_redirects=True)1709        assert rv.data == b"success"17101711    app.debug = False1712    with client:1713        rv = client.post("/foo", data={}, follow_redirects=True)1714        assert rv.data == b"success"171517161717def test_route_decorator_custom_endpoint(app, client):1718    app.debug = True17191720    @app.route("/foo/")1721    def foo():1722        return flask.request.endpoint17231724    @app.route("/bar/", endpoint="bar")1725    def for_bar():1726        return flask.request.endpoint17271728    @app.route("/bar/123", endpoint="123")1729    def for_bar_foo():1730        return flask.request.endpoint17311732    with app.test_request_context():1733        assert flask.url_for("foo") == "/foo/"1734        assert flask.url_for("bar") == "/bar/"1735        assert flask.url_for("123") == "/bar/123"17361737    assert client.get("/foo/").data == b"foo"1738    assert client.get("/bar/").data == b"bar"1739    assert client.get("/bar/123").data == b"123"174017411742def test_preserve_only_once(app, client):1743    app.debug = True17441745    @app.route("/fail")1746    def fail_func():1747        1 // 017481749    for _x in range(3):1750        with pytest.raises(ZeroDivisionError):1751            client.get("/fail")17521753    assert flask._request_ctx_stack.top is not None1754    assert flask._app_ctx_stack.top is not None1755    # implicit appctx disappears too1756    flask._request_ctx_stack.top.pop()1757    assert flask._request_ctx_stack.top is None1758    assert flask._app_ctx_stack.top is None175917601761def test_preserve_remembers_exception(app, client):1762    app.debug = True1763    errors = []17641765    @app.route("/fail")1766    def fail_func():1767        1 // 017681769    @app.route("/success")1770    def success_func():1771        return "Okay"17721773    @app.teardown_request1774    def teardown_handler(exc):1775        errors.append(exc)17761777    # After this failure we did not yet call the teardown handler1778    with pytest.raises(ZeroDivisionError):1779        client.get("/fail")1780    assert errors == []17811782    # But this request triggers it, and it's an error1783    client.get("/success")1784    assert len(errors) == 21785    assert isinstance(errors[0], ZeroDivisionError)17861787    # At this point another request does nothing.1788    client.get("/success")1789    assert len(errors) == 31790    assert errors[1] is None179117921793def test_get_method_on_g(app_ctx):1794    assert flask.g.get("x") is None1795    assert flask.g.get("x", 11) == 111796    flask.g.x = 421797    assert flask.g.get("x") == 421798    assert flask.g.x == 42179918001801def test_g_iteration_protocol(app_ctx):1802    flask.g.foo = 231803    flask.g.bar = 421804    assert "foo" in flask.g1805    assert "foos" not in flask.g1806    assert sorted(flask.g) == ["bar", "foo"]180718081809def test_subdomain_basic_support():1810    app = flask.Flask(__name__, subdomain_matching=True)1811    app.config["SERVER_NAME"] = "localhost.localdomain"1812    client = app.test_client()18131814    @app.route("/")1815    def normal_index():1816        return "normal index"18171818    @app.route("/", subdomain="test")1819    def test_index():1820        return "test index"18211822    rv = client.get("/", "http://localhost.localdomain/")1823    assert rv.data == b"normal index"18241825    rv = client.get("/", "http://test.localhost.localdomain/")1826    assert rv.data == b"test index"182718281829def test_subdomain_matching():1830    app = flask.Flask(__name__, subdomain_matching=True)1831    client = app.test_client()1832    app.config["SERVER_NAME"] = "localhost.localdomain"18331834    @app.route("/", subdomain="<user>")1835    def index(user):1836        return f"index for {user}"18371838    rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1839    assert rv.data == b"index for mitsuhiko"184018411842def test_subdomain_matching_with_ports():1843    app = flask.Flask(__name__, subdomain_matching=True)1844    app.config["SERVER_NAME"] = "localhost.localdomain:3000"1845    client = app.test_client()18461847    @app.route("/", subdomain="<user>")1848    def index(user):1849        return f"index for {user}"18501851    rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1852    assert rv.data == b"index for mitsuhiko"185318541855@pytest.mark.parametrize("matching", (False, True))1856def test_subdomain_matching_other_name(matching):1857    app = flask.Flask(__name__, subdomain_matching=matching)1858    app.config["SERVER_NAME"] = "localhost.localdomain:3000"1859    client = app.test_client()18601861    @app.route("/")1862    def index():1863        return "", 20418641865    # suppress Werkzeug 0.15 warning about name mismatch1866    with pytest.warns(None):1867        # ip address can't match name1868        rv = client.get("/", "http://127.0.0.1:3000/")1869        assert rv.status_code == 404 if matching else 20418701871    # allow all subdomains if matching is disabled1872    rv = client.get("/", "http://www.localhost.localdomain:3000/")1873    assert rv.status_code == 404 if matching else 204187418751876def test_multi_route_rules(app, client):1877    @app.route("/")1878    @app.route("/<test>/")1879    def index(test="a"):1880        return test18811882    rv = client.open("/")1883    assert rv.data == b"a"1884    rv = client.open("/b/")1885    assert rv.data == b"b"188618871888def test_multi_route_class_views(app, client):1889    class View:1890        def __init__(self, app):1891            app.add_url_rule("/", "index", self.index)1892            app.add_url_rule("/<test>/", "index", self.index)18931894        def index(self, test="a"):1895            return test18961897    _ = View(app)1898    rv = client.open("/")1899    assert rv.data == b"a"1900    rv = client.open("/b/")1901    assert rv.data == b"b"190219031904def test_run_defaults(monkeypatch, app):1905    rv = {}19061907    # Mocks werkzeug.serving.run_simple method1908    def run_simple_mock(*args, **kwargs):1909        rv["result"] = "running..."19101911    monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1912    app.run()1913    assert rv["result"] == "running..."191419151916def test_run_server_port(monkeypatch, app):1917    rv = {}19181919    # Mocks werkzeug.serving.run_simple method1920    def run_simple_mock(hostname, port, application, *args, **kwargs):1921        rv["result"] = f"running on {hostname}:{port} ..."19221923    monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1924    hostname, port = "localhost", 80001925    app.run(hostname, port, debug=True)1926    assert rv["result"] == f"running on {hostname}:{port} ..."192719281929@pytest.mark.parametrize(1930    "host,port,server_name,expect_host,expect_port",1931    (1932        (None, None, "pocoo.org:8080", "pocoo.org", 8080),1933        ("localhost", None, "pocoo.org:8080", "localhost", 8080),1934        (None, 80, "pocoo.org:8080", "pocoo.org", 80),1935        ("localhost", 80, "pocoo.org:8080", "localhost", 80),1936        ("localhost", 0, "localhost:8080", "localhost", 0),1937        (None, None, "localhost:8080", "localhost", 8080),1938        (None, None, "localhost:0", "localhost", 0),1939    ),1940)1941def test_run_from_config(1942    monkeypatch, host, port, server_name, expect_host, expect_port, app1943):1944    def run_simple_mock(hostname, port, *args, **kwargs):1945        assert hostname == expect_host1946        assert port == expect_port19471948    monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1949    app.config["SERVER_NAME"] = server_name1950    app.run(host, port)195119521953def test_max_cookie_size(app, client, recwarn):1954    app.config["MAX_COOKIE_SIZE"] = 10019551956    # outside app context, default to Werkzeug static value,1957    # which is also the default config1958    response = flask.Response()1959    default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1960    assert response.max_cookie_size == default19611962    # inside app context, use app config1963    with app.app_context():1964        assert flask.Response().max_cookie_size == 10019651966    @app.route("/")1967    def index():1968        r = flask.Response("", status=204)1969        r.set_cookie("foo", "bar" * 100)1970        return r19711972    client.get("/")1973    assert len(recwarn) == 11974    w = recwarn.pop()1975    assert "cookie is too large" in str(w.message)19761977    app.config["MAX_COOKIE_SIZE"] = 019781979    client.get("/")1980    assert len(recwarn) == 0198119821983@require_cpython_gc1984def test_app_freed_on_zero_refcount():1985    # A Flask instance should not create a reference cycle that prevents CPython1986    # from freeing it when all external references to it are released (see #3761).1987    gc.disable()1988    try:1989        app = flask.Flask(__name__)1990        assert app.view_functions["static"]1991        weak = weakref.ref(app)1992        assert weak() is not None1993        del app1994        assert weak() is None1995    finally:1996        gc.enable()