Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

2,019 lines · 54.5 KiB · Python

Last changed by

avoid triggering setupmethod late in testsDavid Lordbefore adoptione044b00

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 BuildError18from werkzeug.routing import RequestRedirect1920import flask212223require_cpython_gc = pytest.mark.skipif(24    python_implementation() != "CPython",25    reason="Requires CPython GC behavior",26)272829def test_options_work(app, client):30    @app.route("/", methods=["GET", "POST"])31    def index():32        return "Hello World"3334    rv = client.open("/", method="OPTIONS")35    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]36    assert rv.data == b""373839def test_options_on_multiple_rules(app, client):40    @app.route("/", methods=["GET", "POST"])41    def index():42        return "Hello World"4344    @app.route("/", methods=["PUT"])45    def index_put():46        return "Aha!"4748    rv = client.open("/", method="OPTIONS")49    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST", "PUT"]505152@pytest.mark.parametrize("method", ["get", "post", "put", "delete", "patch"])53def test_method_route(app, client, method):54    method_route = getattr(app, method)55    client_method = getattr(client, method)5657    @method_route("/")58    def hello():59        return "Hello"6061    assert client_method("/").data == b"Hello"626364def test_method_route_no_methods(app):65    with pytest.raises(TypeError):66        app.get("/", methods=["GET", "POST"])676869def test_provide_automatic_options_attr():70    app = flask.Flask(__name__)7172    def index():73        return "Hello World!"7475    index.provide_automatic_options = False76    app.route("/")(index)77    rv = app.test_client().open("/", method="OPTIONS")78    assert rv.status_code == 4057980    app = flask.Flask(__name__)8182    def index2():83        return "Hello World!"8485    index2.provide_automatic_options = True86    app.route("/", methods=["OPTIONS"])(index2)87    rv = app.test_client().open("/", method="OPTIONS")88    assert sorted(rv.allow) == ["OPTIONS"]899091def test_provide_automatic_options_kwarg(app, client):92    def index():93        return flask.request.method9495    def more():96        return flask.request.method9798    app.add_url_rule("/", view_func=index, provide_automatic_options=False)99    app.add_url_rule(100        "/more",101        view_func=more,102        methods=["GET", "POST"],103        provide_automatic_options=False,104    )105    assert client.get("/").data == b"GET"106107    rv = client.post("/")108    assert rv.status_code == 405109    assert sorted(rv.allow) == ["GET", "HEAD"]110111    rv = client.open("/", method="OPTIONS")112    assert rv.status_code == 405113114    rv = client.head("/")115    assert rv.status_code == 200116    assert not rv.data  # head truncates117    assert client.post("/more").data == b"POST"118    assert client.get("/more").data == b"GET"119120    rv = client.delete("/more")121    assert rv.status_code == 405122    assert sorted(rv.allow) == ["GET", "HEAD", "POST"]123124    rv = client.open("/more", method="OPTIONS")125    assert rv.status_code == 405126127128def test_request_dispatching(app, client):129    @app.route("/")130    def index():131        return flask.request.method132133    @app.route("/more", methods=["GET", "POST"])134    def more():135        return flask.request.method136137    assert client.get("/").data == b"GET"138    rv = client.post("/")139    assert rv.status_code == 405140    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]141    rv = client.head("/")142    assert rv.status_code == 200143    assert not rv.data  # head truncates144    assert client.post("/more").data == b"POST"145    assert client.get("/more").data == b"GET"146    rv = client.delete("/more")147    assert rv.status_code == 405148    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]149150151def test_disallow_string_for_allowed_methods(app):152    with pytest.raises(TypeError):153        app.add_url_rule("/", methods="GET POST", endpoint="test")154155156def test_url_mapping(app, client):157    random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"158159    def index():160        return flask.request.method161162    def more():163        return flask.request.method164165    def options():166        return random_uuid4167168    app.add_url_rule("/", "index", index)169    app.add_url_rule("/more", "more", more, methods=["GET", "POST"])170171    # Issue 1288: Test that automatic options are not added172    #             when non-uppercase 'options' in methods173    app.add_url_rule("/options", "options", options, methods=["options"])174175    assert client.get("/").data == b"GET"176    rv = client.post("/")177    assert rv.status_code == 405178    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]179    rv = client.head("/")180    assert rv.status_code == 200181    assert not rv.data  # head truncates182    assert client.post("/more").data == b"POST"183    assert client.get("/more").data == b"GET"184    rv = client.delete("/more")185    assert rv.status_code == 405186    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]187    rv = client.open("/options", method="OPTIONS")188    assert rv.status_code == 200189    assert random_uuid4 in rv.data.decode("utf-8")190191192def test_werkzeug_routing(app, client):193    from werkzeug.routing import Submount, Rule194195    app.url_map.add(196        Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])197    )198199    def bar():200        return "bar"201202    def index():203        return "index"204205    app.view_functions["bar"] = bar206    app.view_functions["index"] = index207208    assert client.get("/foo/").data == b"index"209    assert client.get("/foo/bar").data == b"bar"210211212def test_endpoint_decorator(app, client):213    from werkzeug.routing import Submount, Rule214215    app.url_map.add(216        Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])217    )218219    @app.endpoint("bar")220    def bar():221        return "bar"222223    @app.endpoint("index")224    def index():225        return "index"226227    assert client.get("/foo/").data == b"index"228    assert client.get("/foo/bar").data == b"bar"229230231def test_session(app, client):232    @app.route("/set", methods=["POST"])233    def set():234        assert not flask.session.accessed235        assert not flask.session.modified236        flask.session["value"] = flask.request.form["value"]237        assert flask.session.accessed238        assert flask.session.modified239        return "value set"240241    @app.route("/get")242    def get():243        assert not flask.session.accessed244        assert not flask.session.modified245        v = flask.session.get("value", "None")246        assert flask.session.accessed247        assert not flask.session.modified248        return v249250    assert client.post("/set", data={"value": "42"}).data == b"value set"251    assert client.get("/get").data == b"42"252253254def test_session_using_server_name(app, client):255    app.config.update(SERVER_NAME="example.com")256257    @app.route("/")258    def index():259        flask.session["testing"] = 42260        return "Hello World"261262    rv = client.get("/", "http://example.com/")263    assert "domain=.example.com" in rv.headers["set-cookie"].lower()264    assert "httponly" in rv.headers["set-cookie"].lower()265266267def test_session_using_server_name_and_port(app, client):268    app.config.update(SERVER_NAME="example.com:8080")269270    @app.route("/")271    def index():272        flask.session["testing"] = 42273        return "Hello World"274275    rv = client.get("/", "http://example.com:8080/")276    assert "domain=.example.com" in rv.headers["set-cookie"].lower()277    assert "httponly" in rv.headers["set-cookie"].lower()278279280def test_session_using_server_name_port_and_path(app, client):281    app.config.update(SERVER_NAME="example.com:8080", APPLICATION_ROOT="/foo")282283    @app.route("/")284    def index():285        flask.session["testing"] = 42286        return "Hello World"287288    rv = client.get("/", "http://example.com:8080/foo")289    assert "domain=example.com" in rv.headers["set-cookie"].lower()290    assert "path=/foo" in rv.headers["set-cookie"].lower()291    assert "httponly" in rv.headers["set-cookie"].lower()292293294def test_session_using_application_root(app, client):295    class PrefixPathMiddleware:296        def __init__(self, app, prefix):297            self.app = app298            self.prefix = prefix299300        def __call__(self, environ, start_response):301            environ["SCRIPT_NAME"] = self.prefix302            return self.app(environ, start_response)303304    app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, "/bar")305    app.config.update(APPLICATION_ROOT="/bar")306307    @app.route("/")308    def index():309        flask.session["testing"] = 42310        return "Hello World"311312    rv = client.get("/", "http://example.com:8080/")313    assert "path=/bar" in rv.headers["set-cookie"].lower()314315316def test_session_using_session_settings(app, client):317    app.config.update(318        SERVER_NAME="www.example.com:8080",319        APPLICATION_ROOT="/test",320        SESSION_COOKIE_DOMAIN=".example.com",321        SESSION_COOKIE_HTTPONLY=False,322        SESSION_COOKIE_SECURE=True,323        SESSION_COOKIE_SAMESITE="Lax",324        SESSION_COOKIE_PATH="/",325    )326327    @app.route("/")328    def index():329        flask.session["testing"] = 42330        return "Hello World"331332    @app.route("/clear")333    def clear():334        flask.session.pop("testing", None)335        return "Goodbye World"336337    rv = client.get("/", "http://www.example.com:8080/test/")338    cookie = rv.headers["set-cookie"].lower()339    assert "domain=.example.com" in cookie340    assert "path=/" in cookie341    assert "secure" in cookie342    assert "httponly" not in cookie343    assert "samesite" in cookie344345    rv = client.get("/clear", "http://www.example.com:8080/test/")346    cookie = rv.headers["set-cookie"].lower()347    assert "session=;" in cookie348    assert "domain=.example.com" in cookie349    assert "path=/" in cookie350    assert "secure" in cookie351    assert "samesite" in cookie352353354def test_session_using_samesite_attribute(app, client):355    @app.route("/")356    def index():357        flask.session["testing"] = 42358        return "Hello World"359360    app.config.update(SESSION_COOKIE_SAMESITE="invalid")361362    with pytest.raises(ValueError):363        client.get("/")364365    app.config.update(SESSION_COOKIE_SAMESITE=None)366    rv = client.get("/")367    cookie = rv.headers["set-cookie"].lower()368    assert "samesite" not in cookie369370    app.config.update(SESSION_COOKIE_SAMESITE="Strict")371    rv = client.get("/")372    cookie = rv.headers["set-cookie"].lower()373    assert "samesite=strict" in cookie374375    app.config.update(SESSION_COOKIE_SAMESITE="Lax")376    rv = client.get("/")377    cookie = rv.headers["set-cookie"].lower()378    assert "samesite=lax" in cookie379380381def test_session_localhost_warning(recwarn, app, client):382    app.config.update(SERVER_NAME="localhost:5000")383384    @app.route("/")385    def index():386        flask.session["testing"] = 42387        return "testing"388389    rv = client.get("/", "http://localhost:5000/")390    assert "domain" not in rv.headers["set-cookie"].lower()391    w = recwarn.pop(UserWarning)392    assert "'localhost' is not a valid cookie domain" in str(w.message)393394395def test_session_ip_warning(recwarn, app, client):396    app.config.update(SERVER_NAME="127.0.0.1:5000")397398    @app.route("/")399    def index():400        flask.session["testing"] = 42401        return "testing"402403    rv = client.get("/", "http://127.0.0.1:5000/")404    assert "domain=127.0.0.1" in rv.headers["set-cookie"].lower()405    w = recwarn.pop(UserWarning)406    assert "cookie domain is an IP" in str(w.message)407408409def test_missing_session(app):410    app.secret_key = None411412    def expect_exception(f, *args, **kwargs):413        e = pytest.raises(RuntimeError, f, *args, **kwargs)414        assert e.value.args and "session is unavailable" in e.value.args[0]415416    with app.test_request_context():417        assert flask.session.get("missing_key") is None418        expect_exception(flask.session.__setitem__, "foo", 42)419        expect_exception(flask.session.pop, "foo")420421422def test_session_expiration(app, client):423    permanent = True424425    @app.route("/")426    def index():427        flask.session["test"] = 42428        flask.session.permanent = permanent429        return ""430431    @app.route("/test")432    def test():433        return str(flask.session.permanent)434435    rv = client.get("/")436    assert "set-cookie" in rv.headers437    match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])438    expires = parse_date(match.group())439    expected = datetime.utcnow() + app.permanent_session_lifetime440    assert expires.year == expected.year441    assert expires.month == expected.month442    assert expires.day == expected.day443444    rv = client.get("/test")445    assert rv.data == b"True"446447    permanent = False448    rv = client.get("/")449    assert "set-cookie" in rv.headers450    match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])451    assert match is None452453454def test_session_stored_last(app, client):455    @app.after_request456    def modify_session(response):457        flask.session["foo"] = 42458        return response459460    @app.route("/")461    def dump_session_contents():462        return repr(flask.session.get("foo"))463464    assert client.get("/").data == b"None"465    assert client.get("/").data == b"42"466467468def test_session_special_types(app, client):469    now = datetime.utcnow().replace(microsecond=0)470    the_uuid = uuid.uuid4()471472    @app.route("/")473    def dump_session_contents():474        flask.session["t"] = (1, 2, 3)475        flask.session["b"] = b"\xff"476        flask.session["m"] = flask.Markup("<html>")477        flask.session["u"] = the_uuid478        flask.session["d"] = now479        flask.session["t_tag"] = {" t": "not-a-tuple"}480        flask.session["di_t_tag"] = {" t__": "not-a-tuple"}481        flask.session["di_tag"] = {" di": "not-a-dict"}482        return "", 204483484    with client:485        client.get("/")486        s = flask.session487        assert s["t"] == (1, 2, 3)488        assert type(s["b"]) == bytes489        assert s["b"] == b"\xff"490        assert type(s["m"]) == flask.Markup491        assert s["m"] == flask.Markup("<html>")492        assert s["u"] == the_uuid493        assert s["d"] == now494        assert s["t_tag"] == {" t": "not-a-tuple"}495        assert s["di_t_tag"] == {" t__": "not-a-tuple"}496        assert s["di_tag"] == {" di": "not-a-dict"}497498499def test_session_cookie_setting(app):500    is_permanent = True501502    @app.route("/bump")503    def bump():504        rv = flask.session["foo"] = flask.session.get("foo", 0) + 1505        flask.session.permanent = is_permanent506        return str(rv)507508    @app.route("/read")509    def read():510        return str(flask.session.get("foo", 0))511512    def run_test(expect_header):513        with app.test_client() as c:514            assert c.get("/bump").data == b"1"515            assert c.get("/bump").data == b"2"516            assert c.get("/bump").data == b"3"517518            rv = c.get("/read")519            set_cookie = rv.headers.get("set-cookie")520            assert (set_cookie is not None) == expect_header521            assert rv.data == b"3"522523    is_permanent = True524    app.config["SESSION_REFRESH_EACH_REQUEST"] = True525    run_test(expect_header=True)526527    is_permanent = True528    app.config["SESSION_REFRESH_EACH_REQUEST"] = False529    run_test(expect_header=False)530531    is_permanent = False532    app.config["SESSION_REFRESH_EACH_REQUEST"] = True533    run_test(expect_header=False)534535    is_permanent = False536    app.config["SESSION_REFRESH_EACH_REQUEST"] = False537    run_test(expect_header=False)538539540def test_session_vary_cookie(app, client):541    @app.route("/set")542    def set_session():543        flask.session["test"] = "test"544        return ""545546    @app.route("/get")547    def get():548        return flask.session.get("test")549550    @app.route("/getitem")551    def getitem():552        return flask.session["test"]553554    @app.route("/setdefault")555    def setdefault():556        return flask.session.setdefault("test", "default")557558    @app.route("/vary-cookie-header-set")559    def vary_cookie_header_set():560        response = flask.Response()561        response.vary.add("Cookie")562        flask.session["test"] = "test"563        return response564565    @app.route("/vary-header-set")566    def vary_header_set():567        response = flask.Response()568        response.vary.update(("Accept-Encoding", "Accept-Language"))569        flask.session["test"] = "test"570        return response571572    @app.route("/no-vary-header")573    def no_vary_header():574        return ""575576    def expect(path, header_value="Cookie"):577        rv = client.get(path)578579        if header_value:580            # The 'Vary' key should exist in the headers only once.581            assert len(rv.headers.get_all("Vary")) == 1582            assert rv.headers["Vary"] == header_value583        else:584            assert "Vary" not in rv.headers585586    expect("/set")587    expect("/get")588    expect("/getitem")589    expect("/setdefault")590    expect("/vary-cookie-header-set")591    expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")592    expect("/no-vary-header", None)593594595def test_flashes(app, req_ctx):596    assert not flask.session.modified597    flask.flash("Zap")598    flask.session.modified = False599    flask.flash("Zip")600    assert flask.session.modified601    assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]602603604def test_extended_flashing(app):605    # Be sure app.testing=True below, else tests can fail silently.606    #607    # Specifically, if app.testing is not set to True, the AssertionErrors608    # in the view functions will cause a 500 response to the test client609    # instead of propagating exceptions.610611    @app.route("/")612    def index():613        flask.flash("Hello World")614        flask.flash("Hello World", "error")615        flask.flash(flask.Markup("<em>Testing</em>"), "warning")616        return ""617618    @app.route("/test/")619    def test():620        messages = flask.get_flashed_messages()621        assert list(messages) == [622            "Hello World",623            "Hello World",624            flask.Markup("<em>Testing</em>"),625        ]626        return ""627628    @app.route("/test_with_categories/")629    def test_with_categories():630        messages = flask.get_flashed_messages(with_categories=True)631        assert len(messages) == 3632        assert list(messages) == [633            ("message", "Hello World"),634            ("error", "Hello World"),635            ("warning", flask.Markup("<em>Testing</em>")),636        ]637        return ""638639    @app.route("/test_filter/")640    def test_filter():641        messages = flask.get_flashed_messages(642            category_filter=["message"], with_categories=True643        )644        assert list(messages) == [("message", "Hello World")]645        return ""646647    @app.route("/test_filters/")648    def test_filters():649        messages = flask.get_flashed_messages(650            category_filter=["message", "warning"], with_categories=True651        )652        assert list(messages) == [653            ("message", "Hello World"),654            ("warning", flask.Markup("<em>Testing</em>")),655        ]656        return ""657658    @app.route("/test_filters_without_returning_categories/")659    def test_filters2():660        messages = flask.get_flashed_messages(category_filter=["message", "warning"])661        assert len(messages) == 2662        assert messages[0] == "Hello World"663        assert messages[1] == flask.Markup("<em>Testing</em>")664        return ""665666    # Create new test client on each test to clean flashed messages.667668    client = app.test_client()669    client.get("/")670    client.get("/test_with_categories/")671672    client = app.test_client()673    client.get("/")674    client.get("/test_filter/")675676    client = app.test_client()677    client.get("/")678    client.get("/test_filters/")679680    client = app.test_client()681    client.get("/")682    client.get("/test_filters_without_returning_categories/")683684685def test_request_processing(app, client):686    evts = []687688    @app.before_request689    def before_request():690        evts.append("before")691692    @app.after_request693    def after_request(response):694        response.data += b"|after"695        evts.append("after")696        return response697698    @app.route("/")699    def index():700        assert "before" in evts701        assert "after" not in evts702        return "request"703704    assert "after" not in evts705    rv = client.get("/").data706    assert "after" in evts707    assert rv == b"request|after"708709710def test_request_preprocessing_early_return(app, client):711    evts = []712713    @app.before_request714    def before_request1():715        evts.append(1)716717    @app.before_request718    def before_request2():719        evts.append(2)720        return "hello"721722    @app.before_request723    def before_request3():724        evts.append(3)725        return "bye"726727    @app.route("/")728    def index():729        evts.append("index")730        return "damnit"731732    rv = client.get("/").data.strip()733    assert rv == b"hello"734    assert evts == [1, 2]735736737def test_after_request_processing(app, client):738    @app.route("/")739    def index():740        @flask.after_this_request741        def foo(response):742            response.headers["X-Foo"] = "a header"743            return response744745        return "Test"746747    resp = client.get("/")748    assert resp.status_code == 200749    assert resp.headers["X-Foo"] == "a header"750751752def test_teardown_request_handler(app, client):753    called = []754755    @app.teardown_request756    def teardown_request(exc):757        called.append(True)758        return "Ignored"759760    @app.route("/")761    def root():762        return "Response"763764    rv = client.get("/")765    assert rv.status_code == 200766    assert b"Response" in rv.data767    assert len(called) == 1768769770def test_teardown_request_handler_debug_mode(app, client):771    called = []772773    @app.teardown_request774    def teardown_request(exc):775        called.append(True)776        return "Ignored"777778    @app.route("/")779    def root():780        return "Response"781782    rv = client.get("/")783    assert rv.status_code == 200784    assert b"Response" in rv.data785    assert len(called) == 1786787788def test_teardown_request_handler_error(app, client):789    called = []790    app.testing = False791792    @app.teardown_request793    def teardown_request1(exc):794        assert type(exc) == ZeroDivisionError795        called.append(True)796        # This raises a new error and blows away sys.exc_info(), so we can797        # test that all teardown_requests get passed the same original798        # exception.799        try:800            raise TypeError()801        except Exception:802            pass803804    @app.teardown_request805    def teardown_request2(exc):806        assert type(exc) == ZeroDivisionError807        called.append(True)808        # This raises a new error and blows away sys.exc_info(), so we can809        # test that all teardown_requests get passed the same original810        # exception.811        try:812            raise TypeError()813        except Exception:814            pass815816    @app.route("/")817    def fails():818        1 // 0819820    rv = client.get("/")821    assert rv.status_code == 500822    assert b"Internal Server Error" in rv.data823    assert len(called) == 2824825826def test_before_after_request_order(app, client):827    called = []828829    @app.before_request830    def before1():831        called.append(1)832833    @app.before_request834    def before2():835        called.append(2)836837    @app.after_request838    def after1(response):839        called.append(4)840        return response841842    @app.after_request843    def after2(response):844        called.append(3)845        return response846847    @app.teardown_request848    def finish1(exc):849        called.append(6)850851    @app.teardown_request852    def finish2(exc):853        called.append(5)854855    @app.route("/")856    def index():857        return "42"858859    rv = client.get("/")860    assert rv.data == b"42"861    assert called == [1, 2, 3, 4, 5, 6]862863864def test_error_handling(app, client):865    app.testing = False866867    @app.errorhandler(404)868    def not_found(e):869        return "not found", 404870871    @app.errorhandler(500)872    def internal_server_error(e):873        return "internal server error", 500874875    @app.errorhandler(Forbidden)876    def forbidden(e):877        return "forbidden", 403878879    @app.route("/")880    def index():881        flask.abort(404)882883    @app.route("/error")884    def error():885        1 // 0886887    @app.route("/forbidden")888    def error2():889        flask.abort(403)890891    rv = client.get("/")892    assert rv.status_code == 404893    assert rv.data == b"not found"894    rv = client.get("/error")895    assert rv.status_code == 500896    assert b"internal server error" == rv.data897    rv = client.get("/forbidden")898    assert rv.status_code == 403899    assert b"forbidden" == rv.data900901902def test_error_handling_processing(app, client):903    app.testing = False904905    @app.errorhandler(500)906    def internal_server_error(e):907        return "internal server error", 500908909    @app.route("/")910    def broken_func():911        1 // 0912913    @app.after_request914    def after_request(resp):915        resp.mimetype = "text/x-special"916        return resp917918    resp = client.get("/")919    assert resp.mimetype == "text/x-special"920    assert resp.data == b"internal server error"921922923def test_baseexception_error_handling(app, client):924    app.testing = False925926    @app.route("/")927    def broken_func():928        raise KeyboardInterrupt()929930    with client:931        with pytest.raises(KeyboardInterrupt):932            client.get("/")933934        ctx = flask._request_ctx_stack.top935        assert ctx.preserved936        assert type(ctx._preserved_exc) is KeyboardInterrupt937938939def test_before_request_and_routing_errors(app, client):940    @app.before_request941    def attach_something():942        flask.g.something = "value"943944    @app.errorhandler(404)945    def return_something(error):946        return flask.g.something, 404947948    rv = client.get("/")949    assert rv.status_code == 404950    assert rv.data == b"value"951952953def test_user_error_handling(app, client):954    class MyException(Exception):955        pass956957    @app.errorhandler(MyException)958    def handle_my_exception(e):959        assert isinstance(e, MyException)960        return "42"961962    @app.route("/")963    def index():964        raise MyException()965966    assert client.get("/").data == b"42"967968969def test_http_error_subclass_handling(app, client):970    class ForbiddenSubclass(Forbidden):971        pass972973    @app.errorhandler(ForbiddenSubclass)974    def handle_forbidden_subclass(e):975        assert isinstance(e, ForbiddenSubclass)976        return "banana"977978    @app.errorhandler(403)979    def handle_403(e):980        assert not isinstance(e, ForbiddenSubclass)981        assert isinstance(e, Forbidden)982        return "apple"983984    @app.route("/1")985    def index1():986        raise ForbiddenSubclass()987988    @app.route("/2")989    def index2():990        flask.abort(403)991992    @app.route("/3")993    def index3():994        raise Forbidden()995996    assert client.get("/1").data == b"banana"997    assert client.get("/2").data == b"apple"998    assert client.get("/3").data == b"apple"99910001001def test_errorhandler_precedence(app, client):1002    class E1(Exception):1003        pass10041005    class E2(Exception):1006        pass10071008    class E3(E1, E2):1009        pass10101011    @app.errorhandler(E2)1012    def handle_e2(e):1013        return "E2"10141015    @app.errorhandler(Exception)1016    def handle_exception(e):1017        return "Exception"10181019    @app.route("/E1")1020    def raise_e1():1021        raise E110221023    @app.route("/E3")1024    def raise_e3():1025        raise E310261027    rv = client.get("/E1")1028    assert rv.data == b"Exception"10291030    rv = client.get("/E3")1031    assert rv.data == b"E2"103210331034@pytest.mark.parametrize(1035    ("debug", "trap", "expect_key", "expect_abort"),1036    [(False, None, True, True), (True, None, False, True), (False, True, False, False)],1037)1038def test_trap_bad_request_key_error(app, client, debug, trap, expect_key, expect_abort):1039    app.config["DEBUG"] = debug1040    app.config["TRAP_BAD_REQUEST_ERRORS"] = trap10411042    @app.route("/key")1043    def fail():1044        flask.request.form["missing_key"]10451046    @app.route("/abort")1047    def allow_abort():1048        flask.abort(400)10491050    if expect_key:1051        rv = client.get("/key")1052        assert rv.status_code == 4001053        assert b"missing_key" not in rv.data1054    else:1055        with pytest.raises(KeyError) as exc_info:1056            client.get("/key")10571058        assert exc_info.errisinstance(BadRequest)1059        assert "missing_key" in exc_info.value.get_description()10601061    if expect_abort:1062        rv = client.get("/abort")1063        assert rv.status_code == 4001064    else:1065        with pytest.raises(BadRequest):1066            client.get("/abort")106710681069def test_trapping_of_all_http_exceptions(app, client):1070    app.config["TRAP_HTTP_EXCEPTIONS"] = True10711072    @app.route("/fail")1073    def fail():1074        flask.abort(404)10751076    with pytest.raises(NotFound):1077        client.get("/fail")107810791080def test_error_handler_after_processor_error(app, client):1081    app.testing = False10821083    @app.before_request1084    def before_request():1085        if _trigger == "before":1086            1 // 010871088    @app.after_request1089    def after_request(response):1090        if _trigger == "after":1091            1 // 01092        return response10931094    @app.route("/")1095    def index():1096        return "Foo"10971098    @app.errorhandler(500)1099    def internal_server_error(e):1100        return "Hello Server Error", 50011011102    for _trigger in "before", "after":1103        rv = client.get("/")1104        assert rv.status_code == 5001105        assert rv.data == b"Hello Server Error"110611071108def test_enctype_debug_helper(app, client):1109    from flask.debughelpers import DebugFilesKeyError11101111    app.debug = True11121113    @app.route("/fail", methods=["POST"])1114    def index():1115        return flask.request.files["foo"].filename11161117    # with statement is important because we leave an exception on the1118    # stack otherwise and we want to ensure that this is not the case1119    # to not negatively affect other tests.1120    with client:1121        with pytest.raises(DebugFilesKeyError) as e:1122            client.post("/fail", data={"foo": "index.txt"})1123        assert "no file contents were transmitted" in str(e.value)1124        assert "This was submitted: 'index.txt'" in str(e.value)112511261127def test_response_types(app, client):1128    @app.route("/text")1129    def from_text():1130        return "Hällo Wörld"11311132    @app.route("/bytes")1133    def from_bytes():1134        return "Hällo Wörld".encode()11351136    @app.route("/full_tuple")1137    def from_full_tuple():1138        return (1139            "Meh",1140            400,1141            {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1142        )11431144    @app.route("/text_headers")1145    def from_text_headers():1146        return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}11471148    @app.route("/text_status")1149    def from_text_status():1150        return "Hi, status!", 40011511152    @app.route("/response_headers")1153    def from_response_headers():1154        return (1155            flask.Response(1156                "Hello world", 404, {"Content-Type": "text/html", "X-Foo": "Baz"}1157            ),1158            {"Content-Type": "text/plain", "X-Foo": "Bar", "X-Bar": "Foo"},1159        )11601161    @app.route("/response_status")1162    def from_response_status():1163        return app.response_class("Hello world", 400), 50011641165    @app.route("/wsgi")1166    def from_wsgi():1167        return NotFound()11681169    @app.route("/dict")1170    def from_dict():1171        return {"foo": "bar"}, 20111721173    assert client.get("/text").data == "Hällo Wörld".encode()1174    assert client.get("/bytes").data == "Hällo Wörld".encode()11751176    rv = client.get("/full_tuple")1177    assert rv.data == b"Meh"1178    assert rv.headers["X-Foo"] == "Testing"1179    assert rv.status_code == 4001180    assert rv.mimetype == "text/plain"11811182    rv = client.get("/text_headers")1183    assert rv.data == b"Hello"1184    assert rv.headers["X-Foo"] == "Test"1185    assert rv.status_code == 2001186    assert rv.mimetype == "text/plain"11871188    rv = client.get("/text_status")1189    assert rv.data == b"Hi, status!"1190    assert rv.status_code == 4001191    assert rv.mimetype == "text/html"11921193    rv = client.get("/response_headers")1194    assert rv.data == b"Hello world"1195    assert rv.content_type == "text/plain"1196    assert rv.headers.getlist("X-Foo") == ["Bar"]1197    assert rv.headers["X-Bar"] == "Foo"1198    assert rv.status_code == 40411991200    rv = client.get("/response_status")1201    assert rv.data == b"Hello world"1202    assert rv.status_code == 50012031204    rv = client.get("/wsgi")1205    assert b"Not Found" in rv.data1206    assert rv.status_code == 40412071208    rv = client.get("/dict")1209    assert rv.json == {"foo": "bar"}1210    assert rv.status_code == 201121112121213def test_response_type_errors():1214    app = flask.Flask(__name__)1215    app.testing = True12161217    @app.route("/none")1218    def from_none():1219        pass12201221    @app.route("/small_tuple")1222    def from_small_tuple():1223        return ("Hello",)12241225    @app.route("/large_tuple")1226    def from_large_tuple():1227        return "Hello", 234, {"X-Foo": "Bar"}, "???"12281229    @app.route("/bad_type")1230    def from_bad_type():1231        return True12321233    @app.route("/bad_wsgi")1234    def from_bad_wsgi():1235        return lambda: None12361237    c = app.test_client()12381239    with pytest.raises(TypeError) as e:1240        c.get("/none")12411242    assert "returned None" in str(e.value)1243    assert "from_none" in str(e.value)12441245    with pytest.raises(TypeError) as e:1246        c.get("/small_tuple")12471248    assert "tuple must have the form" in str(e.value)12491250    with pytest.raises(TypeError):1251        c.get("/large_tuple")12521253    with pytest.raises(TypeError) as e:1254        c.get("/bad_type")12551256    assert "it was a bool" in str(e.value)12571258    with pytest.raises(TypeError):1259        c.get("/bad_wsgi")126012611262def test_make_response(app, req_ctx):1263    rv = flask.make_response()1264    assert rv.status_code == 2001265    assert rv.data == b""1266    assert rv.mimetype == "text/html"12671268    rv = flask.make_response("Awesome")1269    assert rv.status_code == 2001270    assert rv.data == b"Awesome"1271    assert rv.mimetype == "text/html"12721273    rv = flask.make_response("W00t", 404)1274    assert rv.status_code == 4041275    assert rv.data == b"W00t"1276    assert rv.mimetype == "text/html"127712781279def test_make_response_with_response_instance(app, req_ctx):1280    rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1281    assert rv.status_code == 4001282    assert rv.data == b'{"msg":"W00t"}\n'1283    assert rv.mimetype == "application/json"12841285    rv = flask.make_response(flask.Response(""), 400)1286    assert rv.status_code == 4001287    assert rv.data == b""1288    assert rv.mimetype == "text/html"12891290    rv = flask.make_response(1291        flask.Response("", headers={"Content-Type": "text/html"}),1292        400,1293        [("X-Foo", "bar")],1294    )1295    assert rv.status_code == 4001296    assert rv.headers["Content-Type"] == "text/html"1297    assert rv.headers["X-Foo"] == "bar"129812991300def test_jsonify_no_prettyprint(app, req_ctx):1301    app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1302    compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1303    uncompressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}13041305    rv = flask.make_response(flask.jsonify(uncompressed_msg), 200)1306    assert rv.data == compressed_msg130713081309def test_jsonify_prettyprint(app, req_ctx):1310    app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1311    compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1312    pretty_response = (1313        b'{\n  "msg": {\n    "submsg": "W00t"\n  }, \n  "msg2": "foobar"\n}\n'1314    )13151316    rv = flask.make_response(flask.jsonify(compressed_msg), 200)1317    assert rv.data == pretty_response131813191320def test_jsonify_mimetype(app, req_ctx):1321    app.config.update({"JSONIFY_MIMETYPE": "application/vnd.api+json"})1322    msg = {"msg": {"submsg": "W00t"}}1323    rv = flask.make_response(flask.jsonify(msg), 200)1324    assert rv.mimetype == "application/vnd.api+json"132513261327def 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 0.15 warning about name mismatch1531    with warnings.catch_warnings():1532        warnings.filterwarnings(1533            "ignore", "Current server name", UserWarning, "flask.app"1534        )1535        rv = client.get("/", "http://foo.localhost")1536        assert rv.status_code == 40415371538    rv = client.get("/", "http://foo.dev.local")1539    assert rv.data == b"subdomain"154015411542@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning")1543@pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning")1544def test_exception_propagation(app, client):1545    def apprunner(config_key):1546        @app.route("/")1547        def index():1548            1 // 015491550        if config_key is not None:1551            app.config[config_key] = True1552            with pytest.raises(Exception):1553                client.get("/")1554        else:1555            assert client.get("/").status_code == 50015561557    # we have to run this test in an isolated thread because if the1558    # debug flag is set to true and an exception happens the context is1559    # not torn down.  This causes other tests that run after this fail1560    # when they expect no exception on the stack.1561    for config_key in "TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None:1562        t = Thread(target=apprunner, args=(config_key,))1563        t.start()1564        t.join()156515661567@pytest.mark.parametrize("debug", [True, False])1568@pytest.mark.parametrize("use_debugger", [True, False])1569@pytest.mark.parametrize("use_reloader", [True, False])1570@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1571def test_werkzeug_passthrough_errors(1572    monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1573):1574    rv = {}15751576    # Mocks werkzeug.serving.run_simple method1577    def run_simple_mock(*args, **kwargs):1578        rv["passthrough_errors"] = kwargs.get("passthrough_errors")15791580    monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1581    app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1582    app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)158315841585def test_max_content_length(app, client):1586    app.config["MAX_CONTENT_LENGTH"] = 6415871588    @app.before_request1589    def always_first():1590        flask.request.form["myfile"]1591        AssertionError()15921593    @app.route("/accept", methods=["POST"])1594    def accept_file():1595        flask.request.form["myfile"]1596        AssertionError()15971598    @app.errorhandler(413)1599    def catcher(error):1600        return "42"16011602    rv = client.post("/accept", data={"myfile": "foo" * 100})1603    assert rv.data == b"42"160416051606def test_url_processors(app, client):1607    @app.url_defaults1608    def add_language_code(endpoint, values):1609        if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1610            endpoint, "lang_code"1611        ):1612            values.setdefault("lang_code", flask.g.lang_code)16131614    @app.url_value_preprocessor1615    def pull_lang_code(endpoint, values):1616        flask.g.lang_code = values.pop("lang_code", None)16171618    @app.route("/<lang_code>/")1619    def index():1620        return flask.url_for("about")16211622    @app.route("/<lang_code>/about")1623    def about():1624        return flask.url_for("something_else")16251626    @app.route("/foo")1627    def something_else():1628        return flask.url_for("about", lang_code="en")16291630    assert client.get("/de/").data == b"/de/about"1631    assert client.get("/de/about").data == b"/foo"1632    assert client.get("/foo").data == b"/en/about"163316341635def test_inject_blueprint_url_defaults(app):1636    bp = flask.Blueprint("foo", __name__, template_folder="template")16371638    @bp.url_defaults1639    def bp_defaults(endpoint, values):1640        values["page"] = "login"16411642    @bp.route("/<page>")1643    def view(page):1644        pass16451646    app.register_blueprint(bp)16471648    values = dict()1649    app.inject_url_defaults("foo.view", values)1650    expected = dict(page="login")1651    assert values == expected16521653    with app.test_request_context("/somepage"):1654        url = flask.url_for("foo.view")1655    expected = "/login"1656    assert url == expected165716581659def test_nonascii_pathinfo(app, client):1660    @app.route("/киртест")1661    def index():1662        return "Hello World!"16631664    rv = client.get("/киртест")1665    assert rv.data == b"Hello World!"166616671668def test_no_setup_after_first_request(app, client):1669    app.debug = True16701671    @app.route("/")1672    def index():1673        return "Awesome"16741675    assert not app.got_first_request1676    assert client.get("/").data == b"Awesome"16771678    with pytest.raises(AssertionError) as exc_info:1679        app.add_url_rule("/foo", endpoint="late")16801681    assert "setup method 'add_url_rule'" in str(exc_info.value)168216831684def test_before_first_request_functions(app, client):1685    got = []16861687    @app.before_first_request1688    def foo():1689        got.append(42)16901691    client.get("/")1692    assert got == [42]1693    client.get("/")1694    assert got == [42]1695    assert app.got_first_request169616971698def test_before_first_request_functions_concurrent(app, client):1699    got = []17001701    @app.before_first_request1702    def foo():1703        time.sleep(0.2)1704        got.append(42)17051706    def get_and_assert():1707        client.get("/")1708        assert got == [42]17091710    t = Thread(target=get_and_assert)1711    t.start()1712    get_and_assert()1713    t.join()1714    assert app.got_first_request171517161717def test_routing_redirect_debugging(monkeypatch, app, client):1718    app.config["DEBUG"] = True17191720    @app.route("/user/", methods=["GET", "POST"])1721    def user():1722        return flask.request.form["status"]17231724    # default redirect code preserves form data1725    rv = client.post("/user", data={"status": "success"}, follow_redirects=True)1726    assert rv.data == b"success"17271728    # 301 and 302 raise error1729    monkeypatch.setattr(RequestRedirect, "code", 301)17301731    with client, pytest.raises(AssertionError) as exc_info:1732        client.post("/user", data={"status": "error"}, follow_redirects=True)17331734    assert "canonical URL 'http://localhost/user/'" in str(exc_info.value)173517361737def test_route_decorator_custom_endpoint(app, client):1738    app.debug = True17391740    @app.route("/foo/")1741    def foo():1742        return flask.request.endpoint17431744    @app.route("/bar/", endpoint="bar")1745    def for_bar():1746        return flask.request.endpoint17471748    @app.route("/bar/123", endpoint="123")1749    def for_bar_foo():1750        return flask.request.endpoint17511752    with app.test_request_context():1753        assert flask.url_for("foo") == "/foo/"1754        assert flask.url_for("bar") == "/bar/"1755        assert flask.url_for("123") == "/bar/123"17561757    assert client.get("/foo/").data == b"foo"1758    assert client.get("/bar/").data == b"bar"1759    assert client.get("/bar/123").data == b"123"176017611762def test_preserve_only_once(app, client):1763    app.debug = True17641765    @app.route("/fail")1766    def fail_func():1767        1 // 017681769    for _x in range(3):1770        with pytest.raises(ZeroDivisionError):1771            client.get("/fail")17721773    assert flask._request_ctx_stack.top is not None1774    assert flask._app_ctx_stack.top is not None1775    # implicit appctx disappears too1776    flask._request_ctx_stack.top.pop()1777    assert flask._request_ctx_stack.top is None1778    assert flask._app_ctx_stack.top is None177917801781def test_preserve_remembers_exception(app, client):1782    app.debug = True1783    errors = []17841785    @app.route("/fail")1786    def fail_func():1787        1 // 017881789    @app.route("/success")1790    def success_func():1791        return "Okay"17921793    @app.teardown_request1794    def teardown_handler(exc):1795        errors.append(exc)17961797    # After this failure we did not yet call the teardown handler1798    with pytest.raises(ZeroDivisionError):1799        client.get("/fail")1800    assert errors == []18011802    # But this request triggers it, and it's an error1803    client.get("/success")1804    assert len(errors) == 21805    assert isinstance(errors[0], ZeroDivisionError)18061807    # At this point another request does nothing.1808    client.get("/success")1809    assert len(errors) == 31810    assert errors[1] is None181118121813def test_get_method_on_g(app_ctx):1814    assert flask.g.get("x") is None1815    assert flask.g.get("x", 11) == 111816    flask.g.x = 421817    assert flask.g.get("x") == 421818    assert flask.g.x == 42181918201821def test_g_iteration_protocol(app_ctx):1822    flask.g.foo = 231823    flask.g.bar = 421824    assert "foo" in flask.g1825    assert "foos" not in flask.g1826    assert sorted(flask.g) == ["bar", "foo"]182718281829def test_subdomain_basic_support():1830    app = flask.Flask(__name__, subdomain_matching=True)1831    app.config["SERVER_NAME"] = "localhost.localdomain"1832    client = app.test_client()18331834    @app.route("/")1835    def normal_index():1836        return "normal index"18371838    @app.route("/", subdomain="test")1839    def test_index():1840        return "test index"18411842    rv = client.get("/", "http://localhost.localdomain/")1843    assert rv.data == b"normal index"18441845    rv = client.get("/", "http://test.localhost.localdomain/")1846    assert rv.data == b"test index"184718481849def test_subdomain_matching():1850    app = flask.Flask(__name__, subdomain_matching=True)1851    client = app.test_client()1852    app.config["SERVER_NAME"] = "localhost.localdomain"18531854    @app.route("/", subdomain="<user>")1855    def index(user):1856        return f"index for {user}"18571858    rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1859    assert rv.data == b"index for mitsuhiko"186018611862def test_subdomain_matching_with_ports():1863    app = flask.Flask(__name__, subdomain_matching=True)1864    app.config["SERVER_NAME"] = "localhost.localdomain:3000"1865    client = app.test_client()18661867    @app.route("/", subdomain="<user>")1868    def index(user):1869        return f"index for {user}"18701871    rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1872    assert rv.data == b"index for mitsuhiko"187318741875@pytest.mark.parametrize("matching", (False, True))1876def test_subdomain_matching_other_name(matching):1877    app = flask.Flask(__name__, subdomain_matching=matching)1878    app.config["SERVER_NAME"] = "localhost.localdomain:3000"1879    client = app.test_client()18801881    @app.route("/")1882    def index():1883        return "", 20418841885    # suppress Werkzeug 0.15 warning about name mismatch1886    with warnings.catch_warnings():1887        warnings.filterwarnings(1888            "ignore", "Current server name", UserWarning, "flask.app"1889        )1890        # ip address can't match name1891        rv = client.get("/", "http://127.0.0.1:3000/")1892        assert rv.status_code == 404 if matching else 20418931894    # allow all subdomains if matching is disabled1895    rv = client.get("/", "http://www.localhost.localdomain:3000/")1896    assert rv.status_code == 404 if matching else 204189718981899def test_multi_route_rules(app, client):1900    @app.route("/")1901    @app.route("/<test>/")1902    def index(test="a"):1903        return test19041905    rv = client.open("/")1906    assert rv.data == b"a"1907    rv = client.open("/b/")1908    assert rv.data == b"b"190919101911def test_multi_route_class_views(app, client):1912    class View:1913        def __init__(self, app):1914            app.add_url_rule("/", "index", self.index)1915            app.add_url_rule("/<test>/", "index", self.index)19161917        def index(self, test="a"):1918            return test19191920    _ = View(app)1921    rv = client.open("/")1922    assert rv.data == b"a"1923    rv = client.open("/b/")1924    assert rv.data == b"b"192519261927def test_run_defaults(monkeypatch, app):1928    rv = {}19291930    # Mocks werkzeug.serving.run_simple method1931    def run_simple_mock(*args, **kwargs):1932        rv["result"] = "running..."19331934    monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1935    app.run()1936    assert rv["result"] == "running..."193719381939def test_run_server_port(monkeypatch, app):1940    rv = {}19411942    # Mocks werkzeug.serving.run_simple method1943    def run_simple_mock(hostname, port, application, *args, **kwargs):1944        rv["result"] = f"running on {hostname}:{port} ..."19451946    monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1947    hostname, port = "localhost", 80001948    app.run(hostname, port, debug=True)1949    assert rv["result"] == f"running on {hostname}:{port} ..."195019511952@pytest.mark.parametrize(1953    "host,port,server_name,expect_host,expect_port",1954    (1955        (None, None, "pocoo.org:8080", "pocoo.org", 8080),1956        ("localhost", None, "pocoo.org:8080", "localhost", 8080),1957        (None, 80, "pocoo.org:8080", "pocoo.org", 80),1958        ("localhost", 80, "pocoo.org:8080", "localhost", 80),1959        ("localhost", 0, "localhost:8080", "localhost", 0),1960        (None, None, "localhost:8080", "localhost", 8080),1961        (None, None, "localhost:0", "localhost", 0),1962    ),1963)1964def test_run_from_config(1965    monkeypatch, host, port, server_name, expect_host, expect_port, app1966):1967    def run_simple_mock(hostname, port, *args, **kwargs):1968        assert hostname == expect_host1969        assert port == expect_port19701971    monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1972    app.config["SERVER_NAME"] = server_name1973    app.run(host, port)197419751976def test_max_cookie_size(app, client, recwarn):1977    app.config["MAX_COOKIE_SIZE"] = 10019781979    # outside app context, default to Werkzeug static value,1980    # which is also the default config1981    response = flask.Response()1982    default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1983    assert response.max_cookie_size == default19841985    # inside app context, use app config1986    with app.app_context():1987        assert flask.Response().max_cookie_size == 10019881989    @app.route("/")1990    def index():1991        r = flask.Response("", status=204)1992        r.set_cookie("foo", "bar" * 100)1993        return r19941995    client.get("/")1996    assert len(recwarn) == 11997    w = recwarn.pop()1998    assert "cookie is too large" in str(w.message)19992000    app.config["MAX_COOKIE_SIZE"] = 0

The first 2,000 of 2,019 lines.