Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

2,033 lines · 54.7 KiB · Python

Last changed by

Merge branch '2.0.x'David Lordbefore adoptione37e871

History of this file

Take it

1import gc2import re3import time4import uuid5import warnings6import 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"132413251326def test_json_dump_dataclass(app, req_ctx):1327    from dataclasses import make_dataclass13281329    Data = make_dataclass("Data", [("name", str)])1330    value = flask.json.dumps(Data("Flask"), app=app)1331    value = flask.json.loads(value, app=app)1332    assert value == {"name": "Flask"}133313341335def test_jsonify_args_and_kwargs_check(app, req_ctx):1336    with pytest.raises(TypeError) as e:1337        flask.jsonify("fake args", kwargs="fake")1338    assert "behavior undefined" in str(e.value)133913401341def test_url_generation(app, req_ctx):1342    @app.route("/hello/<name>", methods=["POST"])1343    def hello():1344        pass13451346    assert flask.url_for("hello", name="test x") == "/hello/test%20x"1347    assert (1348        flask.url_for("hello", name="test x", _external=True)1349        == "http://localhost/hello/test%20x"1350    )135113521353def test_build_error_handler(app):1354    # Test base case, a URL which results in a BuildError.1355    with app.test_request_context():1356        pytest.raises(BuildError, flask.url_for, "spam")13571358    # Verify the error is re-raised if not the current exception.1359    try:1360        with app.test_request_context():1361            flask.url_for("spam")1362    except BuildError as err:1363        error = err1364    try:1365        raise RuntimeError("Test case where BuildError is not current.")1366    except RuntimeError:1367        pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})13681369    # Test a custom handler.1370    def handler(error, endpoint, values):1371        # Just a test.1372        return "/test_handler/"13731374    app.url_build_error_handlers.append(handler)1375    with app.test_request_context():1376        assert flask.url_for("spam") == "/test_handler/"137713781379def test_build_error_handler_reraise(app):1380    # Test a custom handler which reraises the BuildError1381    def handler_raises_build_error(error, endpoint, values):1382        raise error13831384    app.url_build_error_handlers.append(handler_raises_build_error)13851386    with app.test_request_context():1387        pytest.raises(BuildError, flask.url_for, "not.existing")138813891390def test_url_for_passes_special_values_to_build_error_handler(app):1391    @app.url_build_error_handlers.append1392    def handler(error, endpoint, values):1393        assert values == {1394            "_external": False,1395            "_anchor": None,1396            "_method": None,1397            "_scheme": None,1398        }1399        return "handled"14001401    with app.test_request_context():1402        flask.url_for("/")140314041405def test_static_files(app, client):1406    rv = client.get("/static/index.html")1407    assert rv.status_code == 2001408    assert rv.data.strip() == b"<h1>Hello World!</h1>"1409    with app.test_request_context():1410        assert flask.url_for("static", filename="index.html") == "/static/index.html"1411    rv.close()141214131414def test_static_url_path():1415    app = flask.Flask(__name__, static_url_path="/foo")1416    app.testing = True1417    rv = app.test_client().get("/foo/index.html")1418    assert rv.status_code == 2001419    rv.close()14201421    with app.test_request_context():1422        assert flask.url_for("static", filename="index.html") == "/foo/index.html"142314241425def test_static_url_path_with_ending_slash():1426    app = flask.Flask(__name__, static_url_path="/foo/")1427    app.testing = True1428    rv = app.test_client().get("/foo/index.html")1429    assert rv.status_code == 2001430    rv.close()14311432    with app.test_request_context():1433        assert flask.url_for("static", filename="index.html") == "/foo/index.html"143414351436def test_static_url_empty_path(app):1437    app = flask.Flask(__name__, static_folder="", static_url_path="")1438    rv = app.test_client().open("/static/index.html", method="GET")1439    assert rv.status_code == 2001440    rv.close()144114421443def test_static_url_empty_path_default(app):1444    app = flask.Flask(__name__, static_folder="")1445    rv = app.test_client().open("/static/index.html", method="GET")1446    assert rv.status_code == 2001447    rv.close()144814491450def test_static_folder_with_pathlib_path(app):1451    from pathlib import Path14521453    app = flask.Flask(__name__, static_folder=Path("static"))1454    rv = app.test_client().open("/static/index.html", method="GET")1455    assert rv.status_code == 2001456    rv.close()145714581459def test_static_folder_with_ending_slash():1460    app = flask.Flask(__name__, static_folder="static/")14611462    @app.route("/<path:path>")1463    def catch_all(path):1464        return path14651466    rv = app.test_client().get("/catch/all")1467    assert rv.data == b"catch/all"146814691470def test_static_route_with_host_matching():1471    app = flask.Flask(__name__, host_matching=True, static_host="example.com")1472    c = app.test_client()1473    rv = c.get("http://example.com/static/index.html")1474    assert rv.status_code == 2001475    rv.close()1476    with app.test_request_context():1477        rv = flask.url_for("static", filename="index.html", _external=True)1478        assert rv == "http://example.com/static/index.html"1479    # Providing static_host without host_matching=True should error.1480    with pytest.raises(Exception):1481        flask.Flask(__name__, static_host="example.com")1482    # Providing host_matching=True with static_folder1483    # but without static_host should error.1484    with pytest.raises(Exception):1485        flask.Flask(__name__, host_matching=True)1486    # Providing host_matching=True without static_host1487    # but with static_folder=None should not error.1488    flask.Flask(__name__, host_matching=True, static_folder=None)148914901491def test_request_locals():1492    assert repr(flask.g) == "<LocalProxy unbound>"1493    assert not flask.g149414951496def test_server_name_subdomain():1497    app = flask.Flask(__name__, subdomain_matching=True)1498    client = app.test_client()14991500    @app.route("/")1501    def index():1502        return "default"15031504    @app.route("/", subdomain="foo")1505    def subdomain():1506        return "subdomain"15071508    app.config["SERVER_NAME"] = "dev.local:5000"1509    rv = client.get("/")1510    assert rv.data == b"default"15111512    rv = client.get("/", "http://dev.local:5000")1513    assert rv.data == b"default"15141515    rv = client.get("/", "https://dev.local:5000")1516    assert rv.data == b"default"15171518    app.config["SERVER_NAME"] = "dev.local:443"1519    rv = client.get("/", "https://dev.local")15201521    # Werkzeug 1.0 fixes matching https scheme with 443 port1522    if rv.status_code != 404:1523        assert rv.data == b"default"15241525    app.config["SERVER_NAME"] = "dev.local"1526    rv = client.get("/", "https://dev.local")1527    assert rv.data == b"default"15281529    # suppress Werkzeug 0.15 warning about name mismatch1530    with warnings.catch_warnings():1531        warnings.filterwarnings(1532            "ignore", "Current server name", UserWarning, "flask.app"1533        )1534        rv = client.get("/", "http://foo.localhost")1535        assert rv.status_code == 40415361537    rv = client.get("/", "http://foo.dev.local")1538    assert rv.data == b"subdomain"153915401541@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning")1542@pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning")1543def test_exception_propagation(app, client):1544    def apprunner(config_key):1545        @app.route("/")1546        def index():1547            1 // 015481549        if config_key is not None:1550            app.config[config_key] = True1551            with pytest.raises(Exception):1552                client.get("/")1553        else:1554            assert client.get("/").status_code == 50015551556    # we have to run this test in an isolated thread because if the1557    # debug flag is set to true and an exception happens the context is1558    # not torn down.  This causes other tests that run after this fail1559    # when they expect no exception on the stack.1560    for config_key in "TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None:1561        t = Thread(target=apprunner, args=(config_key,))1562        t.start()1563        t.join()156415651566@pytest.mark.parametrize("debug", [True, False])1567@pytest.mark.parametrize("use_debugger", [True, False])1568@pytest.mark.parametrize("use_reloader", [True, False])1569@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1570def test_werkzeug_passthrough_errors(1571    monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1572):1573    rv = {}15741575    # Mocks werkzeug.serving.run_simple method1576    def run_simple_mock(*args, **kwargs):1577        rv["passthrough_errors"] = kwargs.get("passthrough_errors")15781579    monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1580    app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1581    app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)158215831584def test_max_content_length(app, client):1585    app.config["MAX_CONTENT_LENGTH"] = 6415861587    @app.before_request1588    def always_first():1589        flask.request.form["myfile"]1590        AssertionError()15911592    @app.route("/accept", methods=["POST"])1593    def accept_file():1594        flask.request.form["myfile"]1595        AssertionError()15961597    @app.errorhandler(413)1598    def catcher(error):1599        return "42"16001601    rv = client.post("/accept", data={"myfile": "foo" * 100})1602    assert rv.data == b"42"160316041605def test_url_processors(app, client):1606    @app.url_defaults1607    def add_language_code(endpoint, values):1608        if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1609            endpoint, "lang_code"1610        ):1611            values.setdefault("lang_code", flask.g.lang_code)16121613    @app.url_value_preprocessor1614    def pull_lang_code(endpoint, values):1615        flask.g.lang_code = values.pop("lang_code", None)16161617    @app.route("/<lang_code>/")1618    def index():1619        return flask.url_for("about")16201621    @app.route("/<lang_code>/about")1622    def about():1623        return flask.url_for("something_else")16241625    @app.route("/foo")1626    def something_else():1627        return flask.url_for("about", lang_code="en")16281629    assert client.get("/de/").data == b"/de/about"1630    assert client.get("/de/about").data == b"/foo"1631    assert client.get("/foo").data == b"/en/about"163216331634def test_inject_blueprint_url_defaults(app):1635    bp = flask.Blueprint("foo", __name__, template_folder="template")16361637    @bp.url_defaults1638    def bp_defaults(endpoint, values):1639        values["page"] = "login"16401641    @bp.route("/<page>")1642    def view(page):1643        pass16441645    app.register_blueprint(bp)16461647    values = dict()1648    app.inject_url_defaults("foo.view", values)1649    expected = dict(page="login")1650    assert values == expected16511652    with app.test_request_context("/somepage"):1653        url = flask.url_for("foo.view")1654    expected = "/login"1655    assert url == expected165616571658def test_nonascii_pathinfo(app, client):1659    @app.route("/киртест")1660    def index():1661        return "Hello World!"16621663    rv = client.get("/киртест")1664    assert rv.data == b"Hello World!"166516661667def test_debug_mode_complains_after_first_request(app, client):1668    app.debug = True16691670    @app.route("/")1671    def index():1672        return "Awesome"16731674    assert not app.got_first_request1675    assert client.get("/").data == b"Awesome"1676    with pytest.raises(AssertionError) as e:16771678        @app.route("/foo")1679        def broken():1680            return "Meh"16811682    assert "A setup function was called" in str(e.value)16831684    app.debug = False16851686    @app.route("/foo")1687    def working():1688        return "Meh"16891690    assert client.get("/foo").data == b"Meh"1691    assert app.got_first_request169216931694def test_before_first_request_functions(app, client):1695    got = []16961697    @app.before_first_request1698    def foo():1699        got.append(42)17001701    client.get("/")1702    assert got == [42]1703    client.get("/")1704    assert got == [42]1705    assert app.got_first_request170617071708def test_before_first_request_functions_concurrent(app, client):1709    got = []17101711    @app.before_first_request1712    def foo():1713        time.sleep(0.2)1714        got.append(42)17151716    def get_and_assert():1717        client.get("/")1718        assert got == [42]17191720    t = Thread(target=get_and_assert)1721    t.start()1722    get_and_assert()1723    t.join()1724    assert app.got_first_request172517261727def test_routing_redirect_debugging(app, client):1728    app.debug = True17291730    @app.route("/foo/", methods=["GET", "POST"])1731    def foo():1732        return "success"17331734    with client:1735        with pytest.raises(AssertionError) as e:1736            client.post("/foo", data={})1737        assert "http://localhost/foo/" in str(e.value)1738        assert "Make sure to directly send your POST-request to this URL" in str(1739            e.value1740        )17411742        rv = client.get("/foo", data={}, follow_redirects=True)1743        assert rv.data == b"success"17441745    app.debug = False1746    with client:1747        rv = client.post("/foo", data={}, follow_redirects=True)1748        assert rv.data == b"success"174917501751def test_route_decorator_custom_endpoint(app, client):1752    app.debug = True17531754    @app.route("/foo/")1755    def foo():1756        return flask.request.endpoint17571758    @app.route("/bar/", endpoint="bar")1759    def for_bar():1760        return flask.request.endpoint17611762    @app.route("/bar/123", endpoint="123")1763    def for_bar_foo():1764        return flask.request.endpoint17651766    with app.test_request_context():1767        assert flask.url_for("foo") == "/foo/"1768        assert flask.url_for("bar") == "/bar/"1769        assert flask.url_for("123") == "/bar/123"17701771    assert client.get("/foo/").data == b"foo"1772    assert client.get("/bar/").data == b"bar"1773    assert client.get("/bar/123").data == b"123"177417751776def test_preserve_only_once(app, client):1777    app.debug = True17781779    @app.route("/fail")1780    def fail_func():1781        1 // 017821783    for _x in range(3):1784        with pytest.raises(ZeroDivisionError):1785            client.get("/fail")17861787    assert flask._request_ctx_stack.top is not None1788    assert flask._app_ctx_stack.top is not None1789    # implicit appctx disappears too1790    flask._request_ctx_stack.top.pop()1791    assert flask._request_ctx_stack.top is None1792    assert flask._app_ctx_stack.top is None179317941795def test_preserve_remembers_exception(app, client):1796    app.debug = True1797    errors = []17981799    @app.route("/fail")1800    def fail_func():1801        1 // 018021803    @app.route("/success")1804    def success_func():1805        return "Okay"18061807    @app.teardown_request1808    def teardown_handler(exc):1809        errors.append(exc)18101811    # After this failure we did not yet call the teardown handler1812    with pytest.raises(ZeroDivisionError):1813        client.get("/fail")1814    assert errors == []18151816    # But this request triggers it, and it's an error1817    client.get("/success")1818    assert len(errors) == 21819    assert isinstance(errors[0], ZeroDivisionError)18201821    # At this point another request does nothing.1822    client.get("/success")1823    assert len(errors) == 31824    assert errors[1] is None182518261827def test_get_method_on_g(app_ctx):1828    assert flask.g.get("x") is None1829    assert flask.g.get("x", 11) == 111830    flask.g.x = 421831    assert flask.g.get("x") == 421832    assert flask.g.x == 42183318341835def test_g_iteration_protocol(app_ctx):1836    flask.g.foo = 231837    flask.g.bar = 421838    assert "foo" in flask.g1839    assert "foos" not in flask.g1840    assert sorted(flask.g) == ["bar", "foo"]184118421843def test_subdomain_basic_support():1844    app = flask.Flask(__name__, subdomain_matching=True)1845    app.config["SERVER_NAME"] = "localhost.localdomain"1846    client = app.test_client()18471848    @app.route("/")1849    def normal_index():1850        return "normal index"18511852    @app.route("/", subdomain="test")1853    def test_index():1854        return "test index"18551856    rv = client.get("/", "http://localhost.localdomain/")1857    assert rv.data == b"normal index"18581859    rv = client.get("/", "http://test.localhost.localdomain/")1860    assert rv.data == b"test index"186118621863def test_subdomain_matching():1864    app = flask.Flask(__name__, subdomain_matching=True)1865    client = app.test_client()1866    app.config["SERVER_NAME"] = "localhost.localdomain"18671868    @app.route("/", subdomain="<user>")1869    def index(user):1870        return f"index for {user}"18711872    rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1873    assert rv.data == b"index for mitsuhiko"187418751876def test_subdomain_matching_with_ports():1877    app = flask.Flask(__name__, subdomain_matching=True)1878    app.config["SERVER_NAME"] = "localhost.localdomain:3000"1879    client = app.test_client()18801881    @app.route("/", subdomain="<user>")1882    def index(user):1883        return f"index for {user}"18841885    rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1886    assert rv.data == b"index for mitsuhiko"188718881889@pytest.mark.parametrize("matching", (False, True))1890def test_subdomain_matching_other_name(matching):1891    app = flask.Flask(__name__, subdomain_matching=matching)1892    app.config["SERVER_NAME"] = "localhost.localdomain:3000"1893    client = app.test_client()18941895    @app.route("/")1896    def index():1897        return "", 20418981899    # suppress Werkzeug 0.15 warning about name mismatch1900    with warnings.catch_warnings():1901        warnings.filterwarnings(1902            "ignore", "Current server name", UserWarning, "flask.app"1903        )1904        # ip address can't match name1905        rv = client.get("/", "http://127.0.0.1:3000/")1906        assert rv.status_code == 404 if matching else 20419071908    # allow all subdomains if matching is disabled1909    rv = client.get("/", "http://www.localhost.localdomain:3000/")1910    assert rv.status_code == 404 if matching else 204191119121913def test_multi_route_rules(app, client):1914    @app.route("/")1915    @app.route("/<test>/")1916    def index(test="a"):1917        return test19181919    rv = client.open("/")1920    assert rv.data == b"a"1921    rv = client.open("/b/")1922    assert rv.data == b"b"192319241925def test_multi_route_class_views(app, client):1926    class View:1927        def __init__(self, app):1928            app.add_url_rule("/", "index", self.index)1929            app.add_url_rule("/<test>/", "index", self.index)19301931        def index(self, test="a"):1932            return test19331934    _ = View(app)1935    rv = client.open("/")1936    assert rv.data == b"a"1937    rv = client.open("/b/")1938    assert rv.data == b"b"193919401941def test_run_defaults(monkeypatch, app):1942    rv = {}19431944    # Mocks werkzeug.serving.run_simple method1945    def run_simple_mock(*args, **kwargs):1946        rv["result"] = "running..."19471948    monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1949    app.run()1950    assert rv["result"] == "running..."195119521953def test_run_server_port(monkeypatch, app):1954    rv = {}19551956    # Mocks werkzeug.serving.run_simple method1957    def run_simple_mock(hostname, port, application, *args, **kwargs):1958        rv["result"] = f"running on {hostname}:{port} ..."19591960    monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1961    hostname, port = "localhost", 80001962    app.run(hostname, port, debug=True)1963    assert rv["result"] == f"running on {hostname}:{port} ..."196419651966@pytest.mark.parametrize(1967    "host,port,server_name,expect_host,expect_port",1968    (1969        (None, None, "pocoo.org:8080", "pocoo.org", 8080),1970        ("localhost", None, "pocoo.org:8080", "localhost", 8080),1971        (None, 80, "pocoo.org:8080", "pocoo.org", 80),1972        ("localhost", 80, "pocoo.org:8080", "localhost", 80),1973        ("localhost", 0, "localhost:8080", "localhost", 0),1974        (None, None, "localhost:8080", "localhost", 8080),1975        (None, None, "localhost:0", "localhost", 0),1976    ),1977)1978def test_run_from_config(1979    monkeypatch, host, port, server_name, expect_host, expect_port, app1980):1981    def run_simple_mock(hostname, port, *args, **kwargs):1982        assert hostname == expect_host1983        assert port == expect_port19841985    monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1986    app.config["SERVER_NAME"] = server_name1987    app.run(host, port)198819891990def test_max_cookie_size(app, client, recwarn):1991    app.config["MAX_COOKIE_SIZE"] = 10019921993    # outside app context, default to Werkzeug static value,1994    # which is also the default config1995    response = flask.Response()1996    default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1997    assert response.max_cookie_size == default19981999    # inside app context, use app config2000    with app.app_context():

The first 2,000 of 2,033 lines.