Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

2,012 lines · 54.2 KiB · Python

Last changed by

Merge pull request #3861 from greyli/fix-pytestDavid Lordbefore adoptionc676c2c

History of this file

Take it

1import gc2import re3import sys4import time5import uuid6import weakref7from datetime import datetime8from platform import python_implementation9from threading import Thread1011import pytest12import werkzeug.serving13from werkzeug.exceptions import BadRequest14from werkzeug.exceptions import Forbidden15from werkzeug.exceptions import NotFound16from werkzeug.http import parse_date17from werkzeug.routing import BuildError1819import flask202122require_cpython_gc = pytest.mark.skipif(23    python_implementation() != "CPython",24    reason="Requires CPython GC behavior",25)262728def test_options_work(app, client):29    @app.route("/", methods=["GET", "POST"])30    def index():31        return "Hello World"3233    rv = client.open("/", method="OPTIONS")34    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]35    assert rv.data == b""363738def test_options_on_multiple_rules(app, client):39    @app.route("/", methods=["GET", "POST"])40    def index():41        return "Hello World"4243    @app.route("/", methods=["PUT"])44    def index_put():45        return "Aha!"4647    rv = client.open("/", method="OPTIONS")48    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST", "PUT"]495051def test_provide_automatic_options_attr():52    app = flask.Flask(__name__)5354    def index():55        return "Hello World!"5657    index.provide_automatic_options = False58    app.route("/")(index)59    rv = app.test_client().open("/", method="OPTIONS")60    assert rv.status_code == 4056162    app = flask.Flask(__name__)6364    def index2():65        return "Hello World!"6667    index2.provide_automatic_options = True68    app.route("/", methods=["OPTIONS"])(index2)69    rv = app.test_client().open("/", method="OPTIONS")70    assert sorted(rv.allow) == ["OPTIONS"]717273def test_provide_automatic_options_kwarg(app, client):74    def index():75        return flask.request.method7677    def more():78        return flask.request.method7980    app.add_url_rule("/", view_func=index, provide_automatic_options=False)81    app.add_url_rule(82        "/more",83        view_func=more,84        methods=["GET", "POST"],85        provide_automatic_options=False,86    )87    assert client.get("/").data == b"GET"8889    rv = client.post("/")90    assert rv.status_code == 40591    assert sorted(rv.allow) == ["GET", "HEAD"]9293    rv = client.open("/", method="OPTIONS")94    assert rv.status_code == 4059596    rv = client.head("/")97    assert rv.status_code == 20098    assert not rv.data  # head truncates99    assert client.post("/more").data == b"POST"100    assert client.get("/more").data == b"GET"101102    rv = client.delete("/more")103    assert rv.status_code == 405104    assert sorted(rv.allow) == ["GET", "HEAD", "POST"]105106    rv = client.open("/more", method="OPTIONS")107    assert rv.status_code == 405108109110def test_request_dispatching(app, client):111    @app.route("/")112    def index():113        return flask.request.method114115    @app.route("/more", methods=["GET", "POST"])116    def more():117        return flask.request.method118119    assert client.get("/").data == b"GET"120    rv = client.post("/")121    assert rv.status_code == 405122    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]123    rv = client.head("/")124    assert rv.status_code == 200125    assert not rv.data  # head truncates126    assert client.post("/more").data == b"POST"127    assert client.get("/more").data == b"GET"128    rv = client.delete("/more")129    assert rv.status_code == 405130    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]131132133def test_disallow_string_for_allowed_methods(app):134    with pytest.raises(TypeError):135136        @app.route("/", methods="GET POST")137        def index():138            return "Hey"139140141def test_url_mapping(app, client):142    random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"143144    def index():145        return flask.request.method146147    def more():148        return flask.request.method149150    def options():151        return random_uuid4152153    app.add_url_rule("/", "index", index)154    app.add_url_rule("/more", "more", more, methods=["GET", "POST"])155156    # Issue 1288: Test that automatic options are not added157    #             when non-uppercase 'options' in methods158    app.add_url_rule("/options", "options", options, methods=["options"])159160    assert client.get("/").data == b"GET"161    rv = client.post("/")162    assert rv.status_code == 405163    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]164    rv = client.head("/")165    assert rv.status_code == 200166    assert not rv.data  # head truncates167    assert client.post("/more").data == b"POST"168    assert client.get("/more").data == b"GET"169    rv = client.delete("/more")170    assert rv.status_code == 405171    assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]172    rv = client.open("/options", method="OPTIONS")173    assert rv.status_code == 200174    assert random_uuid4 in rv.data.decode("utf-8")175176177def test_werkzeug_routing(app, client):178    from werkzeug.routing import Submount, Rule179180    app.url_map.add(181        Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])182    )183184    def bar():185        return "bar"186187    def index():188        return "index"189190    app.view_functions["bar"] = bar191    app.view_functions["index"] = index192193    assert client.get("/foo/").data == b"index"194    assert client.get("/foo/bar").data == b"bar"195196197def test_endpoint_decorator(app, client):198    from werkzeug.routing import Submount, Rule199200    app.url_map.add(201        Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])202    )203204    @app.endpoint("bar")205    def bar():206        return "bar"207208    @app.endpoint("index")209    def index():210        return "index"211212    assert client.get("/foo/").data == b"index"213    assert client.get("/foo/bar").data == b"bar"214215216def test_session(app, client):217    @app.route("/set", methods=["POST"])218    def set():219        assert not flask.session.accessed220        assert not flask.session.modified221        flask.session["value"] = flask.request.form["value"]222        assert flask.session.accessed223        assert flask.session.modified224        return "value set"225226    @app.route("/get")227    def get():228        assert not flask.session.accessed229        assert not flask.session.modified230        v = flask.session.get("value", "None")231        assert flask.session.accessed232        assert not flask.session.modified233        return v234235    assert client.post("/set", data={"value": "42"}).data == b"value set"236    assert client.get("/get").data == b"42"237238239def test_session_using_server_name(app, client):240    app.config.update(SERVER_NAME="example.com")241242    @app.route("/")243    def index():244        flask.session["testing"] = 42245        return "Hello World"246247    rv = client.get("/", "http://example.com/")248    assert "domain=.example.com" in rv.headers["set-cookie"].lower()249    assert "httponly" in rv.headers["set-cookie"].lower()250251252def test_session_using_server_name_and_port(app, client):253    app.config.update(SERVER_NAME="example.com:8080")254255    @app.route("/")256    def index():257        flask.session["testing"] = 42258        return "Hello World"259260    rv = client.get("/", "http://example.com:8080/")261    assert "domain=.example.com" in rv.headers["set-cookie"].lower()262    assert "httponly" in rv.headers["set-cookie"].lower()263264265def test_session_using_server_name_port_and_path(app, client):266    app.config.update(SERVER_NAME="example.com:8080", APPLICATION_ROOT="/foo")267268    @app.route("/")269    def index():270        flask.session["testing"] = 42271        return "Hello World"272273    rv = client.get("/", "http://example.com:8080/foo")274    assert "domain=example.com" in rv.headers["set-cookie"].lower()275    assert "path=/foo" in rv.headers["set-cookie"].lower()276    assert "httponly" in rv.headers["set-cookie"].lower()277278279def test_session_using_application_root(app, client):280    class PrefixPathMiddleware:281        def __init__(self, app, prefix):282            self.app = app283            self.prefix = prefix284285        def __call__(self, environ, start_response):286            environ["SCRIPT_NAME"] = self.prefix287            return self.app(environ, start_response)288289    app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, "/bar")290    app.config.update(APPLICATION_ROOT="/bar")291292    @app.route("/")293    def index():294        flask.session["testing"] = 42295        return "Hello World"296297    rv = client.get("/", "http://example.com:8080/")298    assert "path=/bar" in rv.headers["set-cookie"].lower()299300301def test_session_using_session_settings(app, client):302    app.config.update(303        SERVER_NAME="www.example.com:8080",304        APPLICATION_ROOT="/test",305        SESSION_COOKIE_DOMAIN=".example.com",306        SESSION_COOKIE_HTTPONLY=False,307        SESSION_COOKIE_SECURE=True,308        SESSION_COOKIE_SAMESITE="Lax",309        SESSION_COOKIE_PATH="/",310    )311312    @app.route("/")313    def index():314        flask.session["testing"] = 42315        return "Hello World"316317    rv = client.get("/", "http://www.example.com:8080/test/")318    cookie = rv.headers["set-cookie"].lower()319    assert "domain=.example.com" in cookie320    assert "path=/" in cookie321    assert "secure" in cookie322    assert "httponly" not in cookie323    assert "samesite" in cookie324325    @app.route("/clear")326    def clear():327        flask.session.pop("testing", None)328        return "Goodbye World"329330    rv = client.get("/clear", "http://www.example.com:8080/test/")331    cookie = rv.headers["set-cookie"].lower()332    assert "session=;" in cookie333    assert "domain=.example.com" in cookie334    assert "path=/" in cookie335    assert "secure" in cookie336    assert "samesite" in cookie337338339def test_session_using_samesite_attribute(app, client):340    @app.route("/")341    def index():342        flask.session["testing"] = 42343        return "Hello World"344345    app.config.update(SESSION_COOKIE_SAMESITE="invalid")346347    with pytest.raises(ValueError):348        client.get("/")349350    app.config.update(SESSION_COOKIE_SAMESITE=None)351    rv = client.get("/")352    cookie = rv.headers["set-cookie"].lower()353    assert "samesite" not in cookie354355    app.config.update(SESSION_COOKIE_SAMESITE="Strict")356    rv = client.get("/")357    cookie = rv.headers["set-cookie"].lower()358    assert "samesite=strict" in cookie359360    app.config.update(SESSION_COOKIE_SAMESITE="Lax")361    rv = client.get("/")362    cookie = rv.headers["set-cookie"].lower()363    assert "samesite=lax" in cookie364365366def test_session_localhost_warning(recwarn, app, client):367    app.config.update(SERVER_NAME="localhost:5000")368369    @app.route("/")370    def index():371        flask.session["testing"] = 42372        return "testing"373374    rv = client.get("/", "http://localhost:5000/")375    assert "domain" not in rv.headers["set-cookie"].lower()376    w = recwarn.pop(UserWarning)377    assert "'localhost' is not a valid cookie domain" in str(w.message)378379380def test_session_ip_warning(recwarn, app, client):381    app.config.update(SERVER_NAME="127.0.0.1:5000")382383    @app.route("/")384    def index():385        flask.session["testing"] = 42386        return "testing"387388    rv = client.get("/", "http://127.0.0.1:5000/")389    assert "domain=127.0.0.1" in rv.headers["set-cookie"].lower()390    w = recwarn.pop(UserWarning)391    assert "cookie domain is an IP" in str(w.message)392393394def test_missing_session(app):395    app.secret_key = None396397    def expect_exception(f, *args, **kwargs):398        e = pytest.raises(RuntimeError, f, *args, **kwargs)399        assert e.value.args and "session is unavailable" in e.value.args[0]400401    with app.test_request_context():402        assert flask.session.get("missing_key") is None403        expect_exception(flask.session.__setitem__, "foo", 42)404        expect_exception(flask.session.pop, "foo")405406407def test_session_expiration(app, client):408    permanent = True409410    @app.route("/")411    def index():412        flask.session["test"] = 42413        flask.session.permanent = permanent414        return ""415416    @app.route("/test")417    def test():418        return str(flask.session.permanent)419420    rv = client.get("/")421    assert "set-cookie" in rv.headers422    match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])423    expires = parse_date(match.group())424    expected = datetime.utcnow() + app.permanent_session_lifetime425    assert expires.year == expected.year426    assert expires.month == expected.month427    assert expires.day == expected.day428429    rv = client.get("/test")430    assert rv.data == b"True"431432    permanent = False433    rv = client.get("/")434    assert "set-cookie" in rv.headers435    match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])436    assert match is None437438439def test_session_stored_last(app, client):440    @app.after_request441    def modify_session(response):442        flask.session["foo"] = 42443        return response444445    @app.route("/")446    def dump_session_contents():447        return repr(flask.session.get("foo"))448449    assert client.get("/").data == b"None"450    assert client.get("/").data == b"42"451452453def test_session_special_types(app, client):454    now = datetime.utcnow().replace(microsecond=0)455    the_uuid = uuid.uuid4()456457    @app.route("/")458    def dump_session_contents():459        flask.session["t"] = (1, 2, 3)460        flask.session["b"] = b"\xff"461        flask.session["m"] = flask.Markup("<html>")462        flask.session["u"] = the_uuid463        flask.session["d"] = now464        flask.session["t_tag"] = {" t": "not-a-tuple"}465        flask.session["di_t_tag"] = {" t__": "not-a-tuple"}466        flask.session["di_tag"] = {" di": "not-a-dict"}467        return "", 204468469    with client:470        client.get("/")471        s = flask.session472        assert s["t"] == (1, 2, 3)473        assert type(s["b"]) == bytes474        assert s["b"] == b"\xff"475        assert type(s["m"]) == flask.Markup476        assert s["m"] == flask.Markup("<html>")477        assert s["u"] == the_uuid478        assert s["d"] == now479        assert s["t_tag"] == {" t": "not-a-tuple"}480        assert s["di_t_tag"] == {" t__": "not-a-tuple"}481        assert s["di_tag"] == {" di": "not-a-dict"}482483484def test_session_cookie_setting(app):485    is_permanent = True486487    @app.route("/bump")488    def bump():489        rv = flask.session["foo"] = flask.session.get("foo", 0) + 1490        flask.session.permanent = is_permanent491        return str(rv)492493    @app.route("/read")494    def read():495        return str(flask.session.get("foo", 0))496497    def run_test(expect_header):498        with app.test_client() as c:499            assert c.get("/bump").data == b"1"500            assert c.get("/bump").data == b"2"501            assert c.get("/bump").data == b"3"502503            rv = c.get("/read")504            set_cookie = rv.headers.get("set-cookie")505            assert (set_cookie is not None) == expect_header506            assert rv.data == b"3"507508    is_permanent = True509    app.config["SESSION_REFRESH_EACH_REQUEST"] = True510    run_test(expect_header=True)511512    is_permanent = True513    app.config["SESSION_REFRESH_EACH_REQUEST"] = False514    run_test(expect_header=False)515516    is_permanent = False517    app.config["SESSION_REFRESH_EACH_REQUEST"] = True518    run_test(expect_header=False)519520    is_permanent = False521    app.config["SESSION_REFRESH_EACH_REQUEST"] = False522    run_test(expect_header=False)523524525def test_session_vary_cookie(app, client):526    @app.route("/set")527    def set_session():528        flask.session["test"] = "test"529        return ""530531    @app.route("/get")532    def get():533        return flask.session.get("test")534535    @app.route("/getitem")536    def getitem():537        return flask.session["test"]538539    @app.route("/setdefault")540    def setdefault():541        return flask.session.setdefault("test", "default")542543    @app.route("/vary-cookie-header-set")544    def vary_cookie_header_set():545        response = flask.Response()546        response.vary.add("Cookie")547        flask.session["test"] = "test"548        return response549550    @app.route("/vary-header-set")551    def vary_header_set():552        response = flask.Response()553        response.vary.update(("Accept-Encoding", "Accept-Language"))554        flask.session["test"] = "test"555        return response556557    @app.route("/no-vary-header")558    def no_vary_header():559        return ""560561    def expect(path, header_value="Cookie"):562        rv = client.get(path)563564        if header_value:565            # The 'Vary' key should exist in the headers only once.566            assert len(rv.headers.get_all("Vary")) == 1567            assert rv.headers["Vary"] == header_value568        else:569            assert "Vary" not in rv.headers570571    expect("/set")572    expect("/get")573    expect("/getitem")574    expect("/setdefault")575    expect("/vary-cookie-header-set")576    expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")577    expect("/no-vary-header", None)578579580def test_flashes(app, req_ctx):581    assert not flask.session.modified582    flask.flash("Zap")583    flask.session.modified = False584    flask.flash("Zip")585    assert flask.session.modified586    assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]587588589def test_extended_flashing(app):590    # Be sure app.testing=True below, else tests can fail silently.591    #592    # Specifically, if app.testing is not set to True, the AssertionErrors593    # in the view functions will cause a 500 response to the test client594    # instead of propagating exceptions.595596    @app.route("/")597    def index():598        flask.flash("Hello World")599        flask.flash("Hello World", "error")600        flask.flash(flask.Markup("<em>Testing</em>"), "warning")601        return ""602603    @app.route("/test/")604    def test():605        messages = flask.get_flashed_messages()606        assert list(messages) == [607            "Hello World",608            "Hello World",609            flask.Markup("<em>Testing</em>"),610        ]611        return ""612613    @app.route("/test_with_categories/")614    def test_with_categories():615        messages = flask.get_flashed_messages(with_categories=True)616        assert len(messages) == 3617        assert list(messages) == [618            ("message", "Hello World"),619            ("error", "Hello World"),620            ("warning", flask.Markup("<em>Testing</em>")),621        ]622        return ""623624    @app.route("/test_filter/")625    def test_filter():626        messages = flask.get_flashed_messages(627            category_filter=["message"], with_categories=True628        )629        assert list(messages) == [("message", "Hello World")]630        return ""631632    @app.route("/test_filters/")633    def test_filters():634        messages = flask.get_flashed_messages(635            category_filter=["message", "warning"], with_categories=True636        )637        assert list(messages) == [638            ("message", "Hello World"),639            ("warning", flask.Markup("<em>Testing</em>")),640        ]641        return ""642643    @app.route("/test_filters_without_returning_categories/")644    def test_filters2():645        messages = flask.get_flashed_messages(category_filter=["message", "warning"])646        assert len(messages) == 2647        assert messages[0] == "Hello World"648        assert messages[1] == flask.Markup("<em>Testing</em>")649        return ""650651    # Create new test client on each test to clean flashed messages.652653    client = app.test_client()654    client.get("/")655    client.get("/test_with_categories/")656657    client = app.test_client()658    client.get("/")659    client.get("/test_filter/")660661    client = app.test_client()662    client.get("/")663    client.get("/test_filters/")664665    client = app.test_client()666    client.get("/")667    client.get("/test_filters_without_returning_categories/")668669670def test_request_processing(app, client):671    evts = []672673    @app.before_request674    def before_request():675        evts.append("before")676677    @app.after_request678    def after_request(response):679        response.data += b"|after"680        evts.append("after")681        return response682683    @app.route("/")684    def index():685        assert "before" in evts686        assert "after" not in evts687        return "request"688689    assert "after" not in evts690    rv = client.get("/").data691    assert "after" in evts692    assert rv == b"request|after"693694695def test_request_preprocessing_early_return(app, client):696    evts = []697698    @app.before_request699    def before_request1():700        evts.append(1)701702    @app.before_request703    def before_request2():704        evts.append(2)705        return "hello"706707    @app.before_request708    def before_request3():709        evts.append(3)710        return "bye"711712    @app.route("/")713    def index():714        evts.append("index")715        return "damnit"716717    rv = client.get("/").data.strip()718    assert rv == b"hello"719    assert evts == [1, 2]720721722def test_after_request_processing(app, client):723    @app.route("/")724    def index():725        @flask.after_this_request726        def foo(response):727            response.headers["X-Foo"] = "a header"728            return response729730        return "Test"731732    resp = client.get("/")733    assert resp.status_code == 200734    assert resp.headers["X-Foo"] == "a header"735736737def test_teardown_request_handler(app, client):738    called = []739740    @app.teardown_request741    def teardown_request(exc):742        called.append(True)743        return "Ignored"744745    @app.route("/")746    def root():747        return "Response"748749    rv = client.get("/")750    assert rv.status_code == 200751    assert b"Response" in rv.data752    assert len(called) == 1753754755def test_teardown_request_handler_debug_mode(app, client):756    called = []757758    @app.teardown_request759    def teardown_request(exc):760        called.append(True)761        return "Ignored"762763    @app.route("/")764    def root():765        return "Response"766767    rv = client.get("/")768    assert rv.status_code == 200769    assert b"Response" in rv.data770    assert len(called) == 1771772773def test_teardown_request_handler_error(app, client):774    called = []775    app.testing = False776777    @app.teardown_request778    def teardown_request1(exc):779        assert type(exc) == ZeroDivisionError780        called.append(True)781        # This raises a new error and blows away sys.exc_info(), so we can782        # test that all teardown_requests get passed the same original783        # exception.784        try:785            raise TypeError()786        except Exception:787            pass788789    @app.teardown_request790    def teardown_request2(exc):791        assert type(exc) == ZeroDivisionError792        called.append(True)793        # This raises a new error and blows away sys.exc_info(), so we can794        # test that all teardown_requests get passed the same original795        # exception.796        try:797            raise TypeError()798        except Exception:799            pass800801    @app.route("/")802    def fails():803        1 // 0804805    rv = client.get("/")806    assert rv.status_code == 500807    assert b"Internal Server Error" in rv.data808    assert len(called) == 2809810811def test_before_after_request_order(app, client):812    called = []813814    @app.before_request815    def before1():816        called.append(1)817818    @app.before_request819    def before2():820        called.append(2)821822    @app.after_request823    def after1(response):824        called.append(4)825        return response826827    @app.after_request828    def after2(response):829        called.append(3)830        return response831832    @app.teardown_request833    def finish1(exc):834        called.append(6)835836    @app.teardown_request837    def finish2(exc):838        called.append(5)839840    @app.route("/")841    def index():842        return "42"843844    rv = client.get("/")845    assert rv.data == b"42"846    assert called == [1, 2, 3, 4, 5, 6]847848849def test_error_handling(app, client):850    app.testing = False851852    @app.errorhandler(404)853    def not_found(e):854        return "not found", 404855856    @app.errorhandler(500)857    def internal_server_error(e):858        return "internal server error", 500859860    @app.errorhandler(Forbidden)861    def forbidden(e):862        return "forbidden", 403863864    @app.route("/")865    def index():866        flask.abort(404)867868    @app.route("/error")869    def error():870        1 // 0871872    @app.route("/forbidden")873    def error2():874        flask.abort(403)875876    rv = client.get("/")877    assert rv.status_code == 404878    assert rv.data == b"not found"879    rv = client.get("/error")880    assert rv.status_code == 500881    assert b"internal server error" == rv.data882    rv = client.get("/forbidden")883    assert rv.status_code == 403884    assert b"forbidden" == rv.data885886887def test_error_handler_unknown_code(app):888    with pytest.raises(KeyError) as exc_info:889        app.register_error_handler(999, lambda e: ("999", 999))890891    assert "Use a subclass" in exc_info.value.args[0]892893894def test_error_handling_processing(app, client):895    app.testing = False896897    @app.errorhandler(500)898    def internal_server_error(e):899        return "internal server error", 500900901    @app.route("/")902    def broken_func():903        1 // 0904905    @app.after_request906    def after_request(resp):907        resp.mimetype = "text/x-special"908        return resp909910    resp = client.get("/")911    assert resp.mimetype == "text/x-special"912    assert resp.data == b"internal server error"913914915def test_baseexception_error_handling(app, client):916    app.testing = False917918    @app.route("/")919    def broken_func():920        raise KeyboardInterrupt()921922    with pytest.raises(KeyboardInterrupt):923        client.get("/")924925        ctx = flask._request_ctx_stack.top926        assert ctx.preserved927        assert type(ctx._preserved_exc) is KeyboardInterrupt928929930def test_before_request_and_routing_errors(app, client):931    @app.before_request932    def attach_something():933        flask.g.something = "value"934935    @app.errorhandler(404)936    def return_something(error):937        return flask.g.something, 404938939    rv = client.get("/")940    assert rv.status_code == 404941    assert rv.data == b"value"942943944def test_user_error_handling(app, client):945    class MyException(Exception):946        pass947948    @app.errorhandler(MyException)949    def handle_my_exception(e):950        assert isinstance(e, MyException)951        return "42"952953    @app.route("/")954    def index():955        raise MyException()956957    assert client.get("/").data == b"42"958959960def test_http_error_subclass_handling(app, client):961    class ForbiddenSubclass(Forbidden):962        pass963964    @app.errorhandler(ForbiddenSubclass)965    def handle_forbidden_subclass(e):966        assert isinstance(e, ForbiddenSubclass)967        return "banana"968969    @app.errorhandler(403)970    def handle_403(e):971        assert not isinstance(e, ForbiddenSubclass)972        assert isinstance(e, Forbidden)973        return "apple"974975    @app.route("/1")976    def index1():977        raise ForbiddenSubclass()978979    @app.route("/2")980    def index2():981        flask.abort(403)982983    @app.route("/3")984    def index3():985        raise Forbidden()986987    assert client.get("/1").data == b"banana"988    assert client.get("/2").data == b"apple"989    assert client.get("/3").data == b"apple"990991992def test_errorhandler_precedence(app, client):993    class E1(Exception):994        pass995996    class E2(Exception):997        pass998999    class E3(E1, E2):1000        pass10011002    @app.errorhandler(E2)1003    def handle_e2(e):1004        return "E2"10051006    @app.errorhandler(Exception)1007    def handle_exception(e):1008        return "Exception"10091010    @app.route("/E1")1011    def raise_e1():1012        raise E110131014    @app.route("/E3")1015    def raise_e3():1016        raise E310171018    rv = client.get("/E1")1019    assert rv.data == b"Exception"10201021    rv = client.get("/E3")1022    assert rv.data == b"E2"102310241025def test_trapping_of_bad_request_key_errors(app, client):1026    @app.route("/key")1027    def fail():1028        flask.request.form["missing_key"]10291030    @app.route("/abort")1031    def allow_abort():1032        flask.abort(400)10331034    rv = client.get("/key")1035    assert rv.status_code == 4001036    assert b"missing_key" not in rv.data1037    rv = client.get("/abort")1038    assert rv.status_code == 40010391040    app.debug = True1041    with pytest.raises(KeyError) as e:1042        client.get("/key")1043    assert e.errisinstance(BadRequest)1044    assert "missing_key" in e.value.get_description()1045    rv = client.get("/abort")1046    assert rv.status_code == 40010471048    app.debug = False1049    app.config["TRAP_BAD_REQUEST_ERRORS"] = True1050    with pytest.raises(KeyError):1051        client.get("/key")1052    with pytest.raises(BadRequest):1053        client.get("/abort")105410551056def test_trapping_of_all_http_exceptions(app, client):1057    app.config["TRAP_HTTP_EXCEPTIONS"] = True10581059    @app.route("/fail")1060    def fail():1061        flask.abort(404)10621063    with pytest.raises(NotFound):1064        client.get("/fail")106510661067def test_error_handler_after_processor_error(app, client):1068    app.testing = False10691070    @app.before_request1071    def before_request():1072        if _trigger == "before":1073            1 // 010741075    @app.after_request1076    def after_request(response):1077        if _trigger == "after":1078            1 // 01079        return response10801081    @app.route("/")1082    def index():1083        return "Foo"10841085    @app.errorhandler(500)1086    def internal_server_error(e):1087        return "Hello Server Error", 50010881089    for _trigger in "before", "after":1090        rv = client.get("/")1091        assert rv.status_code == 5001092        assert rv.data == b"Hello Server Error"109310941095def test_enctype_debug_helper(app, client):1096    from flask.debughelpers import DebugFilesKeyError10971098    app.debug = True10991100    @app.route("/fail", methods=["POST"])1101    def index():1102        return flask.request.files["foo"].filename11031104    # with statement is important because we leave an exception on the1105    # stack otherwise and we want to ensure that this is not the case1106    # to not negatively affect other tests.1107    with client:1108        with pytest.raises(DebugFilesKeyError) as e:1109            client.post("/fail", data={"foo": "index.txt"})1110        assert "no file contents were transmitted" in str(e.value)1111        assert "This was submitted: 'index.txt'" in str(e.value)111211131114def test_response_types(app, client):1115    @app.route("/text")1116    def from_text():1117        return "Hällo Wörld"11181119    @app.route("/bytes")1120    def from_bytes():1121        return "Hällo Wörld".encode()11221123    @app.route("/full_tuple")1124    def from_full_tuple():1125        return (1126            "Meh",1127            400,1128            {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1129        )11301131    @app.route("/text_headers")1132    def from_text_headers():1133        return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}11341135    @app.route("/text_status")1136    def from_text_status():1137        return "Hi, status!", 40011381139    @app.route("/response_headers")1140    def from_response_headers():1141        return (1142            flask.Response(1143                "Hello world", 404, {"Content-Type": "text/html", "X-Foo": "Baz"}1144            ),1145            {"Content-Type": "text/plain", "X-Foo": "Bar", "X-Bar": "Foo"},1146        )11471148    @app.route("/response_status")1149    def from_response_status():1150        return app.response_class("Hello world", 400), 50011511152    @app.route("/wsgi")1153    def from_wsgi():1154        return NotFound()11551156    @app.route("/dict")1157    def from_dict():1158        return {"foo": "bar"}, 20111591160    assert client.get("/text").data == "Hällo Wörld".encode()1161    assert client.get("/bytes").data == "Hällo Wörld".encode()11621163    rv = client.get("/full_tuple")1164    assert rv.data == b"Meh"1165    assert rv.headers["X-Foo"] == "Testing"1166    assert rv.status_code == 4001167    assert rv.mimetype == "text/plain"11681169    rv = client.get("/text_headers")1170    assert rv.data == b"Hello"1171    assert rv.headers["X-Foo"] == "Test"1172    assert rv.status_code == 2001173    assert rv.mimetype == "text/plain"11741175    rv = client.get("/text_status")1176    assert rv.data == b"Hi, status!"1177    assert rv.status_code == 4001178    assert rv.mimetype == "text/html"11791180    rv = client.get("/response_headers")1181    assert rv.data == b"Hello world"1182    assert rv.content_type == "text/plain"1183    assert rv.headers.getlist("X-Foo") == ["Bar"]1184    assert rv.headers["X-Bar"] == "Foo"1185    assert rv.status_code == 40411861187    rv = client.get("/response_status")1188    assert rv.data == b"Hello world"1189    assert rv.status_code == 50011901191    rv = client.get("/wsgi")1192    assert b"Not Found" in rv.data1193    assert rv.status_code == 40411941195    rv = client.get("/dict")1196    assert rv.json == {"foo": "bar"}1197    assert rv.status_code == 201119811991200def test_response_type_errors():1201    app = flask.Flask(__name__)1202    app.testing = True12031204    @app.route("/none")1205    def from_none():1206        pass12071208    @app.route("/small_tuple")1209    def from_small_tuple():1210        return ("Hello",)12111212    @app.route("/large_tuple")1213    def from_large_tuple():1214        return "Hello", 234, {"X-Foo": "Bar"}, "???"12151216    @app.route("/bad_type")1217    def from_bad_type():1218        return True12191220    @app.route("/bad_wsgi")1221    def from_bad_wsgi():1222        return lambda: None12231224    c = app.test_client()12251226    with pytest.raises(TypeError) as e:1227        c.get("/none")1228        assert "returned None" in str(e.value)1229        assert "from_none" in str(e.value)12301231    with pytest.raises(TypeError) as e:1232        c.get("/small_tuple")1233        assert "tuple must have the form" in str(e.value)12341235    pytest.raises(TypeError, c.get, "/large_tuple")12361237    with pytest.raises(TypeError) as e:1238        c.get("/bad_type")1239        assert "it was a bool" in str(e.value)12401241    pytest.raises(TypeError, c.get, "/bad_wsgi")124212431244def test_make_response(app, req_ctx):1245    rv = flask.make_response()1246    assert rv.status_code == 2001247    assert rv.data == b""1248    assert rv.mimetype == "text/html"12491250    rv = flask.make_response("Awesome")1251    assert rv.status_code == 2001252    assert rv.data == b"Awesome"1253    assert rv.mimetype == "text/html"12541255    rv = flask.make_response("W00t", 404)1256    assert rv.status_code == 4041257    assert rv.data == b"W00t"1258    assert rv.mimetype == "text/html"125912601261def test_make_response_with_response_instance(app, req_ctx):1262    rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1263    assert rv.status_code == 4001264    assert rv.data == b'{"msg":"W00t"}\n'1265    assert rv.mimetype == "application/json"12661267    rv = flask.make_response(flask.Response(""), 400)1268    assert rv.status_code == 4001269    assert rv.data == b""1270    assert rv.mimetype == "text/html"12711272    rv = flask.make_response(1273        flask.Response("", headers={"Content-Type": "text/html"}),1274        400,1275        [("X-Foo", "bar")],1276    )1277    assert rv.status_code == 4001278    assert rv.headers["Content-Type"] == "text/html"1279    assert rv.headers["X-Foo"] == "bar"128012811282def test_jsonify_no_prettyprint(app, req_ctx):1283    app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1284    compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1285    uncompressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}12861287    rv = flask.make_response(flask.jsonify(uncompressed_msg), 200)1288    assert rv.data == compressed_msg128912901291def test_jsonify_prettyprint(app, req_ctx):1292    app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1293    compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1294    pretty_response = (1295        b'{\n  "msg": {\n    "submsg": "W00t"\n  }, \n  "msg2": "foobar"\n}\n'1296    )12971298    rv = flask.make_response(flask.jsonify(compressed_msg), 200)1299    assert rv.data == pretty_response130013011302def test_jsonify_mimetype(app, req_ctx):1303    app.config.update({"JSONIFY_MIMETYPE": "application/vnd.api+json"})1304    msg = {"msg": {"submsg": "W00t"}}1305    rv = flask.make_response(flask.jsonify(msg), 200)1306    assert rv.mimetype == "application/vnd.api+json"130713081309@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")1310def test_json_dump_dataclass(app, req_ctx):1311    from dataclasses import make_dataclass13121313    Data = make_dataclass("Data", [("name", str)])1314    value = flask.json.dumps(Data("Flask"), app=app)1315    value = flask.json.loads(value, app=app)1316    assert value == {"name": "Flask"}131713181319def test_jsonify_args_and_kwargs_check(app, req_ctx):1320    with pytest.raises(TypeError) as e:1321        flask.jsonify("fake args", kwargs="fake")1322    assert "behavior undefined" in str(e.value)132313241325def test_url_generation(app, req_ctx):1326    @app.route("/hello/<name>", methods=["POST"])1327    def hello():1328        pass13291330    assert flask.url_for("hello", name="test x") == "/hello/test%20x"1331    assert (1332        flask.url_for("hello", name="test x", _external=True)1333        == "http://localhost/hello/test%20x"1334    )133513361337def test_build_error_handler(app):1338    # Test base case, a URL which results in a BuildError.1339    with app.test_request_context():1340        pytest.raises(BuildError, flask.url_for, "spam")13411342    # Verify the error is re-raised if not the current exception.1343    try:1344        with app.test_request_context():1345            flask.url_for("spam")1346    except BuildError as err:1347        error = err1348    try:1349        raise RuntimeError("Test case where BuildError is not current.")1350    except RuntimeError:1351        pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})13521353    # Test a custom handler.1354    def handler(error, endpoint, values):1355        # Just a test.1356        return "/test_handler/"13571358    app.url_build_error_handlers.append(handler)1359    with app.test_request_context():1360        assert flask.url_for("spam") == "/test_handler/"136113621363def test_build_error_handler_reraise(app):1364    # Test a custom handler which reraises the BuildError1365    def handler_raises_build_error(error, endpoint, values):1366        raise error13671368    app.url_build_error_handlers.append(handler_raises_build_error)13691370    with app.test_request_context():1371        pytest.raises(BuildError, flask.url_for, "not.existing")137213731374def test_url_for_passes_special_values_to_build_error_handler(app):1375    @app.url_build_error_handlers.append1376    def handler(error, endpoint, values):1377        assert values == {1378            "_external": False,1379            "_anchor": None,1380            "_method": None,1381            "_scheme": None,1382        }1383        return "handled"13841385    with app.test_request_context():1386        flask.url_for("/")138713881389def test_static_files(app, client):1390    rv = client.get("/static/index.html")1391    assert rv.status_code == 2001392    assert rv.data.strip() == b"<h1>Hello World!</h1>"1393    with app.test_request_context():1394        assert flask.url_for("static", filename="index.html") == "/static/index.html"1395    rv.close()139613971398def test_static_url_path():1399    app = flask.Flask(__name__, static_url_path="/foo")1400    app.testing = True1401    rv = app.test_client().get("/foo/index.html")1402    assert rv.status_code == 2001403    rv.close()14041405    with app.test_request_context():1406        assert flask.url_for("static", filename="index.html") == "/foo/index.html"140714081409def test_static_url_path_with_ending_slash():1410    app = flask.Flask(__name__, static_url_path="/foo/")1411    app.testing = True1412    rv = app.test_client().get("/foo/index.html")1413    assert rv.status_code == 2001414    rv.close()14151416    with app.test_request_context():1417        assert flask.url_for("static", filename="index.html") == "/foo/index.html"141814191420def test_static_url_empty_path(app):1421    app = flask.Flask(__name__, static_folder="", static_url_path="")1422    rv = app.test_client().open("/static/index.html", method="GET")1423    assert rv.status_code == 2001424    rv.close()142514261427def test_static_url_empty_path_default(app):1428    app = flask.Flask(__name__, static_folder="")1429    rv = app.test_client().open("/static/index.html", method="GET")1430    assert rv.status_code == 2001431    rv.close()143214331434@pytest.mark.skipif(sys.version_info < (3, 6), reason="requires Python >= 3.6")1435def test_static_folder_with_pathlib_path(app):1436    from pathlib import Path14371438    app = flask.Flask(__name__, static_folder=Path("static"))1439    rv = app.test_client().open("/static/index.html", method="GET")1440    assert rv.status_code == 2001441    rv.close()144214431444def test_static_folder_with_ending_slash():1445    app = flask.Flask(__name__, static_folder="static/")14461447    @app.route("/<path:path>")1448    def catch_all(path):1449        return path14501451    rv = app.test_client().get("/catch/all")1452    assert rv.data == b"catch/all"145314541455def test_static_route_with_host_matching():1456    app = flask.Flask(__name__, host_matching=True, static_host="example.com")1457    c = app.test_client()1458    rv = c.get("http://example.com/static/index.html")1459    assert rv.status_code == 2001460    rv.close()1461    with app.test_request_context():1462        rv = flask.url_for("static", filename="index.html", _external=True)1463        assert rv == "http://example.com/static/index.html"1464    # Providing static_host without host_matching=True should error.1465    with pytest.raises(Exception):1466        flask.Flask(__name__, static_host="example.com")1467    # Providing host_matching=True with static_folder1468    # but without static_host should error.1469    with pytest.raises(Exception):1470        flask.Flask(__name__, host_matching=True)1471    # Providing host_matching=True without static_host1472    # but with static_folder=None should not error.1473    flask.Flask(__name__, host_matching=True, static_folder=None)147414751476def test_request_locals():1477    assert repr(flask.g) == "<LocalProxy unbound>"1478    assert not flask.g147914801481def test_server_name_subdomain():1482    app = flask.Flask(__name__, subdomain_matching=True)1483    client = app.test_client()14841485    @app.route("/")1486    def index():1487        return "default"14881489    @app.route("/", subdomain="foo")1490    def subdomain():1491        return "subdomain"14921493    app.config["SERVER_NAME"] = "dev.local:5000"1494    rv = client.get("/")1495    assert rv.data == b"default"14961497    rv = client.get("/", "http://dev.local:5000")1498    assert rv.data == b"default"14991500    rv = client.get("/", "https://dev.local:5000")1501    assert rv.data == b"default"15021503    app.config["SERVER_NAME"] = "dev.local:443"1504    rv = client.get("/", "https://dev.local")15051506    # Werkzeug 1.0 fixes matching https scheme with 443 port1507    if rv.status_code != 404:1508        assert rv.data == b"default"15091510    app.config["SERVER_NAME"] = "dev.local"1511    rv = client.get("/", "https://dev.local")1512    assert rv.data == b"default"15131514    # suppress Werkzeug 1.0 warning about name mismatch1515    with pytest.warns(None):1516        rv = client.get("/", "http://foo.localhost")1517        assert rv.status_code == 40415181519    rv = client.get("/", "http://foo.dev.local")1520    assert rv.data == b"subdomain"152115221523@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning")1524@pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning")1525def test_exception_propagation(app, client):1526    def apprunner(config_key):1527        @app.route("/")1528        def index():1529            1 // 015301531        if config_key is not None:1532            app.config[config_key] = True1533            with pytest.raises(Exception):1534                client.get("/")1535        else:1536            assert client.get("/").status_code == 50015371538    # we have to run this test in an isolated thread because if the1539    # debug flag is set to true and an exception happens the context is1540    # not torn down.  This causes other tests that run after this fail1541    # when they expect no exception on the stack.1542    for config_key in "TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None:1543        t = Thread(target=apprunner, args=(config_key,))1544        t.start()1545        t.join()154615471548@pytest.mark.parametrize("debug", [True, False])1549@pytest.mark.parametrize("use_debugger", [True, False])1550@pytest.mark.parametrize("use_reloader", [True, False])1551@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1552def test_werkzeug_passthrough_errors(1553    monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1554):1555    rv = {}15561557    # Mocks werkzeug.serving.run_simple method1558    def run_simple_mock(*args, **kwargs):1559        rv["passthrough_errors"] = kwargs.get("passthrough_errors")15601561    monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1562    app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1563    app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)156415651566def test_max_content_length(app, client):1567    app.config["MAX_CONTENT_LENGTH"] = 6415681569    @app.before_request1570    def always_first():1571        flask.request.form["myfile"]1572        AssertionError()15731574    @app.route("/accept", methods=["POST"])1575    def accept_file():1576        flask.request.form["myfile"]1577        AssertionError()15781579    @app.errorhandler(413)1580    def catcher(error):1581        return "42"15821583    rv = client.post("/accept", data={"myfile": "foo" * 100})1584    assert rv.data == b"42"158515861587def test_url_processors(app, client):1588    @app.url_defaults1589    def add_language_code(endpoint, values):1590        if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1591            endpoint, "lang_code"1592        ):1593            values.setdefault("lang_code", flask.g.lang_code)15941595    @app.url_value_preprocessor1596    def pull_lang_code(endpoint, values):1597        flask.g.lang_code = values.pop("lang_code", None)15981599    @app.route("/<lang_code>/")1600    def index():1601        return flask.url_for("about")16021603    @app.route("/<lang_code>/about")1604    def about():1605        return flask.url_for("something_else")16061607    @app.route("/foo")1608    def something_else():1609        return flask.url_for("about", lang_code="en")16101611    assert client.get("/de/").data == b"/de/about"1612    assert client.get("/de/about").data == b"/foo"1613    assert client.get("/foo").data == b"/en/about"161416151616def test_inject_blueprint_url_defaults(app):1617    bp = flask.Blueprint("foo.bar.baz", __name__, template_folder="template")16181619    @bp.url_defaults1620    def bp_defaults(endpoint, values):1621        values["page"] = "login"16221623    @bp.route("/<page>")1624    def view(page):1625        pass16261627    app.register_blueprint(bp)16281629    values = dict()1630    app.inject_url_defaults("foo.bar.baz.view", values)1631    expected = dict(page="login")1632    assert values == expected16331634    with app.test_request_context("/somepage"):1635        url = flask.url_for("foo.bar.baz.view")1636    expected = "/login"1637    assert url == expected163816391640def test_nonascii_pathinfo(app, client):1641    @app.route("/киртест")1642    def index():1643        return "Hello World!"16441645    rv = client.get("/киртест")1646    assert rv.data == b"Hello World!"164716481649def test_debug_mode_complains_after_first_request(app, client):1650    app.debug = True16511652    @app.route("/")1653    def index():1654        return "Awesome"16551656    assert not app.got_first_request1657    assert client.get("/").data == b"Awesome"1658    with pytest.raises(AssertionError) as e:16591660        @app.route("/foo")1661        def broken():1662            return "Meh"16631664    assert "A setup function was called" in str(e.value)16651666    app.debug = False16671668    @app.route("/foo")1669    def working():1670        return "Meh"16711672    assert client.get("/foo").data == b"Meh"1673    assert app.got_first_request167416751676def test_before_first_request_functions(app, client):1677    got = []16781679    @app.before_first_request1680    def foo():1681        got.append(42)16821683    client.get("/")1684    assert got == [42]1685    client.get("/")1686    assert got == [42]1687    assert app.got_first_request168816891690def test_before_first_request_functions_concurrent(app, client):1691    got = []16921693    @app.before_first_request1694    def foo():1695        time.sleep(0.2)1696        got.append(42)16971698    def get_and_assert():1699        client.get("/")1700        assert got == [42]17011702    t = Thread(target=get_and_assert)1703    t.start()1704    get_and_assert()1705    t.join()1706    assert app.got_first_request170717081709def test_routing_redirect_debugging(app, client):1710    app.debug = True17111712    @app.route("/foo/", methods=["GET", "POST"])1713    def foo():1714        return "success"17151716    with client:1717        with pytest.raises(AssertionError) as e:1718            client.post("/foo", data={})1719        assert "http://localhost/foo/" in str(e.value)1720        assert "Make sure to directly send your POST-request to this URL" in str(1721            e.value1722        )17231724        rv = client.get("/foo", data={}, follow_redirects=True)1725        assert rv.data == b"success"17261727    app.debug = False1728    with client:1729        rv = client.post("/foo", data={}, follow_redirects=True)1730        assert rv.data == b"success"173117321733def test_route_decorator_custom_endpoint(app, client):1734    app.debug = True17351736    @app.route("/foo/")1737    def foo():1738        return flask.request.endpoint17391740    @app.route("/bar/", endpoint="bar")1741    def for_bar():1742        return flask.request.endpoint17431744    @app.route("/bar/123", endpoint="123")1745    def for_bar_foo():1746        return flask.request.endpoint17471748    with app.test_request_context():1749        assert flask.url_for("foo") == "/foo/"1750        assert flask.url_for("bar") == "/bar/"1751        assert flask.url_for("123") == "/bar/123"17521753    assert client.get("/foo/").data == b"foo"1754    assert client.get("/bar/").data == b"bar"1755    assert client.get("/bar/123").data == b"123"175617571758def test_preserve_only_once(app, client):1759    app.debug = True17601761    @app.route("/fail")1762    def fail_func():1763        1 // 017641765    for _x in range(3):1766        with pytest.raises(ZeroDivisionError):1767            client.get("/fail")17681769    assert flask._request_ctx_stack.top is not None1770    assert flask._app_ctx_stack.top is not None1771    # implicit appctx disappears too1772    flask._request_ctx_stack.top.pop()1773    assert flask._request_ctx_stack.top is None1774    assert flask._app_ctx_stack.top is None177517761777def test_preserve_remembers_exception(app, client):1778    app.debug = True1779    errors = []17801781    @app.route("/fail")1782    def fail_func():1783        1 // 017841785    @app.route("/success")1786    def success_func():1787        return "Okay"17881789    @app.teardown_request1790    def teardown_handler(exc):1791        errors.append(exc)17921793    # After this failure we did not yet call the teardown handler1794    with pytest.raises(ZeroDivisionError):1795        client.get("/fail")1796    assert errors == []17971798    # But this request triggers it, and it's an error1799    client.get("/success")1800    assert len(errors) == 21801    assert isinstance(errors[0], ZeroDivisionError)18021803    # At this point another request does nothing.1804    client.get("/success")1805    assert len(errors) == 31806    assert errors[1] is None180718081809def test_get_method_on_g(app_ctx):1810    assert flask.g.get("x") is None1811    assert flask.g.get("x", 11) == 111812    flask.g.x = 421813    assert flask.g.get("x") == 421814    assert flask.g.x == 42181518161817def test_g_iteration_protocol(app_ctx):1818    flask.g.foo = 231819    flask.g.bar = 421820    assert "foo" in flask.g1821    assert "foos" not in flask.g1822    assert sorted(flask.g) == ["bar", "foo"]182318241825def test_subdomain_basic_support():1826    app = flask.Flask(__name__, subdomain_matching=True)1827    app.config["SERVER_NAME"] = "localhost.localdomain"1828    client = app.test_client()18291830    @app.route("/")1831    def normal_index():1832        return "normal index"18331834    @app.route("/", subdomain="test")1835    def test_index():1836        return "test index"18371838    rv = client.get("/", "http://localhost.localdomain/")1839    assert rv.data == b"normal index"18401841    rv = client.get("/", "http://test.localhost.localdomain/")1842    assert rv.data == b"test index"184318441845def test_subdomain_matching():1846    app = flask.Flask(__name__, subdomain_matching=True)1847    client = app.test_client()1848    app.config["SERVER_NAME"] = "localhost.localdomain"18491850    @app.route("/", subdomain="<user>")1851    def index(user):1852        return f"index for {user}"18531854    rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1855    assert rv.data == b"index for mitsuhiko"185618571858def test_subdomain_matching_with_ports():1859    app = flask.Flask(__name__, subdomain_matching=True)1860    app.config["SERVER_NAME"] = "localhost.localdomain:3000"1861    client = app.test_client()18621863    @app.route("/", subdomain="<user>")1864    def index(user):1865        return f"index for {user}"18661867    rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1868    assert rv.data == b"index for mitsuhiko"186918701871@pytest.mark.parametrize("matching", (False, True))1872def test_subdomain_matching_other_name(matching):1873    app = flask.Flask(__name__, subdomain_matching=matching)1874    app.config["SERVER_NAME"] = "localhost.localdomain:3000"1875    client = app.test_client()18761877    @app.route("/")1878    def index():1879        return "", 20418801881    # suppress Werkzeug 0.15 warning about name mismatch1882    with pytest.warns(None):1883        # ip address can't match name1884        rv = client.get("/", "http://127.0.0.1:3000/")1885        assert rv.status_code == 404 if matching else 20418861887    # allow all subdomains if matching is disabled1888    rv = client.get("/", "http://www.localhost.localdomain:3000/")1889    assert rv.status_code == 404 if matching else 204189018911892def test_multi_route_rules(app, client):1893    @app.route("/")1894    @app.route("/<test>/")1895    def index(test="a"):1896        return test18971898    rv = client.open("/")1899    assert rv.data == b"a"1900    rv = client.open("/b/")1901    assert rv.data == b"b"190219031904def test_multi_route_class_views(app, client):1905    class View:1906        def __init__(self, app):1907            app.add_url_rule("/", "index", self.index)1908            app.add_url_rule("/<test>/", "index", self.index)19091910        def index(self, test="a"):1911            return test19121913    _ = View(app)1914    rv = client.open("/")1915    assert rv.data == b"a"1916    rv = client.open("/b/")1917    assert rv.data == b"b"191819191920def test_run_defaults(monkeypatch, app):1921    rv = {}19221923    # Mocks werkzeug.serving.run_simple method1924    def run_simple_mock(*args, **kwargs):1925        rv["result"] = "running..."19261927    monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1928    app.run()1929    assert rv["result"] == "running..."193019311932def test_run_server_port(monkeypatch, app):1933    rv = {}19341935    # Mocks werkzeug.serving.run_simple method1936    def run_simple_mock(hostname, port, application, *args, **kwargs):1937        rv["result"] = f"running on {hostname}:{port} ..."19381939    monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1940    hostname, port = "localhost", 80001941    app.run(hostname, port, debug=True)1942    assert rv["result"] == f"running on {hostname}:{port} ..."194319441945@pytest.mark.parametrize(1946    "host,port,server_name,expect_host,expect_port",1947    (1948        (None, None, "pocoo.org:8080", "pocoo.org", 8080),1949        ("localhost", None, "pocoo.org:8080", "localhost", 8080),1950        (None, 80, "pocoo.org:8080", "pocoo.org", 80),1951        ("localhost", 80, "pocoo.org:8080", "localhost", 80),1952        ("localhost", 0, "localhost:8080", "localhost", 0),1953        (None, None, "localhost:8080", "localhost", 8080),1954        (None, None, "localhost:0", "localhost", 0),1955    ),1956)1957def test_run_from_config(1958    monkeypatch, host, port, server_name, expect_host, expect_port, app1959):1960    def run_simple_mock(hostname, port, *args, **kwargs):1961        assert hostname == expect_host1962        assert port == expect_port19631964    monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1965    app.config["SERVER_NAME"] = server_name1966    app.run(host, port)196719681969def test_max_cookie_size(app, client, recwarn):1970    app.config["MAX_COOKIE_SIZE"] = 10019711972    # outside app context, default to Werkzeug static value,1973    # which is also the default config1974    response = flask.Response()1975    default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1976    assert response.max_cookie_size == default19771978    # inside app context, use app config1979    with app.app_context():1980        assert flask.Response().max_cookie_size == 10019811982    @app.route("/")1983    def index():1984        r = flask.Response("", status=204)1985        r.set_cookie("foo", "bar" * 100)1986        return r19871988    client.get("/")1989    assert len(recwarn) == 11990    w = recwarn.pop()1991    assert "cookie is too large" in str(w.message)19921993    app.config["MAX_COOKIE_SIZE"] = 019941995    client.get("/")1996    assert len(recwarn) == 0199719981999@require_cpython_gc2000def test_app_freed_on_zero_refcount():

The first 2,000 of 2,012 lines.