Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

2,028 lines · 54.5 KiB · Python

Last changed by

Merge branch '2.0.x'David Lordbefore adoption636f195

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",24    reason="Requires CPython GC behavior",25)262728def test_options_work(app, client):29    @app.route("/", methods=["GET", "POST"])30    def index():31        return "Hello World"3233    rv = client.open("/", method="OPTIONS")34    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]35    assert rv.data == b""363738def test_options_on_multiple_rules(app, client):39    @app.route("/", methods=["GET", "POST"])40    def index():41        return "Hello World"4243    @app.route("/", methods=["PUT"])44    def index_put():45        return "Aha!"4647    rv = client.open("/", method="OPTIONS")48    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST", "PUT"]495051@pytest.mark.parametrize("method", ["get", "post", "put", "delete", "patch"])52def test_method_route(app, client, method):53    method_route = getattr(app, method)54    client_method = getattr(client, method)5556    @method_route("/")57    def hello():58        return "Hello"5960    assert client_method("/").data == b"Hello"616263def test_method_route_no_methods(app):64    with pytest.raises(TypeError):65        app.get("/", methods=["GET", "POST"])666768def test_provide_automatic_options_attr():69    app = flask.Flask(__name__)7071    def index():72        return "Hello World!"7374    index.provide_automatic_options = False75    app.route("/")(index)76    rv = app.test_client().open("/", method="OPTIONS")77    assert rv.status_code == 4057879    app = flask.Flask(__name__)8081    def index2():82        return "Hello World!"8384    index2.provide_automatic_options = True85    app.route("/", methods=["OPTIONS"])(index2)86    rv = app.test_client().open("/", method="OPTIONS")87    assert sorted(rv.allow) == ["OPTIONS"]888990def test_provide_automatic_options_kwarg(app, client):91    def index():92        return flask.request.method9394    def more():95        return flask.request.method9697    app.add_url_rule("/", view_func=index, provide_automatic_options=False)98    app.add_url_rule(99        "/more",100        view_func=more,101        methods=["GET", "POST"],102        provide_automatic_options=False,103    )104    assert client.get("/").data == b"GET"105106    rv = client.post("/")107    assert rv.status_code == 405108    assert sorted(rv.allow) == ["GET", "HEAD"]109110    rv = client.open("/", method="OPTIONS")111    assert rv.status_code == 405112113    rv = client.head("/")114    assert rv.status_code == 200115    assert not rv.data  # head truncates116    assert client.post("/more").data == b"POST"117    assert client.get("/more").data == b"GET"118119    rv = client.delete("/more")120    assert rv.status_code == 405121    assert sorted(rv.allow) == ["GET", "HEAD", "POST"]122123    rv = client.open("/more", method="OPTIONS")124    assert rv.status_code == 405125126127def test_request_dispatching(app, client):128    @app.route("/")129    def index():130        return flask.request.method131132    @app.route("/more", methods=["GET", "POST"])133    def more():134        return flask.request.method135136    assert client.get("/").data == b"GET"137    rv = client.post("/")138    assert rv.status_code == 405139    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]140    rv = client.head("/")141    assert rv.status_code == 200142    assert not rv.data  # head truncates143    assert client.post("/more").data == b"POST"144    assert client.get("/more").data == b"GET"145    rv = client.delete("/more")146    assert rv.status_code == 405147    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]148149150def test_disallow_string_for_allowed_methods(app):151    with pytest.raises(TypeError):152153        @app.route("/", methods="GET POST")154        def index():155            return "Hey"156157158def test_url_mapping(app, client):159    random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"160161    def index():162        return flask.request.method163164    def more():165        return flask.request.method166167    def options():168        return random_uuid4169170    app.add_url_rule("/", "index", index)171    app.add_url_rule("/more", "more", more, methods=["GET", "POST"])172173    # Issue 1288: Test that automatic options are not added174    #             when non-uppercase 'options' in methods175    app.add_url_rule("/options", "options", options, methods=["options"])176177    assert client.get("/").data == b"GET"178    rv = client.post("/")179    assert rv.status_code == 405180    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]181    rv = client.head("/")182    assert rv.status_code == 200183    assert not rv.data  # head truncates184    assert client.post("/more").data == b"POST"185    assert client.get("/more").data == b"GET"186    rv = client.delete("/more")187    assert rv.status_code == 405188    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]189    rv = client.open("/options", method="OPTIONS")190    assert rv.status_code == 200191    assert random_uuid4 in rv.data.decode("utf-8")192193194def test_werkzeug_routing(app, client):195    from werkzeug.routing import Submount, Rule196197    app.url_map.add(198        Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])199    )200201    def bar():202        return "bar"203204    def index():205        return "index"206207    app.view_functions["bar"] = bar208    app.view_functions["index"] = index209210    assert client.get("/foo/").data == b"index"211    assert client.get("/foo/bar").data == b"bar"212213214def test_endpoint_decorator(app, client):215    from werkzeug.routing import Submount, Rule216217    app.url_map.add(218        Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])219    )220221    @app.endpoint("bar")222    def bar():223        return "bar"224225    @app.endpoint("index")226    def index():227        return "index"228229    assert client.get("/foo/").data == b"index"230    assert client.get("/foo/bar").data == b"bar"231232233def test_session(app, client):234    @app.route("/set", methods=["POST"])235    def set():236        assert not flask.session.accessed237        assert not flask.session.modified238        flask.session["value"] = flask.request.form["value"]239        assert flask.session.accessed240        assert flask.session.modified241        return "value set"242243    @app.route("/get")244    def get():245        assert not flask.session.accessed246        assert not flask.session.modified247        v = flask.session.get("value", "None")248        assert flask.session.accessed249        assert not flask.session.modified250        return v251252    assert client.post("/set", data={"value": "42"}).data == b"value set"253    assert client.get("/get").data == b"42"254255256def test_session_using_server_name(app, client):257    app.config.update(SERVER_NAME="example.com")258259    @app.route("/")260    def index():261        flask.session["testing"] = 42262        return "Hello World"263264    rv = client.get("/", "http://example.com/")265    assert "domain=.example.com" in rv.headers["set-cookie"].lower()266    assert "httponly" in rv.headers["set-cookie"].lower()267268269def test_session_using_server_name_and_port(app, client):270    app.config.update(SERVER_NAME="example.com:8080")271272    @app.route("/")273    def index():274        flask.session["testing"] = 42275        return "Hello World"276277    rv = client.get("/", "http://example.com:8080/")278    assert "domain=.example.com" in rv.headers["set-cookie"].lower()279    assert "httponly" in rv.headers["set-cookie"].lower()280281282def test_session_using_server_name_port_and_path(app, client):283    app.config.update(SERVER_NAME="example.com:8080", APPLICATION_ROOT="/foo")284285    @app.route("/")286    def index():287        flask.session["testing"] = 42288        return "Hello World"289290    rv = client.get("/", "http://example.com:8080/foo")291    assert "domain=example.com" in rv.headers["set-cookie"].lower()292    assert "path=/foo" in rv.headers["set-cookie"].lower()293    assert "httponly" in rv.headers["set-cookie"].lower()294295296def test_session_using_application_root(app, client):297    class PrefixPathMiddleware:298        def __init__(self, app, prefix):299            self.app = app300            self.prefix = prefix301302        def __call__(self, environ, start_response):303            environ["SCRIPT_NAME"] = self.prefix304            return self.app(environ, start_response)305306    app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, "/bar")307    app.config.update(APPLICATION_ROOT="/bar")308309    @app.route("/")310    def index():311        flask.session["testing"] = 42312        return "Hello World"313314    rv = client.get("/", "http://example.com:8080/")315    assert "path=/bar" in rv.headers["set-cookie"].lower()316317318def test_session_using_session_settings(app, client):319    app.config.update(320        SERVER_NAME="www.example.com:8080",321        APPLICATION_ROOT="/test",322        SESSION_COOKIE_DOMAIN=".example.com",323        SESSION_COOKIE_HTTPONLY=False,324        SESSION_COOKIE_SECURE=True,325        SESSION_COOKIE_SAMESITE="Lax",326        SESSION_COOKIE_PATH="/",327    )328329    @app.route("/")330    def index():331        flask.session["testing"] = 42332        return "Hello World"333334    rv = client.get("/", "http://www.example.com:8080/test/")335    cookie = rv.headers["set-cookie"].lower()336    assert "domain=.example.com" in cookie337    assert "path=/" in cookie338    assert "secure" in cookie339    assert "httponly" not in cookie340    assert "samesite" in cookie341342    @app.route("/clear")343    def clear():344        flask.session.pop("testing", None)345        return "Goodbye World"346347    rv = client.get("/clear", "http://www.example.com:8080/test/")348    cookie = rv.headers["set-cookie"].lower()349    assert "session=;" in cookie350    assert "domain=.example.com" in cookie351    assert "path=/" in cookie352    assert "secure" in cookie353    assert "samesite" in cookie354355356def test_session_using_samesite_attribute(app, client):357    @app.route("/")358    def index():359        flask.session["testing"] = 42360        return "Hello World"361362    app.config.update(SESSION_COOKIE_SAMESITE="invalid")363364    with pytest.raises(ValueError):365        client.get("/")366367    app.config.update(SESSION_COOKIE_SAMESITE=None)368    rv = client.get("/")369    cookie = rv.headers["set-cookie"].lower()370    assert "samesite" not in cookie371372    app.config.update(SESSION_COOKIE_SAMESITE="Strict")373    rv = client.get("/")374    cookie = rv.headers["set-cookie"].lower()375    assert "samesite=strict" in cookie376377    app.config.update(SESSION_COOKIE_SAMESITE="Lax")378    rv = client.get("/")379    cookie = rv.headers["set-cookie"].lower()380    assert "samesite=lax" in cookie381382383def test_session_localhost_warning(recwarn, app, client):384    app.config.update(SERVER_NAME="localhost:5000")385386    @app.route("/")387    def index():388        flask.session["testing"] = 42389        return "testing"390391    rv = client.get("/", "http://localhost:5000/")392    assert "domain" not in rv.headers["set-cookie"].lower()393    w = recwarn.pop(UserWarning)394    assert "'localhost' is not a valid cookie domain" in str(w.message)395396397def test_session_ip_warning(recwarn, app, client):398    app.config.update(SERVER_NAME="127.0.0.1:5000")399400    @app.route("/")401    def index():402        flask.session["testing"] = 42403        return "testing"404405    rv = client.get("/", "http://127.0.0.1:5000/")406    assert "domain=127.0.0.1" in rv.headers["set-cookie"].lower()407    w = recwarn.pop(UserWarning)408    assert "cookie domain is an IP" in str(w.message)409410411def test_missing_session(app):412    app.secret_key = None413414    def expect_exception(f, *args, **kwargs):415        e = pytest.raises(RuntimeError, f, *args, **kwargs)416        assert e.value.args and "session is unavailable" in e.value.args[0]417418    with app.test_request_context():419        assert flask.session.get("missing_key") is None420        expect_exception(flask.session.__setitem__, "foo", 42)421        expect_exception(flask.session.pop, "foo")422423424def test_session_expiration(app, client):425    permanent = True426427    @app.route("/")428    def index():429        flask.session["test"] = 42430        flask.session.permanent = permanent431        return ""432433    @app.route("/test")434    def test():435        return str(flask.session.permanent)436437    rv = client.get("/")438    assert "set-cookie" in rv.headers439    match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])440    expires = parse_date(match.group())441    expected = datetime.utcnow() + app.permanent_session_lifetime442    assert expires.year == expected.year443    assert expires.month == expected.month444    assert expires.day == expected.day445446    rv = client.get("/test")447    assert rv.data == b"True"448449    permanent = False450    rv = client.get("/")451    assert "set-cookie" in rv.headers452    match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])453    assert match is None454455456def test_session_stored_last(app, client):457    @app.after_request458    def modify_session(response):459        flask.session["foo"] = 42460        return response461462    @app.route("/")463    def dump_session_contents():464        return repr(flask.session.get("foo"))465466    assert client.get("/").data == b"None"467    assert client.get("/").data == b"42"468469470def test_session_special_types(app, client):471    now = datetime.utcnow().replace(microsecond=0)472    the_uuid = uuid.uuid4()473474    @app.route("/")475    def dump_session_contents():476        flask.session["t"] = (1, 2, 3)477        flask.session["b"] = b"\xff"478        flask.session["m"] = flask.Markup("<html>")479        flask.session["u"] = the_uuid480        flask.session["d"] = now481        flask.session["t_tag"] = {" t": "not-a-tuple"}482        flask.session["di_t_tag"] = {" t__": "not-a-tuple"}483        flask.session["di_tag"] = {" di": "not-a-dict"}484        return "", 204485486    with client:487        client.get("/")488        s = flask.session489        assert s["t"] == (1, 2, 3)490        assert type(s["b"]) == bytes491        assert s["b"] == b"\xff"492        assert type(s["m"]) == flask.Markup493        assert s["m"] == flask.Markup("<html>")494        assert s["u"] == the_uuid495        assert s["d"] == now496        assert s["t_tag"] == {" t": "not-a-tuple"}497        assert s["di_t_tag"] == {" t__": "not-a-tuple"}498        assert s["di_tag"] == {" di": "not-a-dict"}499500501def test_session_cookie_setting(app):502    is_permanent = True503504    @app.route("/bump")505    def bump():506        rv = flask.session["foo"] = flask.session.get("foo", 0) + 1507        flask.session.permanent = is_permanent508        return str(rv)509510    @app.route("/read")511    def read():512        return str(flask.session.get("foo", 0))513514    def run_test(expect_header):515        with app.test_client() as c:516            assert c.get("/bump").data == b"1"517            assert c.get("/bump").data == b"2"518            assert c.get("/bump").data == b"3"519520            rv = c.get("/read")521            set_cookie = rv.headers.get("set-cookie")522            assert (set_cookie is not None) == expect_header523            assert rv.data == b"3"524525    is_permanent = True526    app.config["SESSION_REFRESH_EACH_REQUEST"] = True527    run_test(expect_header=True)528529    is_permanent = True530    app.config["SESSION_REFRESH_EACH_REQUEST"] = False531    run_test(expect_header=False)532533    is_permanent = False534    app.config["SESSION_REFRESH_EACH_REQUEST"] = True535    run_test(expect_header=False)536537    is_permanent = False538    app.config["SESSION_REFRESH_EACH_REQUEST"] = False539    run_test(expect_header=False)540541542def test_session_vary_cookie(app, client):543    @app.route("/set")544    def set_session():545        flask.session["test"] = "test"546        return ""547548    @app.route("/get")549    def get():550        return flask.session.get("test")551552    @app.route("/getitem")553    def getitem():554        return flask.session["test"]555556    @app.route("/setdefault")557    def setdefault():558        return flask.session.setdefault("test", "default")559560    @app.route("/vary-cookie-header-set")561    def vary_cookie_header_set():562        response = flask.Response()563        response.vary.add("Cookie")564        flask.session["test"] = "test"565        return response566567    @app.route("/vary-header-set")568    def vary_header_set():569        response = flask.Response()570        response.vary.update(("Accept-Encoding", "Accept-Language"))571        flask.session["test"] = "test"572        return response573574    @app.route("/no-vary-header")575    def no_vary_header():576        return ""577578    def expect(path, header_value="Cookie"):579        rv = client.get(path)580581        if header_value:582            # The 'Vary' key should exist in the headers only once.583            assert len(rv.headers.get_all("Vary")) == 1584            assert rv.headers["Vary"] == header_value585        else:586            assert "Vary" not in rv.headers587588    expect("/set")589    expect("/get")590    expect("/getitem")591    expect("/setdefault")592    expect("/vary-cookie-header-set")593    expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")594    expect("/no-vary-header", None)595596597def test_flashes(app, req_ctx):598    assert not flask.session.modified599    flask.flash("Zap")600    flask.session.modified = False601    flask.flash("Zip")602    assert flask.session.modified603    assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]604605606def test_extended_flashing(app):607    # Be sure app.testing=True below, else tests can fail silently.608    #609    # Specifically, if app.testing is not set to True, the AssertionErrors610    # in the view functions will cause a 500 response to the test client611    # instead of propagating exceptions.612613    @app.route("/")614    def index():615        flask.flash("Hello World")616        flask.flash("Hello World", "error")617        flask.flash(flask.Markup("<em>Testing</em>"), "warning")618        return ""619620    @app.route("/test/")621    def test():622        messages = flask.get_flashed_messages()623        assert list(messages) == [624            "Hello World",625            "Hello World",626            flask.Markup("<em>Testing</em>"),627        ]628        return ""629630    @app.route("/test_with_categories/")631    def test_with_categories():632        messages = flask.get_flashed_messages(with_categories=True)633        assert len(messages) == 3634        assert list(messages) == [635            ("message", "Hello World"),636            ("error", "Hello World"),637            ("warning", flask.Markup("<em>Testing</em>")),638        ]639        return ""640641    @app.route("/test_filter/")642    def test_filter():643        messages = flask.get_flashed_messages(644            category_filter=["message"], with_categories=True645        )646        assert list(messages) == [("message", "Hello World")]647        return ""648649    @app.route("/test_filters/")650    def test_filters():651        messages = flask.get_flashed_messages(652            category_filter=["message", "warning"], with_categories=True653        )654        assert list(messages) == [655            ("message", "Hello World"),656            ("warning", flask.Markup("<em>Testing</em>")),657        ]658        return ""659660    @app.route("/test_filters_without_returning_categories/")661    def test_filters2():662        messages = flask.get_flashed_messages(category_filter=["message", "warning"])663        assert len(messages) == 2664        assert messages[0] == "Hello World"665        assert messages[1] == flask.Markup("<em>Testing</em>")666        return ""667668    # Create new test client on each test to clean flashed messages.669670    client = app.test_client()671    client.get("/")672    client.get("/test_with_categories/")673674    client = app.test_client()675    client.get("/")676    client.get("/test_filter/")677678    client = app.test_client()679    client.get("/")680    client.get("/test_filters/")681682    client = app.test_client()683    client.get("/")684    client.get("/test_filters_without_returning_categories/")685686687def test_request_processing(app, client):688    evts = []689690    @app.before_request691    def before_request():692        evts.append("before")693694    @app.after_request695    def after_request(response):696        response.data += b"|after"697        evts.append("after")698        return response699700    @app.route("/")701    def index():702        assert "before" in evts703        assert "after" not in evts704        return "request"705706    assert "after" not in evts707    rv = client.get("/").data708    assert "after" in evts709    assert rv == b"request|after"710711712def test_request_preprocessing_early_return(app, client):713    evts = []714715    @app.before_request716    def before_request1():717        evts.append(1)718719    @app.before_request720    def before_request2():721        evts.append(2)722        return "hello"723724    @app.before_request725    def before_request3():726        evts.append(3)727        return "bye"728729    @app.route("/")730    def index():731        evts.append("index")732        return "damnit"733734    rv = client.get("/").data.strip()735    assert rv == b"hello"736    assert evts == [1, 2]737738739def test_after_request_processing(app, client):740    @app.route("/")741    def index():742        @flask.after_this_request743        def foo(response):744            response.headers["X-Foo"] = "a header"745            return response746747        return "Test"748749    resp = client.get("/")750    assert resp.status_code == 200751    assert resp.headers["X-Foo"] == "a header"752753754def test_teardown_request_handler(app, client):755    called = []756757    @app.teardown_request758    def teardown_request(exc):759        called.append(True)760        return "Ignored"761762    @app.route("/")763    def root():764        return "Response"765766    rv = client.get("/")767    assert rv.status_code == 200768    assert b"Response" in rv.data769    assert len(called) == 1770771772def test_teardown_request_handler_debug_mode(app, client):773    called = []774775    @app.teardown_request776    def teardown_request(exc):777        called.append(True)778        return "Ignored"779780    @app.route("/")781    def root():782        return "Response"783784    rv = client.get("/")785    assert rv.status_code == 200786    assert b"Response" in rv.data787    assert len(called) == 1788789790def test_teardown_request_handler_error(app, client):791    called = []792    app.testing = False793794    @app.teardown_request795    def teardown_request1(exc):796        assert type(exc) == ZeroDivisionError797        called.append(True)798        # This raises a new error and blows away sys.exc_info(), so we can799        # test that all teardown_requests get passed the same original800        # exception.801        try:802            raise TypeError()803        except Exception:804            pass805806    @app.teardown_request807    def teardown_request2(exc):808        assert type(exc) == ZeroDivisionError809        called.append(True)810        # This raises a new error and blows away sys.exc_info(), so we can811        # test that all teardown_requests get passed the same original812        # exception.813        try:814            raise TypeError()815        except Exception:816            pass817818    @app.route("/")819    def fails():820        1 // 0821822    rv = client.get("/")823    assert rv.status_code == 500824    assert b"Internal Server Error" in rv.data825    assert len(called) == 2826827828def test_before_after_request_order(app, client):829    called = []830831    @app.before_request832    def before1():833        called.append(1)834835    @app.before_request836    def before2():837        called.append(2)838839    @app.after_request840    def after1(response):841        called.append(4)842        return response843844    @app.after_request845    def after2(response):846        called.append(3)847        return response848849    @app.teardown_request850    def finish1(exc):851        called.append(6)852853    @app.teardown_request854    def finish2(exc):855        called.append(5)856857    @app.route("/")858    def index():859        return "42"860861    rv = client.get("/")862    assert rv.data == b"42"863    assert called == [1, 2, 3, 4, 5, 6]864865866def test_error_handling(app, client):867    app.testing = False868869    @app.errorhandler(404)870    def not_found(e):871        return "not found", 404872873    @app.errorhandler(500)874    def internal_server_error(e):875        return "internal server error", 500876877    @app.errorhandler(Forbidden)878    def forbidden(e):879        return "forbidden", 403880881    @app.route("/")882    def index():883        flask.abort(404)884885    @app.route("/error")886    def error():887        1 // 0888889    @app.route("/forbidden")890    def error2():891        flask.abort(403)892893    rv = client.get("/")894    assert rv.status_code == 404895    assert rv.data == b"not found"896    rv = client.get("/error")897    assert rv.status_code == 500898    assert b"internal server error" == rv.data899    rv = client.get("/forbidden")900    assert rv.status_code == 403901    assert b"forbidden" == rv.data902903904def test_error_handler_unknown_code(app):905    with pytest.raises(KeyError) as exc_info:906        app.register_error_handler(999, lambda e: ("999", 999))907908    assert "Use a subclass" in exc_info.value.args[0]909910911def test_error_handling_processing(app, client):912    app.testing = False913914    @app.errorhandler(500)915    def internal_server_error(e):916        return "internal server error", 500917918    @app.route("/")919    def broken_func():920        1 // 0921922    @app.after_request923    def after_request(resp):924        resp.mimetype = "text/x-special"925        return resp926927    resp = client.get("/")928    assert resp.mimetype == "text/x-special"929    assert resp.data == b"internal server error"930931932def test_baseexception_error_handling(app, client):933    app.testing = False934935    @app.route("/")936    def broken_func():937        raise KeyboardInterrupt()938939    with pytest.raises(KeyboardInterrupt):940        client.get("/")941942        ctx = flask._request_ctx_stack.top943        assert ctx.preserved944        assert type(ctx._preserved_exc) is KeyboardInterrupt945946947def test_before_request_and_routing_errors(app, client):948    @app.before_request949    def attach_something():950        flask.g.something = "value"951952    @app.errorhandler(404)953    def return_something(error):954        return flask.g.something, 404955956    rv = client.get("/")957    assert rv.status_code == 404958    assert rv.data == b"value"959960961def test_user_error_handling(app, client):962    class MyException(Exception):963        pass964965    @app.errorhandler(MyException)966    def handle_my_exception(e):967        assert isinstance(e, MyException)968        return "42"969970    @app.route("/")971    def index():972        raise MyException()973974    assert client.get("/").data == b"42"975976977def test_http_error_subclass_handling(app, client):978    class ForbiddenSubclass(Forbidden):979        pass980981    @app.errorhandler(ForbiddenSubclass)982    def handle_forbidden_subclass(e):983        assert isinstance(e, ForbiddenSubclass)984        return "banana"985986    @app.errorhandler(403)987    def handle_403(e):988        assert not isinstance(e, ForbiddenSubclass)989        assert isinstance(e, Forbidden)990        return "apple"991992    @app.route("/1")993    def index1():994        raise ForbiddenSubclass()995996    @app.route("/2")997    def index2():998        flask.abort(403)9991000    @app.route("/3")1001    def index3():1002        raise Forbidden()10031004    assert client.get("/1").data == b"banana"1005    assert client.get("/2").data == b"apple"1006    assert client.get("/3").data == b"apple"100710081009def test_errorhandler_precedence(app, client):1010    class E1(Exception):1011        pass10121013    class E2(Exception):1014        pass10151016    class E3(E1, E2):1017        pass10181019    @app.errorhandler(E2)1020    def handle_e2(e):1021        return "E2"10221023    @app.errorhandler(Exception)1024    def handle_exception(e):1025        return "Exception"10261027    @app.route("/E1")1028    def raise_e1():1029        raise E110301031    @app.route("/E3")1032    def raise_e3():1033        raise E310341035    rv = client.get("/E1")1036    assert rv.data == b"Exception"10371038    rv = client.get("/E3")1039    assert rv.data == b"E2"104010411042def test_trapping_of_bad_request_key_errors(app, client):1043    @app.route("/key")1044    def fail():1045        flask.request.form["missing_key"]10461047    @app.route("/abort")1048    def allow_abort():1049        flask.abort(400)10501051    rv = client.get("/key")1052    assert rv.status_code == 4001053    assert b"missing_key" not in rv.data1054    rv = client.get("/abort")1055    assert rv.status_code == 40010561057    app.debug = True1058    with pytest.raises(KeyError) as e:1059        client.get("/key")1060    assert e.errisinstance(BadRequest)1061    assert "missing_key" in e.value.get_description()1062    rv = client.get("/abort")1063    assert rv.status_code == 40010641065    app.debug = False1066    app.config["TRAP_BAD_REQUEST_ERRORS"] = True1067    with pytest.raises(KeyError):1068        client.get("/key")1069    with pytest.raises(BadRequest):1070        client.get("/abort")107110721073def test_trapping_of_all_http_exceptions(app, client):1074    app.config["TRAP_HTTP_EXCEPTIONS"] = True10751076    @app.route("/fail")1077    def fail():1078        flask.abort(404)10791080    with pytest.raises(NotFound):1081        client.get("/fail")108210831084def test_error_handler_after_processor_error(app, client):1085    app.testing = False10861087    @app.before_request1088    def before_request():1089        if _trigger == "before":1090            1 // 010911092    @app.after_request1093    def after_request(response):1094        if _trigger == "after":1095            1 // 01096        return response10971098    @app.route("/")1099    def index():1100        return "Foo"11011102    @app.errorhandler(500)1103    def internal_server_error(e):1104        return "Hello Server Error", 50011051106    for _trigger in "before", "after":1107        rv = client.get("/")1108        assert rv.status_code == 5001109        assert rv.data == b"Hello Server Error"111011111112def test_enctype_debug_helper(app, client):1113    from flask.debughelpers import DebugFilesKeyError11141115    app.debug = True11161117    @app.route("/fail", methods=["POST"])1118    def index():1119        return flask.request.files["foo"].filename11201121    # with statement is important because we leave an exception on the1122    # stack otherwise and we want to ensure that this is not the case1123    # to not negatively affect other tests.1124    with client:1125        with pytest.raises(DebugFilesKeyError) as e:1126            client.post("/fail", data={"foo": "index.txt"})1127        assert "no file contents were transmitted" in str(e.value)1128        assert "This was submitted: 'index.txt'" in str(e.value)112911301131def test_response_types(app, client):1132    @app.route("/text")1133    def from_text():1134        return "Hällo Wörld"11351136    @app.route("/bytes")1137    def from_bytes():1138        return "Hällo Wörld".encode()11391140    @app.route("/full_tuple")1141    def from_full_tuple():1142        return (1143            "Meh",1144            400,1145            {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1146        )11471148    @app.route("/text_headers")1149    def from_text_headers():1150        return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}11511152    @app.route("/text_status")1153    def from_text_status():1154        return "Hi, status!", 40011551156    @app.route("/response_headers")1157    def from_response_headers():1158        return (1159            flask.Response(1160                "Hello world", 404, {"Content-Type": "text/html", "X-Foo": "Baz"}1161            ),1162            {"Content-Type": "text/plain", "X-Foo": "Bar", "X-Bar": "Foo"},1163        )11641165    @app.route("/response_status")1166    def from_response_status():1167        return app.response_class("Hello world", 400), 50011681169    @app.route("/wsgi")1170    def from_wsgi():1171        return NotFound()11721173    @app.route("/dict")1174    def from_dict():1175        return {"foo": "bar"}, 20111761177    assert client.get("/text").data == "Hällo Wörld".encode()1178    assert client.get("/bytes").data == "Hällo Wörld".encode()11791180    rv = client.get("/full_tuple")1181    assert rv.data == b"Meh"1182    assert rv.headers["X-Foo"] == "Testing"1183    assert rv.status_code == 4001184    assert rv.mimetype == "text/plain"11851186    rv = client.get("/text_headers")1187    assert rv.data == b"Hello"1188    assert rv.headers["X-Foo"] == "Test"1189    assert rv.status_code == 2001190    assert rv.mimetype == "text/plain"11911192    rv = client.get("/text_status")1193    assert rv.data == b"Hi, status!"1194    assert rv.status_code == 4001195    assert rv.mimetype == "text/html"11961197    rv = client.get("/response_headers")1198    assert rv.data == b"Hello world"1199    assert rv.content_type == "text/plain"1200    assert rv.headers.getlist("X-Foo") == ["Bar"]1201    assert rv.headers["X-Bar"] == "Foo"1202    assert rv.status_code == 40412031204    rv = client.get("/response_status")1205    assert rv.data == b"Hello world"1206    assert rv.status_code == 50012071208    rv = client.get("/wsgi")1209    assert b"Not Found" in rv.data1210    assert rv.status_code == 40412111212    rv = client.get("/dict")1213    assert rv.json == {"foo": "bar"}1214    assert rv.status_code == 201121512161217def test_response_type_errors():1218    app = flask.Flask(__name__)1219    app.testing = True12201221    @app.route("/none")1222    def from_none():1223        pass12241225    @app.route("/small_tuple")1226    def from_small_tuple():1227        return ("Hello",)12281229    @app.route("/large_tuple")1230    def from_large_tuple():1231        return "Hello", 234, {"X-Foo": "Bar"}, "???"12321233    @app.route("/bad_type")1234    def from_bad_type():1235        return True12361237    @app.route("/bad_wsgi")1238    def from_bad_wsgi():1239        return lambda: None12401241    c = app.test_client()12421243    with pytest.raises(TypeError) as e:1244        c.get("/none")1245        assert "returned None" in str(e.value)1246        assert "from_none" in str(e.value)12471248    with pytest.raises(TypeError) as e:1249        c.get("/small_tuple")1250        assert "tuple must have the form" in str(e.value)12511252    pytest.raises(TypeError, c.get, "/large_tuple")12531254    with pytest.raises(TypeError) as e:1255        c.get("/bad_type")1256        assert "it was a bool" in str(e.value)12571258    pytest.raises(TypeError, c.get, "/bad_wsgi")125912601261def test_make_response(app, req_ctx):1262    rv = flask.make_response()1263    assert rv.status_code == 2001264    assert rv.data == b""1265    assert rv.mimetype == "text/html"12661267    rv = flask.make_response("Awesome")1268    assert rv.status_code == 2001269    assert rv.data == b"Awesome"1270    assert rv.mimetype == "text/html"12711272    rv = flask.make_response("W00t", 404)1273    assert rv.status_code == 4041274    assert rv.data == b"W00t"1275    assert rv.mimetype == "text/html"127612771278def test_make_response_with_response_instance(app, req_ctx):1279    rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1280    assert rv.status_code == 4001281    assert rv.data == b'{"msg":"W00t"}\n'1282    assert rv.mimetype == "application/json"12831284    rv = flask.make_response(flask.Response(""), 400)1285    assert rv.status_code == 4001286    assert rv.data == b""1287    assert rv.mimetype == "text/html"12881289    rv = flask.make_response(1290        flask.Response("", headers={"Content-Type": "text/html"}),1291        400,1292        [("X-Foo", "bar")],1293    )1294    assert rv.status_code == 4001295    assert rv.headers["Content-Type"] == "text/html"1296    assert rv.headers["X-Foo"] == "bar"129712981299def test_jsonify_no_prettyprint(app, req_ctx):1300    app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1301    compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1302    uncompressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}13031304    rv = flask.make_response(flask.jsonify(uncompressed_msg), 200)1305    assert rv.data == compressed_msg130613071308def test_jsonify_prettyprint(app, req_ctx):1309    app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1310    compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1311    pretty_response = (1312        b'{\n  "msg": {\n    "submsg": "W00t"\n  }, \n  "msg2": "foobar"\n}\n'1313    )13141315    rv = flask.make_response(flask.jsonify(compressed_msg), 200)1316    assert rv.data == pretty_response131713181319def test_jsonify_mimetype(app, req_ctx):1320    app.config.update({"JSONIFY_MIMETYPE": "application/vnd.api+json"})1321    msg = {"msg": {"submsg": "W00t"}}1322    rv = flask.make_response(flask.jsonify(msg), 200)1323    assert rv.mimetype == "application/vnd.api+json"132413251326@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")1327def test_json_dump_dataclass(app, req_ctx):1328    from dataclasses import make_dataclass13291330    Data = make_dataclass("Data", [("name", str)])1331    value = flask.json.dumps(Data("Flask"), app=app)1332    value = flask.json.loads(value, app=app)1333    assert value == {"name": "Flask"}133413351336def test_jsonify_args_and_kwargs_check(app, req_ctx):1337    with pytest.raises(TypeError) as e:1338        flask.jsonify("fake args", kwargs="fake")1339    assert "behavior undefined" in str(e.value)134013411342def test_url_generation(app, req_ctx):1343    @app.route("/hello/<name>", methods=["POST"])1344    def hello():1345        pass13461347    assert flask.url_for("hello", name="test x") == "/hello/test%20x"1348    assert (1349        flask.url_for("hello", name="test x", _external=True)1350        == "http://localhost/hello/test%20x"1351    )135213531354def test_build_error_handler(app):1355    # Test base case, a URL which results in a BuildError.1356    with app.test_request_context():1357        pytest.raises(BuildError, flask.url_for, "spam")13581359    # Verify the error is re-raised if not the current exception.1360    try:1361        with app.test_request_context():1362            flask.url_for("spam")1363    except BuildError as err:1364        error = err1365    try:1366        raise RuntimeError("Test case where BuildError is not current.")1367    except RuntimeError:1368        pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})13691370    # Test a custom handler.1371    def handler(error, endpoint, values):1372        # Just a test.1373        return "/test_handler/"13741375    app.url_build_error_handlers.append(handler)1376    with app.test_request_context():1377        assert flask.url_for("spam") == "/test_handler/"137813791380def test_build_error_handler_reraise(app):1381    # Test a custom handler which reraises the BuildError1382    def handler_raises_build_error(error, endpoint, values):1383        raise error13841385    app.url_build_error_handlers.append(handler_raises_build_error)13861387    with app.test_request_context():1388        pytest.raises(BuildError, flask.url_for, "not.existing")138913901391def test_url_for_passes_special_values_to_build_error_handler(app):1392    @app.url_build_error_handlers.append1393    def handler(error, endpoint, values):1394        assert values == {1395            "_external": False,1396            "_anchor": None,1397            "_method": None,1398            "_scheme": None,1399        }1400        return "handled"14011402    with app.test_request_context():1403        flask.url_for("/")140414051406def test_static_files(app, client):1407    rv = client.get("/static/index.html")1408    assert rv.status_code == 2001409    assert rv.data.strip() == b"<h1>Hello World!</h1>"1410    with app.test_request_context():1411        assert flask.url_for("static", filename="index.html") == "/static/index.html"1412    rv.close()141314141415def test_static_url_path():1416    app = flask.Flask(__name__, static_url_path="/foo")1417    app.testing = True1418    rv = app.test_client().get("/foo/index.html")1419    assert rv.status_code == 2001420    rv.close()14211422    with app.test_request_context():1423        assert flask.url_for("static", filename="index.html") == "/foo/index.html"142414251426def test_static_url_path_with_ending_slash():1427    app = flask.Flask(__name__, static_url_path="/foo/")1428    app.testing = True1429    rv = app.test_client().get("/foo/index.html")1430    assert rv.status_code == 2001431    rv.close()14321433    with app.test_request_context():1434        assert flask.url_for("static", filename="index.html") == "/foo/index.html"143514361437def test_static_url_empty_path(app):1438    app = flask.Flask(__name__, static_folder="", static_url_path="")1439    rv = app.test_client().open("/static/index.html", method="GET")1440    assert rv.status_code == 2001441    rv.close()144214431444def test_static_url_empty_path_default(app):1445    app = flask.Flask(__name__, static_folder="")1446    rv = app.test_client().open("/static/index.html", method="GET")1447    assert rv.status_code == 2001448    rv.close()144914501451def test_static_folder_with_pathlib_path(app):1452    from pathlib import Path14531454    app = flask.Flask(__name__, static_folder=Path("static"))1455    rv = app.test_client().open("/static/index.html", method="GET")1456    assert rv.status_code == 2001457    rv.close()145814591460def test_static_folder_with_ending_slash():1461    app = flask.Flask(__name__, static_folder="static/")14621463    @app.route("/<path:path>")1464    def catch_all(path):1465        return path14661467    rv = app.test_client().get("/catch/all")1468    assert rv.data == b"catch/all"146914701471def test_static_route_with_host_matching():1472    app = flask.Flask(__name__, host_matching=True, static_host="example.com")1473    c = app.test_client()1474    rv = c.get("http://example.com/static/index.html")1475    assert rv.status_code == 2001476    rv.close()1477    with app.test_request_context():1478        rv = flask.url_for("static", filename="index.html", _external=True)1479        assert rv == "http://example.com/static/index.html"1480    # Providing static_host without host_matching=True should error.1481    with pytest.raises(Exception):1482        flask.Flask(__name__, static_host="example.com")1483    # Providing host_matching=True with static_folder1484    # but without static_host should error.1485    with pytest.raises(Exception):1486        flask.Flask(__name__, host_matching=True)1487    # Providing host_matching=True without static_host1488    # but with static_folder=None should not error.1489    flask.Flask(__name__, host_matching=True, static_folder=None)149014911492def test_request_locals():1493    assert repr(flask.g) == "<LocalProxy unbound>"1494    assert not flask.g149514961497def test_server_name_subdomain():1498    app = flask.Flask(__name__, subdomain_matching=True)1499    client = app.test_client()15001501    @app.route("/")1502    def index():1503        return "default"15041505    @app.route("/", subdomain="foo")1506    def subdomain():1507        return "subdomain"15081509    app.config["SERVER_NAME"] = "dev.local:5000"1510    rv = client.get("/")1511    assert rv.data == b"default"15121513    rv = client.get("/", "http://dev.local:5000")1514    assert rv.data == b"default"15151516    rv = client.get("/", "https://dev.local:5000")1517    assert rv.data == b"default"15181519    app.config["SERVER_NAME"] = "dev.local:443"1520    rv = client.get("/", "https://dev.local")15211522    # Werkzeug 1.0 fixes matching https scheme with 443 port1523    if rv.status_code != 404:1524        assert rv.data == b"default"15251526    app.config["SERVER_NAME"] = "dev.local"1527    rv = client.get("/", "https://dev.local")1528    assert rv.data == b"default"15291530    # suppress Werkzeug 1.0 warning about name mismatch1531    with pytest.warns(None):1532        rv = client.get("/", "http://foo.localhost")1533        assert rv.status_code == 40415341535    rv = client.get("/", "http://foo.dev.local")1536    assert rv.data == b"subdomain"153715381539@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning")1540@pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning")1541def test_exception_propagation(app, client):1542    def apprunner(config_key):1543        @app.route("/")1544        def index():1545            1 // 015461547        if config_key is not None:1548            app.config[config_key] = True1549            with pytest.raises(Exception):1550                client.get("/")1551        else:1552            assert client.get("/").status_code == 50015531554    # we have to run this test in an isolated thread because if the1555    # debug flag is set to true and an exception happens the context is1556    # not torn down.  This causes other tests that run after this fail1557    # when they expect no exception on the stack.1558    for config_key in "TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None:1559        t = Thread(target=apprunner, args=(config_key,))1560        t.start()1561        t.join()156215631564@pytest.mark.parametrize("debug", [True, False])1565@pytest.mark.parametrize("use_debugger", [True, False])1566@pytest.mark.parametrize("use_reloader", [True, False])1567@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1568def test_werkzeug_passthrough_errors(1569    monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1570):1571    rv = {}15721573    # Mocks werkzeug.serving.run_simple method1574    def run_simple_mock(*args, **kwargs):1575        rv["passthrough_errors"] = kwargs.get("passthrough_errors")15761577    monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1578    app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1579    app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)158015811582def test_max_content_length(app, client):1583    app.config["MAX_CONTENT_LENGTH"] = 6415841585    @app.before_request1586    def always_first():1587        flask.request.form["myfile"]1588        AssertionError()15891590    @app.route("/accept", methods=["POST"])1591    def accept_file():1592        flask.request.form["myfile"]1593        AssertionError()15941595    @app.errorhandler(413)1596    def catcher(error):1597        return "42"15981599    rv = client.post("/accept", data={"myfile": "foo" * 100})1600    assert rv.data == b"42"160116021603def test_url_processors(app, client):1604    @app.url_defaults1605    def add_language_code(endpoint, values):1606        if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1607            endpoint, "lang_code"1608        ):1609            values.setdefault("lang_code", flask.g.lang_code)16101611    @app.url_value_preprocessor1612    def pull_lang_code(endpoint, values):1613        flask.g.lang_code = values.pop("lang_code", None)16141615    @app.route("/<lang_code>/")1616    def index():1617        return flask.url_for("about")16181619    @app.route("/<lang_code>/about")1620    def about():1621        return flask.url_for("something_else")16221623    @app.route("/foo")1624    def something_else():1625        return flask.url_for("about", lang_code="en")16261627    assert client.get("/de/").data == b"/de/about"1628    assert client.get("/de/about").data == b"/foo"1629    assert client.get("/foo").data == b"/en/about"163016311632def test_inject_blueprint_url_defaults(app):1633    bp = flask.Blueprint("foo", __name__, template_folder="template")16341635    @bp.url_defaults1636    def bp_defaults(endpoint, values):1637        values["page"] = "login"16381639    @bp.route("/<page>")1640    def view(page):1641        pass16421643    app.register_blueprint(bp)16441645    values = dict()1646    app.inject_url_defaults("foo.view", values)1647    expected = dict(page="login")1648    assert values == expected16491650    with app.test_request_context("/somepage"):1651        url = flask.url_for("foo.view")1652    expected = "/login"1653    assert url == expected165416551656def test_nonascii_pathinfo(app, client):1657    @app.route("/киртест")1658    def index():1659        return "Hello World!"16601661    rv = client.get("/киртест")1662    assert rv.data == b"Hello World!"166316641665def test_debug_mode_complains_after_first_request(app, client):1666    app.debug = True16671668    @app.route("/")1669    def index():1670        return "Awesome"16711672    assert not app.got_first_request1673    assert client.get("/").data == b"Awesome"1674    with pytest.raises(AssertionError) as e:16751676        @app.route("/foo")1677        def broken():1678            return "Meh"16791680    assert "A setup function was called" in str(e.value)16811682    app.debug = False16831684    @app.route("/foo")1685    def working():1686        return "Meh"16871688    assert client.get("/foo").data == b"Meh"1689    assert app.got_first_request169016911692def test_before_first_request_functions(app, client):1693    got = []16941695    @app.before_first_request1696    def foo():1697        got.append(42)16981699    client.get("/")1700    assert got == [42]1701    client.get("/")1702    assert got == [42]1703    assert app.got_first_request170417051706def test_before_first_request_functions_concurrent(app, client):1707    got = []17081709    @app.before_first_request1710    def foo():1711        time.sleep(0.2)1712        got.append(42)17131714    def get_and_assert():1715        client.get("/")1716        assert got == [42]17171718    t = Thread(target=get_and_assert)1719    t.start()1720    get_and_assert()1721    t.join()1722    assert app.got_first_request172317241725def test_routing_redirect_debugging(app, client):1726    app.debug = True17271728    @app.route("/foo/", methods=["GET", "POST"])1729    def foo():1730        return "success"17311732    with client:1733        with pytest.raises(AssertionError) as e:1734            client.post("/foo", data={})1735        assert "http://localhost/foo/" in str(e.value)1736        assert "Make sure to directly send your POST-request to this URL" in str(1737            e.value1738        )17391740        rv = client.get("/foo", data={}, follow_redirects=True)1741        assert rv.data == b"success"17421743    app.debug = False1744    with client:1745        rv = client.post("/foo", data={}, follow_redirects=True)1746        assert rv.data == b"success"174717481749def test_route_decorator_custom_endpoint(app, client):1750    app.debug = True17511752    @app.route("/foo/")1753    def foo():1754        return flask.request.endpoint17551756    @app.route("/bar/", endpoint="bar")1757    def for_bar():1758        return flask.request.endpoint17591760    @app.route("/bar/123", endpoint="123")1761    def for_bar_foo():1762        return flask.request.endpoint17631764    with app.test_request_context():1765        assert flask.url_for("foo") == "/foo/"1766        assert flask.url_for("bar") == "/bar/"1767        assert flask.url_for("123") == "/bar/123"17681769    assert client.get("/foo/").data == b"foo"1770    assert client.get("/bar/").data == b"bar"1771    assert client.get("/bar/123").data == b"123"177217731774def test_preserve_only_once(app, client):1775    app.debug = True17761777    @app.route("/fail")1778    def fail_func():1779        1 // 017801781    for _x in range(3):1782        with pytest.raises(ZeroDivisionError):1783            client.get("/fail")17841785    assert flask._request_ctx_stack.top is not None1786    assert flask._app_ctx_stack.top is not None1787    # implicit appctx disappears too1788    flask._request_ctx_stack.top.pop()1789    assert flask._request_ctx_stack.top is None1790    assert flask._app_ctx_stack.top is None179117921793def test_preserve_remembers_exception(app, client):1794    app.debug = True1795    errors = []17961797    @app.route("/fail")1798    def fail_func():1799        1 // 018001801    @app.route("/success")1802    def success_func():1803        return "Okay"18041805    @app.teardown_request1806    def teardown_handler(exc):1807        errors.append(exc)18081809    # After this failure we did not yet call the teardown handler1810    with pytest.raises(ZeroDivisionError):1811        client.get("/fail")1812    assert errors == []18131814    # But this request triggers it, and it's an error1815    client.get("/success")1816    assert len(errors) == 21817    assert isinstance(errors[0], ZeroDivisionError)18181819    # At this point another request does nothing.1820    client.get("/success")1821    assert len(errors) == 31822    assert errors[1] is None182318241825def test_get_method_on_g(app_ctx):1826    assert flask.g.get("x") is None1827    assert flask.g.get("x", 11) == 111828    flask.g.x = 421829    assert flask.g.get("x") == 421830    assert flask.g.x == 42183118321833def test_g_iteration_protocol(app_ctx):1834    flask.g.foo = 231835    flask.g.bar = 421836    assert "foo" in flask.g1837    assert "foos" not in flask.g1838    assert sorted(flask.g) == ["bar", "foo"]183918401841def test_subdomain_basic_support():1842    app = flask.Flask(__name__, subdomain_matching=True)1843    app.config["SERVER_NAME"] = "localhost.localdomain"1844    client = app.test_client()18451846    @app.route("/")1847    def normal_index():1848        return "normal index"18491850    @app.route("/", subdomain="test")1851    def test_index():1852        return "test index"18531854    rv = client.get("/", "http://localhost.localdomain/")1855    assert rv.data == b"normal index"18561857    rv = client.get("/", "http://test.localhost.localdomain/")1858    assert rv.data == b"test index"185918601861def test_subdomain_matching():1862    app = flask.Flask(__name__, subdomain_matching=True)1863    client = app.test_client()1864    app.config["SERVER_NAME"] = "localhost.localdomain"18651866    @app.route("/", subdomain="<user>")1867    def index(user):1868        return f"index for {user}"18691870    rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1871    assert rv.data == b"index for mitsuhiko"187218731874def test_subdomain_matching_with_ports():1875    app = flask.Flask(__name__, subdomain_matching=True)1876    app.config["SERVER_NAME"] = "localhost.localdomain:3000"1877    client = app.test_client()18781879    @app.route("/", subdomain="<user>")1880    def index(user):1881        return f"index for {user}"18821883    rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1884    assert rv.data == b"index for mitsuhiko"188518861887@pytest.mark.parametrize("matching", (False, True))1888def test_subdomain_matching_other_name(matching):1889    app = flask.Flask(__name__, subdomain_matching=matching)1890    app.config["SERVER_NAME"] = "localhost.localdomain:3000"1891    client = app.test_client()18921893    @app.route("/")1894    def index():1895        return "", 20418961897    # suppress Werkzeug 0.15 warning about name mismatch1898    with pytest.warns(None):1899        # ip address can't match name1900        rv = client.get("/", "http://127.0.0.1:3000/")1901        assert rv.status_code == 404 if matching else 20419021903    # allow all subdomains if matching is disabled1904    rv = client.get("/", "http://www.localhost.localdomain:3000/")1905    assert rv.status_code == 404 if matching else 204190619071908def test_multi_route_rules(app, client):1909    @app.route("/")1910    @app.route("/<test>/")1911    def index(test="a"):1912        return test19131914    rv = client.open("/")1915    assert rv.data == b"a"1916    rv = client.open("/b/")1917    assert rv.data == b"b"191819191920def test_multi_route_class_views(app, client):1921    class View:1922        def __init__(self, app):1923            app.add_url_rule("/", "index", self.index)1924            app.add_url_rule("/<test>/", "index", self.index)19251926        def index(self, test="a"):1927            return test19281929    _ = View(app)1930    rv = client.open("/")1931    assert rv.data == b"a"1932    rv = client.open("/b/")1933    assert rv.data == b"b"193419351936def test_run_defaults(monkeypatch, app):1937    rv = {}19381939    # Mocks werkzeug.serving.run_simple method1940    def run_simple_mock(*args, **kwargs):1941        rv["result"] = "running..."19421943    monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1944    app.run()1945    assert rv["result"] == "running..."194619471948def test_run_server_port(monkeypatch, app):1949    rv = {}19501951    # Mocks werkzeug.serving.run_simple method1952    def run_simple_mock(hostname, port, application, *args, **kwargs):1953        rv["result"] = f"running on {hostname}:{port} ..."19541955    monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1956    hostname, port = "localhost", 80001957    app.run(hostname, port, debug=True)1958    assert rv["result"] == f"running on {hostname}:{port} ..."195919601961@pytest.mark.parametrize(1962    "host,port,server_name,expect_host,expect_port",1963    (1964        (None, None, "pocoo.org:8080", "pocoo.org", 8080),1965        ("localhost", None, "pocoo.org:8080", "localhost", 8080),1966        (None, 80, "pocoo.org:8080", "pocoo.org", 80),1967        ("localhost", 80, "pocoo.org:8080", "localhost", 80),1968        ("localhost", 0, "localhost:8080", "localhost", 0),1969        (None, None, "localhost:8080", "localhost", 8080),1970        (None, None, "localhost:0", "localhost", 0),1971    ),1972)1973def test_run_from_config(1974    monkeypatch, host, port, server_name, expect_host, expect_port, app1975):1976    def run_simple_mock(hostname, port, *args, **kwargs):1977        assert hostname == expect_host1978        assert port == expect_port19791980    monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1981    app.config["SERVER_NAME"] = server_name1982    app.run(host, port)198319841985def test_max_cookie_size(app, client, recwarn):1986    app.config["MAX_COOKIE_SIZE"] = 10019871988    # outside app context, default to Werkzeug static value,1989    # which is also the default config1990    response = flask.Response()1991    default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1992    assert response.max_cookie_size == default19931994    # inside app context, use app config1995    with app.app_context():1996        assert flask.Response().max_cookie_size == 10019971998    @app.route("/")1999    def index():2000        r = flask.Response("", status=204)

The first 2,000 of 2,028 lines.