Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

1,937 lines · 52.2 KiB · Python

Last changed by

setting `SERVER_NAME` does not restrict routing for both `subdomain_matching` and `host_matching` (#5634)David Lordbefore adoption10bdf61

History of this file

Take it

The walk stopped after 200 commits: lines older than c34c84b point at it.

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 1–2why, one step back
1import gc
2import re

enable secret key rotation (#5632)David Lordbefore adoptiona20bcff

line 3why, one step back
3import typing as t

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 4–6why, one step back
4import uuid
5import warnings6import weakref

setting `SERVER_NAME` does not restrict routing for both `subdomain_matching` and `host_matching` (#5634)David Lordbefore adoption10bdf61

line 7why, one step back
7from contextlib import nullcontext

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 8–13why, one step back
8from datetime import datetime
9from datetime import timezone10from platform import python_implementation1112import pytest13import werkzeug.serving

Merge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689

line 14why, one step back
14from markupsafe import Markup

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 15–193why, one step back
15from werkzeug.exceptions import BadRequest
16from werkzeug.exceptions import Forbidden17from werkzeug.exceptions import NotFound18from werkzeug.http import parse_date19from werkzeug.routing import BuildError20from werkzeug.routing import RequestRedirect2122import flask2324require_cpython_gc = pytest.mark.skipif(25 python_implementation() != "CPython",26 reason="Requires CPython GC behavior",27)282930def test_options_work(app, client):31 @app.route("/", methods=["GET", "POST"])32 def index():33 return "Hello World"3435 rv = client.open("/", method="OPTIONS")36 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]37 assert rv.data == b""383940def test_options_on_multiple_rules(app, client):41 @app.route("/", methods=["GET", "POST"])42 def index():43 return "Hello World"4445 @app.route("/", methods=["PUT"])46 def index_put():47 return "Aha!"4849 rv = client.open("/", method="OPTIONS")50 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST", "PUT"]515253@pytest.mark.parametrize("method", ["get", "post", "put", "delete", "patch"])54def test_method_route(app, client, method):55 method_route = getattr(app, method)56 client_method = getattr(client, method)5758 @method_route("/")59 def hello():60 return "Hello"6162 assert client_method("/").data == b"Hello"636465def test_method_route_no_methods(app):66 with pytest.raises(TypeError):67 app.get("/", methods=["GET", "POST"])686970def test_provide_automatic_options_attr():71 app = flask.Flask(__name__)7273 def index():74 return "Hello World!"7576 index.provide_automatic_options = False77 app.route("/")(index)78 rv = app.test_client().open("/", method="OPTIONS")79 assert rv.status_code == 4058081 app = flask.Flask(__name__)8283 def index2():84 return "Hello World!"8586 index2.provide_automatic_options = True87 app.route("/", methods=["OPTIONS"])(index2)88 rv = app.test_client().open("/", method="OPTIONS")89 assert sorted(rv.allow) == ["OPTIONS"]909192def test_provide_automatic_options_kwarg(app, client):93 def index():94 return flask.request.method9596 def more():97 return flask.request.method9899 app.add_url_rule("/", view_func=index, provide_automatic_options=False)100 app.add_url_rule(101 "/more",102 view_func=more,103 methods=["GET", "POST"],104 provide_automatic_options=False,105 )106 assert client.get("/").data == b"GET"107108 rv = client.post("/")109 assert rv.status_code == 405110 assert sorted(rv.allow) == ["GET", "HEAD"]111112 rv = client.open("/", method="OPTIONS")113 assert rv.status_code == 405114115 rv = client.head("/")116 assert rv.status_code == 200117 assert not rv.data # head truncates118 assert client.post("/more").data == b"POST"119 assert client.get("/more").data == b"GET"120121 rv = client.delete("/more")122 assert rv.status_code == 405123 assert sorted(rv.allow) == ["GET", "HEAD", "POST"]124125 rv = client.open("/more", method="OPTIONS")126 assert rv.status_code == 405127128129def test_request_dispatching(app, client):130 @app.route("/")131 def index():132 return flask.request.method133134 @app.route("/more", methods=["GET", "POST"])135 def more():136 return flask.request.method137138 assert client.get("/").data == b"GET"139 rv = client.post("/")140 assert rv.status_code == 405141 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]142 rv = client.head("/")143 assert rv.status_code == 200144 assert not rv.data # head truncates145 assert client.post("/more").data == b"POST"146 assert client.get("/more").data == b"GET"147 rv = client.delete("/more")148 assert rv.status_code == 405149 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]150151152def test_disallow_string_for_allowed_methods(app):153 with pytest.raises(TypeError):154 app.add_url_rule("/", methods="GET POST", endpoint="test")155156157def test_url_mapping(app, client):158 random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"159160 def index():161 return flask.request.method162163 def more():164 return flask.request.method165166 def options():167 return random_uuid4168169 app.add_url_rule("/", "index", index)170 app.add_url_rule("/more", "more", more, methods=["GET", "POST"])171172 # Issue 1288: Test that automatic options are not added173 # when non-uppercase 'options' in methods174 app.add_url_rule("/options", "options", options, methods=["options"])175176 assert client.get("/").data == b"GET"177 rv = client.post("/")178 assert rv.status_code == 405179 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]180 rv = client.head("/")181 assert rv.status_code == 200182 assert not rv.data # head truncates183 assert client.post("/more").data == b"POST"184 assert client.get("/more").data == b"GET"185 rv = client.delete("/more")186 assert rv.status_code == 405187 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]188 rv = client.open("/options", method="OPTIONS")189 assert rv.status_code == 200190 assert random_uuid4 in rv.data.decode("utf-8")191192193def test_werkzeug_routing(app, client):

use ruff linter and formatter (#5331)David Lordbefore adoption9a12f34

lines 194–195why, one step back
194 from werkzeug.routing import Rule
195 from werkzeug.routing import Submount

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 196–214why, one step back
196
197 app.url_map.add(198 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])199 )200201 def bar():202 return "bar"203204 def index():205 return "index"206207 app.view_functions["bar"] = bar208 app.view_functions["index"] = index209210 assert client.get("/foo/").data == b"index"211 assert client.get("/foo/bar").data == b"bar"212213214def test_endpoint_decorator(app, client):

use ruff linter and formatter (#5331)David Lordbefore adoption9a12f34

lines 215–216why, one step back
215 from werkzeug.routing import Rule
216 from werkzeug.routing import Submount

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 217–256why, one step back
217
218 app.url_map.add(219 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])220 )221222 @app.endpoint("bar")223 def bar():224 return "bar"225226 @app.endpoint("index")227 def index():228 return "index"229230 assert client.get("/foo/").data == b"index"231 assert client.get("/foo/bar").data == b"bar"232233234def test_session(app, client):235 @app.route("/set", methods=["POST"])236 def set():237 assert not flask.session.accessed238 assert not flask.session.modified239 flask.session["value"] = flask.request.form["value"]240 assert flask.session.accessed241 assert flask.session.modified242 return "value set"243244 @app.route("/get")245 def get():246 assert not flask.session.accessed247 assert not flask.session.modified248 v = flask.session.get("value", "None")249 assert flask.session.accessed250 assert not flask.session.modified251 return v252253 assert client.post("/set", data={"value": "42"}).data == b"value set"254 assert client.get("/get").data == b"42"255256

Merge pull request #5054 from pallets/session-domainDavid Lordbefore adoptionc9a5660

lines 257–258why, one step back
257def test_session_path(app, client):
258 app.config.update(APPLICATION_ROOT="/foo")

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 259–297why, one step back
259
260 @app.route("/")261 def index():262 flask.session["testing"] = 42263 return "Hello World"264265 rv = client.get("/", "http://example.com:8080/foo")266 assert "path=/foo" in rv.headers["set-cookie"].lower()267268269def test_session_using_application_root(app, client):270 class PrefixPathMiddleware:271 def __init__(self, app, prefix):272 self.app = app273 self.prefix = prefix274275 def __call__(self, environ, start_response):276 environ["SCRIPT_NAME"] = self.prefix277 return self.app(environ, start_response)278279 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, "/bar")280 app.config.update(APPLICATION_ROOT="/bar")281282 @app.route("/")283 def index():284 flask.session["testing"] = 42285 return "Hello World"286287 rv = client.get("/", "http://example.com:8080/")288 assert "path=/bar" in rv.headers["set-cookie"].lower()289290291def test_session_using_session_settings(app, client):292 app.config.update(293 SERVER_NAME="www.example.com:8080",294 APPLICATION_ROOT="/test",295 SESSION_COOKIE_DOMAIN=".example.com",296 SESSION_COOKIE_HTTPONLY=False,297 SESSION_COOKIE_SECURE=True,

add SESSION_COOKIE_PARTITIONED config (#5499)David Lordbefore adoptionce08bc7

line 298why, one step back
298 SESSION_COOKIE_PARTITIONED=True,

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 299–314why, one step back
299 SESSION_COOKIE_SAMESITE="Lax",
300 SESSION_COOKIE_PATH="/",301 )302303 @app.route("/")304 def index():305 flask.session["testing"] = 42306 return "Hello World"307308 @app.route("/clear")309 def clear():310 flask.session.pop("testing", None)311 return "Goodbye World"312313 rv = client.get("/", "http://www.example.com:8080/test/")314 cookie = rv.headers["set-cookie"].lower()

Merge branch '2.2.x'David Lordbefore adoptionfa0ceb6

lines 315–316why, one step back
315 # or condition for Werkzeug < 2.3
316 assert "domain=example.com" in cookie or "domain=.example.com" in cookie

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 317–320why, one step back
317 assert "path=/" in cookie
318 assert "secure" in cookie319 assert "httponly" not in cookie320 assert "samesite" in cookie

add SESSION_COOKIE_PARTITIONED config (#5499)David Lordbefore adoptionce08bc7

line 321why, one step back
321 assert "partitioned" in cookie

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 322–325why, one step back
322
323 rv = client.get("/clear", "http://www.example.com:8080/test/")324 cookie = rv.headers["set-cookie"].lower()325 assert "session=;" in cookie

Merge branch '2.2.x'David Lordbefore adoptionfa0ceb6

lines 326–327why, one step back
326 # or condition for Werkzeug < 2.3
327 assert "domain=example.com" in cookie or "domain=.example.com" in cookie

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 328–330why, one step back
328 assert "path=/" in cookie
329 assert "secure" in cookie330 assert "samesite" in cookie

add SESSION_COOKIE_PARTITIONED config (#5499)David Lordbefore adoptionce08bc7

line 331why, one step back
331 assert "partitioned" in cookie

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 332–371why, one step back
332
333334def test_session_using_samesite_attribute(app, client):335 @app.route("/")336 def index():337 flask.session["testing"] = 42338 return "Hello World"339340 app.config.update(SESSION_COOKIE_SAMESITE="invalid")341342 with pytest.raises(ValueError):343 client.get("/")344345 app.config.update(SESSION_COOKIE_SAMESITE=None)346 rv = client.get("/")347 cookie = rv.headers["set-cookie"].lower()348 assert "samesite" not in cookie349350 app.config.update(SESSION_COOKIE_SAMESITE="Strict")351 rv = client.get("/")352 cookie = rv.headers["set-cookie"].lower()353 assert "samesite=strict" in cookie354355 app.config.update(SESSION_COOKIE_SAMESITE="Lax")356 rv = client.get("/")357 cookie = rv.headers["set-cookie"].lower()358 assert "samesite=lax" in cookie359360361def test_missing_session(app):362 app.secret_key = None363364 def expect_exception(f, *args, **kwargs):365 e = pytest.raises(RuntimeError, f, *args, **kwargs)366 assert e.value.args and "session is unavailable" in e.value.args[0]367368 with app.test_request_context():369 assert flask.session.get("missing_key") is None370 expect_exception(flask.session.__setitem__, "foo", 42)371 expect_exception(flask.session.pop, "foo")

enable secret key rotation (#5632)David Lordbefore adoptiona20bcff

lines 372–392why, one step back
372
373374def test_session_secret_key_fallbacks(app, client) -> None:375 @app.post("/")376 def set_session() -> str:377 flask.session["a"] = 1378 return ""379380 @app.get("/")381 def get_session() -> dict[str, t.Any]:382 return dict(flask.session)383384 # Set session with initial secret key385 client.post()386 assert client.get().json == {"a": 1}387 # Change secret key, session can't be loaded and appears empty388 app.secret_key = "new test key"389 assert client.get().json == {}390 # Add initial secret key as fallback, session can be loaded391 app.config["SECRET_KEY_FALLBACKS"] = ["test key"]392 assert client.get().json == {"a": 1}

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 393–448why, one step back
393
394395def test_session_expiration(app, client):396 permanent = True397398 @app.route("/")399 def index():400 flask.session["test"] = 42401 flask.session.permanent = permanent402 return ""403404 @app.route("/test")405 def test():406 return str(flask.session.permanent)407408 rv = client.get("/")409 assert "set-cookie" in rv.headers410 match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])411 expires = parse_date(match.group())412 expected = datetime.now(timezone.utc) + app.permanent_session_lifetime413 assert expires.year == expected.year414 assert expires.month == expected.month415 assert expires.day == expected.day416417 rv = client.get("/test")418 assert rv.data == b"True"419420 permanent = False421 rv = client.get("/")422 assert "set-cookie" in rv.headers423 match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])424 assert match is None425426427def test_session_stored_last(app, client):428 @app.after_request429 def modify_session(response):430 flask.session["foo"] = 42431 return response432433 @app.route("/")434 def dump_session_contents():435 return repr(flask.session.get("foo"))436437 assert client.get("/").data == b"None"438 assert client.get("/").data == b"42"439440441def test_session_special_types(app, client):442 now = datetime.now(timezone.utc).replace(microsecond=0)443 the_uuid = uuid.uuid4()444445 @app.route("/")446 def dump_session_contents():447 flask.session["t"] = (1, 2, 3)448 flask.session["b"] = b"\xff"

Merge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689

line 449why, one step back
449 flask.session["m"] = Markup("<html>")

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 450–460why, one step back
450 flask.session["u"] = the_uuid
451 flask.session["d"] = now452 flask.session["t_tag"] = {" t": "not-a-tuple"}453 flask.session["di_t_tag"] = {" t__": "not-a-tuple"}454 flask.session["di_tag"] = {" di": "not-a-dict"}455 return "", 204456457 with client:458 client.get("/")459 s = flask.session460 assert s["t"] == (1, 2, 3)

use ruff linter and formatter (#5331)David Lordbefore adoption9a12f34

line 461why, one step back
461 assert type(s["b"]) is bytes # noqa: E721

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

line 462why, one step back
462 assert s["b"] == b"\xff"

use ruff linter and formatter (#5331)David Lordbefore adoption9a12f34

line 463why, one step back
463 assert type(s["m"]) is Markup # noqa: E721

Merge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689

line 464why, one step back
464 assert s["m"] == Markup("<html>")

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 465–530why, one step back
465 assert s["u"] == the_uuid
466 assert s["d"] == now467 assert s["t_tag"] == {" t": "not-a-tuple"}468 assert s["di_t_tag"] == {" t__": "not-a-tuple"}469 assert s["di_tag"] == {" di": "not-a-dict"}470471472def test_session_cookie_setting(app):473 is_permanent = True474475 @app.route("/bump")476 def bump():477 rv = flask.session["foo"] = flask.session.get("foo", 0) + 1478 flask.session.permanent = is_permanent479 return str(rv)480481 @app.route("/read")482 def read():483 return str(flask.session.get("foo", 0))484485 def run_test(expect_header):486 with app.test_client() as c:487 assert c.get("/bump").data == b"1"488 assert c.get("/bump").data == b"2"489 assert c.get("/bump").data == b"3"490491 rv = c.get("/read")492 set_cookie = rv.headers.get("set-cookie")493 assert (set_cookie is not None) == expect_header494 assert rv.data == b"3"495496 is_permanent = True497 app.config["SESSION_REFRESH_EACH_REQUEST"] = True498 run_test(expect_header=True)499500 is_permanent = True501 app.config["SESSION_REFRESH_EACH_REQUEST"] = False502 run_test(expect_header=False)503504 is_permanent = False505 app.config["SESSION_REFRESH_EACH_REQUEST"] = True506 run_test(expect_header=False)507508 is_permanent = False509 app.config["SESSION_REFRESH_EACH_REQUEST"] = False510 run_test(expect_header=False)511512513def test_session_vary_cookie(app, client):514 @app.route("/set")515 def set_session():516 flask.session["test"] = "test"517 return ""518519 @app.route("/get")520 def get():521 return flask.session.get("test")522523 @app.route("/getitem")524 def getitem():525 return flask.session["test"]526527 @app.route("/setdefault")528 def setdefault():529 return flask.session.setdefault("test", "default")530

Merge pull request from GHSA-m2qf-hxjv-5gpqDavid Lordbefore adoption70f906c

lines 531–535why, one step back
531 @app.route("/clear")
532 def clear():533 flask.session.clear()534 return ""535

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 536–567why, one step back
536 @app.route("/vary-cookie-header-set")
537 def vary_cookie_header_set():538 response = flask.Response()539 response.vary.add("Cookie")540 flask.session["test"] = "test"541 return response542543 @app.route("/vary-header-set")544 def vary_header_set():545 response = flask.Response()546 response.vary.update(("Accept-Encoding", "Accept-Language"))547 flask.session["test"] = "test"548 return response549550 @app.route("/no-vary-header")551 def no_vary_header():552 return ""553554 def expect(path, header_value="Cookie"):555 rv = client.get(path)556557 if header_value:558 # The 'Vary' key should exist in the headers only once.559 assert len(rv.headers.get_all("Vary")) == 1560 assert rv.headers["Vary"] == header_value561 else:562 assert "Vary" not in rv.headers563564 expect("/set")565 expect("/get")566 expect("/getitem")567 expect("/setdefault")

Merge pull request from GHSA-m2qf-hxjv-5gpqDavid Lordbefore adoption70f906c

line 568why, one step back
568 expect("/clear")

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 569–571why, one step back
569 expect("/vary-cookie-header-set")
570 expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")571 expect("/no-vary-header", None)

Merge pull request from GHSA-m2qf-hxjv-5gpqDavid Lordbefore adoption70f906c

lines 572–588why, one step back
572
573574def test_session_refresh_vary(app, client):575 @app.get("/login")576 def login():577 flask.session["user_id"] = 1578 flask.session.permanent = True579 return ""580581 @app.get("/ignored")582 def ignored():583 return ""584585 rv = client.get("/login")586 assert rv.headers["Vary"] == "Cookie"587 rv = client.get("/ignored")588 assert rv.headers["Vary"] == "Cookie"

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 589–610why, one step back
589
590591def test_flashes(app, req_ctx):592 assert not flask.session.modified593 flask.flash("Zap")594 flask.session.modified = False595 flask.flash("Zip")596 assert flask.session.modified597 assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]598599600def test_extended_flashing(app):601 # Be sure app.testing=True below, else tests can fail silently.602 #603 # Specifically, if app.testing is not set to True, the AssertionErrors604 # in the view functions will cause a 500 response to the test client605 # instead of propagating exceptions.606607 @app.route("/")608 def index():609 flask.flash("Hello World")610 flask.flash("Hello World", "error")

Merge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689

line 611why, one step back
611 flask.flash(Markup("<em>Testing</em>"), "warning")

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 612–619why, one step back
612 return ""
613614 @app.route("/test/")615 def test():616 messages = flask.get_flashed_messages()617 assert list(messages) == [618 "Hello World",619 "Hello World",

Merge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689

line 620why, one step back
620 Markup("<em>Testing</em>"),

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 621–630why, one step back
621 ]
622 return ""623624 @app.route("/test_with_categories/")625 def test_with_categories():626 messages = flask.get_flashed_messages(with_categories=True)627 assert len(messages) == 3628 assert list(messages) == [629 ("message", "Hello World"),630 ("error", "Hello World"),

Merge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689

line 631why, one step back
631 ("warning", Markup("<em>Testing</em>")),

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 632–649why, one step back
632 ]
633 return ""634635 @app.route("/test_filter/")636 def test_filter():637 messages = flask.get_flashed_messages(638 category_filter=["message"], with_categories=True639 )640 assert list(messages) == [("message", "Hello World")]641 return ""642643 @app.route("/test_filters/")644 def test_filters():645 messages = flask.get_flashed_messages(646 category_filter=["message", "warning"], with_categories=True647 )648 assert list(messages) == [649 ("message", "Hello World"),

Merge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689

line 650why, one step back
650 ("warning", Markup("<em>Testing</em>")),

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 651–658why, one step back
651 ]
652 return ""653654 @app.route("/test_filters_without_returning_categories/")655 def test_filters2():656 messages = flask.get_flashed_messages(category_filter=["message", "warning"])657 assert len(messages) == 2658 assert messages[0] == "Hello World"

Merge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689

line 659why, one step back
659 assert messages[1] == Markup("<em>Testing</em>")

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 660–789why, one step back
660 return ""
661662 # Create new test client on each test to clean flashed messages.663664 client = app.test_client()665 client.get("/")666 client.get("/test_with_categories/")667668 client = app.test_client()669 client.get("/")670 client.get("/test_filter/")671672 client = app.test_client()673 client.get("/")674 client.get("/test_filters/")675676 client = app.test_client()677 client.get("/")678 client.get("/test_filters_without_returning_categories/")679680681def test_request_processing(app, client):682 evts = []683684 @app.before_request685 def before_request():686 evts.append("before")687688 @app.after_request689 def after_request(response):690 response.data += b"|after"691 evts.append("after")692 return response693694 @app.route("/")695 def index():696 assert "before" in evts697 assert "after" not in evts698 return "request"699700 assert "after" not in evts701 rv = client.get("/").data702 assert "after" in evts703 assert rv == b"request|after"704705706def test_request_preprocessing_early_return(app, client):707 evts = []708709 @app.before_request710 def before_request1():711 evts.append(1)712713 @app.before_request714 def before_request2():715 evts.append(2)716 return "hello"717718 @app.before_request719 def before_request3():720 evts.append(3)721 return "bye"722723 @app.route("/")724 def index():725 evts.append("index")726 return "damnit"727728 rv = client.get("/").data.strip()729 assert rv == b"hello"730 assert evts == [1, 2]731732733def test_after_request_processing(app, client):734 @app.route("/")735 def index():736 @flask.after_this_request737 def foo(response):738 response.headers["X-Foo"] = "a header"739 return response740741 return "Test"742743 resp = client.get("/")744 assert resp.status_code == 200745 assert resp.headers["X-Foo"] == "a header"746747748def test_teardown_request_handler(app, client):749 called = []750751 @app.teardown_request752 def teardown_request(exc):753 called.append(True)754 return "Ignored"755756 @app.route("/")757 def root():758 return "Response"759760 rv = client.get("/")761 assert rv.status_code == 200762 assert b"Response" in rv.data763 assert len(called) == 1764765766def test_teardown_request_handler_debug_mode(app, client):767 called = []768769 @app.teardown_request770 def teardown_request(exc):771 called.append(True)772 return "Ignored"773774 @app.route("/")775 def root():776 return "Response"777778 rv = client.get("/")779 assert rv.status_code == 200780 assert b"Response" in rv.data781 assert len(called) == 1782783784def test_teardown_request_handler_error(app, client):785 called = []786 app.testing = False787788 @app.teardown_request789 def teardown_request1(exc):

fix flake8 bugbear findingsDavid Lordbefore adoptionc49ce2e

line 790why, one step back
790 assert type(exc) is ZeroDivisionError

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 791–801why, one step back
791 called.append(True)
792 # This raises a new error and blows away sys.exc_info(), so we can793 # test that all teardown_requests get passed the same original794 # exception.795 try:796 raise TypeError()797 except Exception:798 pass799800 @app.teardown_request801 def teardown_request2(exc):

fix flake8 bugbear findingsDavid Lordbefore adoptionc49ce2e

line 802why, one step back
802 assert type(exc) is ZeroDivisionError

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 803–813why, one step back
803 called.append(True)
804 # This raises a new error and blows away sys.exc_info(), so we can805 # test that all teardown_requests get passed the same original806 # exception.807 try:808 raise TypeError()809 except Exception:810 pass811812 @app.route("/")813 def fails():

use ruff linter and formatter (#5331)David Lordbefore adoption9a12f34

line 814why, one step back
814 raise ZeroDivisionError

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 815–880why, one step back
815
816 rv = client.get("/")817 assert rv.status_code == 500818 assert b"Internal Server Error" in rv.data819 assert len(called) == 2820821822def test_before_after_request_order(app, client):823 called = []824825 @app.before_request826 def before1():827 called.append(1)828829 @app.before_request830 def before2():831 called.append(2)832833 @app.after_request834 def after1(response):835 called.append(4)836 return response837838 @app.after_request839 def after2(response):840 called.append(3)841 return response842843 @app.teardown_request844 def finish1(exc):845 called.append(6)846847 @app.teardown_request848 def finish2(exc):849 called.append(5)850851 @app.route("/")852 def index():853 return "42"854855 rv = client.get("/")856 assert rv.data == b"42"857 assert called == [1, 2, 3, 4, 5, 6]858859860def test_error_handling(app, client):861 app.testing = False862863 @app.errorhandler(404)864 def not_found(e):865 return "not found", 404866867 @app.errorhandler(500)868 def internal_server_error(e):869 return "internal server error", 500870871 @app.errorhandler(Forbidden)872 def forbidden(e):873 return "forbidden", 403874875 @app.route("/")876 def index():877 flask.abort(404)878879 @app.route("/error")880 def error():

use ruff linter and formatter (#5331)David Lordbefore adoption9a12f34

line 881why, one step back
881 raise ZeroDivisionError

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 882–906why, one step back
882
883 @app.route("/forbidden")884 def error2():885 flask.abort(403)886887 rv = client.get("/")888 assert rv.status_code == 404889 assert rv.data == b"not found"890 rv = client.get("/error")891 assert rv.status_code == 500892 assert b"internal server error" == rv.data893 rv = client.get("/forbidden")894 assert rv.status_code == 403895 assert b"forbidden" == rv.data896897898def test_error_handling_processing(app, client):899 app.testing = False900901 @app.errorhandler(500)902 def internal_server_error(e):903 return "internal server error", 500904905 @app.route("/")906 def broken_func():

use ruff linter and formatter (#5331)David Lordbefore adoption9a12f34

line 907why, one step back
907 raise ZeroDivisionError

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 908–1076why, one step back
908
909 @app.after_request910 def after_request(resp):911 resp.mimetype = "text/x-special"912 return resp913914 resp = client.get("/")915 assert resp.mimetype == "text/x-special"916 assert resp.data == b"internal server error"917918919def test_baseexception_error_handling(app, client):920 app.testing = False921922 @app.route("/")923 def broken_func():924 raise KeyboardInterrupt()925926 with pytest.raises(KeyboardInterrupt):927 client.get("/")928929930def 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"102310241025@pytest.mark.parametrize(1026 ("debug", "trap", "expect_key", "expect_abort"),1027 [(False, None, True, True), (True, None, False, True), (False, True, False, False)],1028)1029def test_trap_bad_request_key_error(app, client, debug, trap, expect_key, expect_abort):1030 app.config["DEBUG"] = debug1031 app.config["TRAP_BAD_REQUEST_ERRORS"] = trap10321033 @app.route("/key")1034 def fail():1035 flask.request.form["missing_key"]10361037 @app.route("/abort")1038 def allow_abort():1039 flask.abort(400)10401041 if expect_key:1042 rv = client.get("/key")1043 assert rv.status_code == 4001044 assert b"missing_key" not in rv.data1045 else:1046 with pytest.raises(KeyError) as exc_info:1047 client.get("/key")10481049 assert exc_info.errisinstance(BadRequest)1050 assert "missing_key" in exc_info.value.get_description()10511052 if expect_abort:1053 rv = client.get("/abort")1054 assert rv.status_code == 4001055 else:1056 with pytest.raises(BadRequest):1057 client.get("/abort")105810591060def test_trapping_of_all_http_exceptions(app, client):1061 app.config["TRAP_HTTP_EXCEPTIONS"] = True10621063 @app.route("/fail")1064 def fail():1065 flask.abort(404)10661067 with pytest.raises(NotFound):1068 client.get("/fail")106910701071def test_error_handler_after_processor_error(app, client):1072 app.testing = False10731074 @app.before_request1075 def before_request():1076 if _trigger == "before":

use ruff linter and formatter (#5331)David Lordbefore adoption9a12f34

line 1077why, one step back
1077 raise ZeroDivisionError

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 1078–1081why, one step back
1078
1079 @app.after_request1080 def after_request(response):1081 if _trigger == "after":

use ruff linter and formatter (#5331)David Lordbefore adoption9a12f34

lines 1082–1083why, one step back
1082 raise ZeroDivisionError
1083

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 1084–1470why, one step back
1084 return response
10851086 @app.route("/")1087 def index():1088 return "Foo"10891090 @app.errorhandler(500)1091 def internal_server_error(e):1092 return "Hello Server Error", 50010931094 for _trigger in "before", "after":1095 rv = client.get("/")1096 assert rv.status_code == 5001097 assert rv.data == b"Hello Server Error"109810991100def test_enctype_debug_helper(app, client):1101 from flask.debughelpers import DebugFilesKeyError11021103 app.debug = True11041105 @app.route("/fail", methods=["POST"])1106 def index():1107 return flask.request.files["foo"].filename11081109 with pytest.raises(DebugFilesKeyError) as e:1110 client.post("/fail", data={"foo": "index.txt"})1111 assert "no file contents were transmitted" in str(e.value)1112 assert "This was submitted: 'index.txt'" in str(e.value)111311141115def test_response_types(app, client):1116 @app.route("/text")1117 def from_text():1118 return "Hällo Wörld"11191120 @app.route("/bytes")1121 def from_bytes():1122 return "Hällo Wörld".encode()11231124 @app.route("/full_tuple")1125 def from_full_tuple():1126 return (1127 "Meh",1128 400,1129 {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1130 )11311132 @app.route("/text_headers")1133 def from_text_headers():1134 return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}11351136 @app.route("/text_status")1137 def from_text_status():1138 return "Hi, status!", 40011391140 @app.route("/response_headers")1141 def from_response_headers():1142 return (1143 flask.Response(1144 "Hello world", 404, {"Content-Type": "text/html", "X-Foo": "Baz"}1145 ),1146 {"Content-Type": "text/plain", "X-Foo": "Bar", "X-Bar": "Foo"},1147 )11481149 @app.route("/response_status")1150 def from_response_status():1151 return app.response_class("Hello world", 400), 50011521153 @app.route("/wsgi")1154 def from_wsgi():1155 return NotFound()11561157 @app.route("/dict")1158 def from_dict():1159 return {"foo": "bar"}, 20111601161 @app.route("/list")1162 def from_list():1163 return ["foo", "bar"], 20111641165 assert client.get("/text").data == "Hällo Wörld".encode()1166 assert client.get("/bytes").data == "Hällo Wörld".encode()11671168 rv = client.get("/full_tuple")1169 assert rv.data == b"Meh"1170 assert rv.headers["X-Foo"] == "Testing"1171 assert rv.status_code == 4001172 assert rv.mimetype == "text/plain"11731174 rv = client.get("/text_headers")1175 assert rv.data == b"Hello"1176 assert rv.headers["X-Foo"] == "Test"1177 assert rv.status_code == 2001178 assert rv.mimetype == "text/plain"11791180 rv = client.get("/text_status")1181 assert rv.data == b"Hi, status!"1182 assert rv.status_code == 4001183 assert rv.mimetype == "text/html"11841185 rv = client.get("/response_headers")1186 assert rv.data == b"Hello world"1187 assert rv.content_type == "text/plain"1188 assert rv.headers.getlist("X-Foo") == ["Bar"]1189 assert rv.headers["X-Bar"] == "Foo"1190 assert rv.status_code == 40411911192 rv = client.get("/response_status")1193 assert rv.data == b"Hello world"1194 assert rv.status_code == 50011951196 rv = client.get("/wsgi")1197 assert b"Not Found" in rv.data1198 assert rv.status_code == 40411991200 rv = client.get("/dict")1201 assert rv.json == {"foo": "bar"}1202 assert rv.status_code == 20112031204 rv = client.get("/list")1205 assert rv.json == ["foo", "bar"]1206 assert rv.status_code == 201120712081209def test_response_type_errors():1210 app = flask.Flask(__name__)1211 app.testing = True12121213 @app.route("/none")1214 def from_none():1215 pass12161217 @app.route("/small_tuple")1218 def from_small_tuple():1219 return ("Hello",)12201221 @app.route("/large_tuple")1222 def from_large_tuple():1223 return "Hello", 234, {"X-Foo": "Bar"}, "???"12241225 @app.route("/bad_type")1226 def from_bad_type():1227 return True12281229 @app.route("/bad_wsgi")1230 def from_bad_wsgi():1231 return lambda: None12321233 c = app.test_client()12341235 with pytest.raises(TypeError) as e:1236 c.get("/none")12371238 assert "returned None" in str(e.value)1239 assert "from_none" in str(e.value)12401241 with pytest.raises(TypeError) as e:1242 c.get("/small_tuple")12431244 assert "tuple must have the form" in str(e.value)12451246 with pytest.raises(TypeError):1247 c.get("/large_tuple")12481249 with pytest.raises(TypeError) as e:1250 c.get("/bad_type")12511252 assert "it was a bool" in str(e.value)12531254 with pytest.raises(TypeError):1255 c.get("/bad_wsgi")125612571258def test_make_response(app, req_ctx):1259 rv = flask.make_response()1260 assert rv.status_code == 2001261 assert rv.data == b""1262 assert rv.mimetype == "text/html"12631264 rv = flask.make_response("Awesome")1265 assert rv.status_code == 2001266 assert rv.data == b"Awesome"1267 assert rv.mimetype == "text/html"12681269 rv = flask.make_response("W00t", 404)1270 assert rv.status_code == 4041271 assert rv.data == b"W00t"1272 assert rv.mimetype == "text/html"12731274 rv = flask.make_response(c for c in "Hello")1275 assert rv.status_code == 2001276 assert rv.data == b"Hello"1277 assert rv.mimetype == "text/html"127812791280def test_make_response_with_response_instance(app, req_ctx):1281 rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1282 assert rv.status_code == 4001283 assert rv.data == b'{"msg":"W00t"}\n'1284 assert rv.mimetype == "application/json"12851286 rv = flask.make_response(flask.Response(""), 400)1287 assert rv.status_code == 4001288 assert rv.data == b""1289 assert rv.mimetype == "text/html"12901291 rv = flask.make_response(1292 flask.Response("", headers={"Content-Type": "text/html"}),1293 400,1294 [("X-Foo", "bar")],1295 )1296 assert rv.status_code == 4001297 assert rv.headers["Content-Type"] == "text/html"1298 assert rv.headers["X-Foo"] == "bar"129913001301@pytest.mark.parametrize("compact", [True, False])1302def test_jsonify_no_prettyprint(app, compact):1303 app.json.compact = compact1304 rv = app.json.response({"msg": {"submsg": "W00t"}, "msg2": "foobar"})1305 data = rv.data.strip()1306 assert (b" " not in data) is compact1307 assert (b"\n" not in data) is compact130813091310def test_jsonify_mimetype(app, req_ctx):1311 app.json.mimetype = "application/vnd.api+json"1312 msg = {"msg": {"submsg": "W00t"}}1313 rv = flask.make_response(flask.jsonify(msg), 200)1314 assert rv.mimetype == "application/vnd.api+json"131513161317def test_json_dump_dataclass(app, req_ctx):1318 from dataclasses import make_dataclass13191320 Data = make_dataclass("Data", [("name", str)])1321 value = app.json.dumps(Data("Flask"))1322 value = app.json.loads(value)1323 assert value == {"name": "Flask"}132413251326def test_jsonify_args_and_kwargs_check(app, req_ctx):1327 with pytest.raises(TypeError) as e:1328 flask.jsonify("fake args", kwargs="fake")1329 assert "args or kwargs" in str(e.value)133013311332def test_url_generation(app, req_ctx):1333 @app.route("/hello/<name>", methods=["POST"])1334 def hello():1335 pass13361337 assert flask.url_for("hello", name="test x") == "/hello/test%20x"1338 assert (1339 flask.url_for("hello", name="test x", _external=True)1340 == "http://localhost/hello/test%20x"1341 )134213431344def test_build_error_handler(app):1345 # Test base case, a URL which results in a BuildError.1346 with app.test_request_context():1347 pytest.raises(BuildError, flask.url_for, "spam")13481349 # Verify the error is re-raised if not the current exception.1350 try:1351 with app.test_request_context():1352 flask.url_for("spam")1353 except BuildError as err:1354 error = err1355 try:1356 raise RuntimeError("Test case where BuildError is not current.")1357 except RuntimeError:1358 pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})13591360 # Test a custom handler.1361 def handler(error, endpoint, values):1362 # Just a test.1363 return "/test_handler/"13641365 app.url_build_error_handlers.append(handler)1366 with app.test_request_context():1367 assert flask.url_for("spam") == "/test_handler/"136813691370def test_build_error_handler_reraise(app):1371 # Test a custom handler which reraises the BuildError1372 def handler_raises_build_error(error, endpoint, values):1373 raise error13741375 app.url_build_error_handlers.append(handler_raises_build_error)13761377 with app.test_request_context():1378 pytest.raises(BuildError, flask.url_for, "not.existing")137913801381def test_url_for_passes_special_values_to_build_error_handler(app):1382 @app.url_build_error_handlers.append1383 def handler(error, endpoint, values):1384 assert values == {1385 "_external": False,1386 "_anchor": None,1387 "_method": None,1388 "_scheme": None,1389 }1390 return "handled"13911392 with app.test_request_context():1393 flask.url_for("/")139413951396def test_static_files(app, client):1397 rv = client.get("/static/index.html")1398 assert rv.status_code == 2001399 assert rv.data.strip() == b"<h1>Hello World!</h1>"1400 with app.test_request_context():1401 assert flask.url_for("static", filename="index.html") == "/static/index.html"1402 rv.close()140314041405def test_static_url_path():1406 app = flask.Flask(__name__, static_url_path="/foo")1407 app.testing = True1408 rv = app.test_client().get("/foo/index.html")1409 assert rv.status_code == 2001410 rv.close()14111412 with app.test_request_context():1413 assert flask.url_for("static", filename="index.html") == "/foo/index.html"141414151416def test_static_url_path_with_ending_slash():1417 app = flask.Flask(__name__, static_url_path="/foo/")1418 app.testing = True1419 rv = app.test_client().get("/foo/index.html")1420 assert rv.status_code == 2001421 rv.close()14221423 with app.test_request_context():1424 assert flask.url_for("static", filename="index.html") == "/foo/index.html"142514261427def test_static_url_empty_path(app):1428 app = flask.Flask(__name__, static_folder="", static_url_path="")1429 rv = app.test_client().open("/static/index.html", method="GET")1430 assert rv.status_code == 2001431 rv.close()143214331434def test_static_url_empty_path_default(app):1435 app = flask.Flask(__name__, static_folder="")1436 rv = app.test_client().open("/static/index.html", method="GET")1437 assert rv.status_code == 2001438 rv.close()143914401441def test_static_folder_with_pathlib_path(app):1442 from pathlib import Path14431444 app = flask.Flask(__name__, static_folder=Path("static"))1445 rv = app.test_client().open("/static/index.html", method="GET")1446 assert rv.status_code == 2001447 rv.close()144814491450def test_static_folder_with_ending_slash():1451 app = flask.Flask(__name__, static_folder="static/")14521453 @app.route("/<path:path>")1454 def catch_all(path):1455 return path14561457 rv = app.test_client().get("/catch/all")1458 assert rv.data == b"catch/all"145914601461def test_static_route_with_host_matching():1462 app = flask.Flask(__name__, host_matching=True, static_host="example.com")1463 c = app.test_client()1464 rv = c.get("http://example.com/static/index.html")1465 assert rv.status_code == 2001466 rv.close()1467 with app.test_request_context():1468 rv = flask.url_for("static", filename="index.html", _external=True)1469 assert rv == "http://example.com/static/index.html"1470 # Providing static_host without host_matching=True should error.

Merge pull request #4947 from pallets/pyprojectDavid Lordbefore adoption78b42b9

line 1471why, one step back
1471 with pytest.raises(AssertionError):

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 1472–1474why, one step back
1472 flask.Flask(__name__, static_host="example.com")
1473 # Providing host_matching=True with static_folder1474 # but without static_host should error.

Merge pull request #4947 from pallets/pyprojectDavid Lordbefore adoption78b42b9

line 1475why, one step back
1475 with pytest.raises(AssertionError):

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 1476–1484why, one step back
1476 flask.Flask(__name__, host_matching=True)
1477 # Providing host_matching=True without static_host1478 # but with static_folder=None should not error.1479 flask.Flask(__name__, host_matching=True, static_folder=None)148014811482def test_request_locals():1483 assert repr(flask.g) == "<LocalProxy unbound>"1484 assert not flask.g

setting `SERVER_NAME` does not restrict routing for both `subdomain_matching` and `host_matching` (#5634)David Lordbefore adoption10bdf61

lines 1485–1526why, one step back
1485
14861487@pytest.mark.parametrize(1488 ("subdomain_matching", "host_matching", "expect_base", "expect_abc", "expect_xyz"),1489 [1490 (False, False, "default", "default", "default"),1491 (True, False, "default", "abc", "<invalid>"),1492 (False, True, "default", "abc", "default"),1493 ],1494)1495def test_server_name_matching(1496 subdomain_matching: bool,1497 host_matching: bool,1498 expect_base: str,1499 expect_abc: str,1500 expect_xyz: str,1501) -> None:1502 app = flask.Flask(1503 __name__,1504 subdomain_matching=subdomain_matching,1505 host_matching=host_matching,1506 static_host="example.test" if host_matching else None,1507 )1508 app.config["SERVER_NAME"] = "example.test"15091510 @app.route("/", defaults={"name": "default"}, host="<name>")1511 @app.route("/", subdomain="<name>", host="<name>.example.test")1512 def index(name: str) -> str:1513 return name15141515 client = app.test_client()15161517 r = client.get(base_url="http://example.test")1518 assert r.text == expect_base15191520 r = client.get(base_url="http://abc.example.test")1521 assert r.text == expect_abc15221523 with pytest.warns() if subdomain_matching else nullcontext():1524 r = client.get(base_url="http://xyz.other.test")15251526 assert r.text == expect_xyz

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 1527–1579why, one step back
1527
15281529def test_server_name_subdomain():1530 app = flask.Flask(__name__, subdomain_matching=True)1531 client = app.test_client()15321533 @app.route("/")1534 def index():1535 return "default"15361537 @app.route("/", subdomain="foo")1538 def subdomain():1539 return "subdomain"15401541 app.config["SERVER_NAME"] = "dev.local:5000"1542 rv = client.get("/")1543 assert rv.data == b"default"15441545 rv = client.get("/", "http://dev.local:5000")1546 assert rv.data == b"default"15471548 rv = client.get("/", "https://dev.local:5000")1549 assert rv.data == b"default"15501551 app.config["SERVER_NAME"] = "dev.local:443"1552 rv = client.get("/", "https://dev.local")15531554 # Werkzeug 1.0 fixes matching https scheme with 443 port1555 if rv.status_code != 404:1556 assert rv.data == b"default"15571558 app.config["SERVER_NAME"] = "dev.local"1559 rv = client.get("/", "https://dev.local")1560 assert rv.data == b"default"15611562 # suppress Werkzeug 0.15 warning about name mismatch1563 with warnings.catch_warnings():1564 warnings.filterwarnings(1565 "ignore", "Current server name", UserWarning, "flask.app"1566 )1567 rv = client.get("/", "http://foo.localhost")1568 assert rv.status_code == 40415691570 rv = client.get("/", "http://foo.dev.local")1571 assert rv.data == b"subdomain"157215731574@pytest.mark.parametrize("key", ["TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None])1575def test_exception_propagation(app, client, key):1576 app.testing = False15771578 @app.route("/")1579 def index():

use ruff linter and formatter (#5331)David Lordbefore adoption9a12f34

line 1580why, one step back
1580 raise ZeroDivisionError

Merge branch '2.2.x'David Lordbefore adoptionc34c84b

lines 1581–1937why, one step back
1581
1582 if key is not None:1583 app.config[key] = True15841585 with pytest.raises(ZeroDivisionError):1586 client.get("/")1587 else:1588 assert client.get("/").status_code == 500158915901591@pytest.mark.parametrize("debug", [True, False])1592@pytest.mark.parametrize("use_debugger", [True, False])1593@pytest.mark.parametrize("use_reloader", [True, False])1594@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1595def test_werkzeug_passthrough_errors(1596 monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1597):1598 rv = {}15991600 # Mocks werkzeug.serving.run_simple method1601 def run_simple_mock(*args, **kwargs):1602 rv["passthrough_errors"] = kwargs.get("passthrough_errors")16031604 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1605 app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1606 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)160716081609def test_url_processors(app, client):1610 @app.url_defaults1611 def add_language_code(endpoint, values):1612 if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1613 endpoint, "lang_code"1614 ):1615 values.setdefault("lang_code", flask.g.lang_code)16161617 @app.url_value_preprocessor1618 def pull_lang_code(endpoint, values):1619 flask.g.lang_code = values.pop("lang_code", None)16201621 @app.route("/<lang_code>/")1622 def index():1623 return flask.url_for("about")16241625 @app.route("/<lang_code>/about")1626 def about():1627 return flask.url_for("something_else")16281629 @app.route("/foo")1630 def something_else():1631 return flask.url_for("about", lang_code="en")16321633 assert client.get("/de/").data == b"/de/about"1634 assert client.get("/de/about").data == b"/foo"1635 assert client.get("/foo").data == b"/en/about"163616371638def test_inject_blueprint_url_defaults(app):1639 bp = flask.Blueprint("foo", __name__, template_folder="template")16401641 @bp.url_defaults1642 def bp_defaults(endpoint, values):1643 values["page"] = "login"16441645 @bp.route("/<page>")1646 def view(page):1647 pass16481649 app.register_blueprint(bp)16501651 values = dict()1652 app.inject_url_defaults("foo.view", values)1653 expected = dict(page="login")1654 assert values == expected16551656 with app.test_request_context("/somepage"):1657 url = flask.url_for("foo.view")1658 expected = "/login"1659 assert url == expected166016611662def test_nonascii_pathinfo(app, client):1663 @app.route("/киртест")1664 def index():1665 return "Hello World!"16661667 rv = client.get("/киртест")1668 assert rv.data == b"Hello World!"166916701671def test_no_setup_after_first_request(app, client):1672 app.debug = True16731674 @app.route("/")1675 def index():1676 return "Awesome"16771678 assert client.get("/").data == b"Awesome"16791680 with pytest.raises(AssertionError) as exc_info:1681 app.add_url_rule("/foo", endpoint="late")16821683 assert "setup method 'add_url_rule'" in str(exc_info.value)168416851686def test_routing_redirect_debugging(monkeypatch, app, client):1687 app.config["DEBUG"] = True16881689 @app.route("/user/", methods=["GET", "POST"])1690 def user():1691 return flask.request.form["status"]16921693 # default redirect code preserves form data1694 rv = client.post("/user", data={"status": "success"}, follow_redirects=True)1695 assert rv.data == b"success"16961697 # 301 and 302 raise error1698 monkeypatch.setattr(RequestRedirect, "code", 301)16991700 with client, pytest.raises(AssertionError) as exc_info:1701 client.post("/user", data={"status": "error"}, follow_redirects=True)17021703 assert "canonical URL 'http://localhost/user/'" in str(exc_info.value)170417051706def test_route_decorator_custom_endpoint(app, client):1707 app.debug = True17081709 @app.route("/foo/")1710 def foo():1711 return flask.request.endpoint17121713 @app.route("/bar/", endpoint="bar")1714 def for_bar():1715 return flask.request.endpoint17161717 @app.route("/bar/123", endpoint="123")1718 def for_bar_foo():1719 return flask.request.endpoint17201721 with app.test_request_context():1722 assert flask.url_for("foo") == "/foo/"1723 assert flask.url_for("bar") == "/bar/"1724 assert flask.url_for("123") == "/bar/123"17251726 assert client.get("/foo/").data == b"foo"1727 assert client.get("/bar/").data == b"bar"1728 assert client.get("/bar/123").data == b"123"172917301731def test_get_method_on_g(app_ctx):1732 assert flask.g.get("x") is None1733 assert flask.g.get("x", 11) == 111734 flask.g.x = 421735 assert flask.g.get("x") == 421736 assert flask.g.x == 42173717381739def test_g_iteration_protocol(app_ctx):1740 flask.g.foo = 231741 flask.g.bar = 421742 assert "foo" in flask.g1743 assert "foos" not in flask.g1744 assert sorted(flask.g) == ["bar", "foo"]174517461747def test_subdomain_basic_support():1748 app = flask.Flask(__name__, subdomain_matching=True)1749 app.config["SERVER_NAME"] = "localhost.localdomain"1750 client = app.test_client()17511752 @app.route("/")1753 def normal_index():1754 return "normal index"17551756 @app.route("/", subdomain="test")1757 def test_index():1758 return "test index"17591760 rv = client.get("/", "http://localhost.localdomain/")1761 assert rv.data == b"normal index"17621763 rv = client.get("/", "http://test.localhost.localdomain/")1764 assert rv.data == b"test index"176517661767def test_subdomain_matching():1768 app = flask.Flask(__name__, subdomain_matching=True)1769 client = app.test_client()1770 app.config["SERVER_NAME"] = "localhost.localdomain"17711772 @app.route("/", subdomain="<user>")1773 def index(user):1774 return f"index for {user}"17751776 rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1777 assert rv.data == b"index for mitsuhiko"177817791780def test_subdomain_matching_with_ports():1781 app = flask.Flask(__name__, subdomain_matching=True)1782 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1783 client = app.test_client()17841785 @app.route("/", subdomain="<user>")1786 def index(user):1787 return f"index for {user}"17881789 rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1790 assert rv.data == b"index for mitsuhiko"179117921793@pytest.mark.parametrize("matching", (False, True))1794def test_subdomain_matching_other_name(matching):1795 app = flask.Flask(__name__, subdomain_matching=matching)1796 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1797 client = app.test_client()17981799 @app.route("/")1800 def index():1801 return "", 20418021803 # suppress Werkzeug 0.15 warning about name mismatch1804 with warnings.catch_warnings():1805 warnings.filterwarnings(1806 "ignore", "Current server name", UserWarning, "flask.app"1807 )1808 # ip address can't match name1809 rv = client.get("/", "http://127.0.0.1:3000/")1810 assert rv.status_code == 404 if matching else 20418111812 # allow all subdomains if matching is disabled1813 rv = client.get("/", "http://www.localhost.localdomain:3000/")1814 assert rv.status_code == 404 if matching else 204181518161817def test_multi_route_rules(app, client):1818 @app.route("/")1819 @app.route("/<test>/")1820 def index(test="a"):1821 return test18221823 rv = client.open("/")1824 assert rv.data == b"a"1825 rv = client.open("/b/")1826 assert rv.data == b"b"182718281829def test_multi_route_class_views(app, client):1830 class View:1831 def __init__(self, app):1832 app.add_url_rule("/", "index", self.index)1833 app.add_url_rule("/<test>/", "index", self.index)18341835 def index(self, test="a"):1836 return test18371838 _ = View(app)1839 rv = client.open("/")1840 assert rv.data == b"a"1841 rv = client.open("/b/")1842 assert rv.data == b"b"184318441845def test_run_defaults(monkeypatch, app):1846 rv = {}18471848 # Mocks werkzeug.serving.run_simple method1849 def run_simple_mock(*args, **kwargs):1850 rv["result"] = "running..."18511852 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1853 app.run()1854 assert rv["result"] == "running..."185518561857def test_run_server_port(monkeypatch, app):1858 rv = {}18591860 # Mocks werkzeug.serving.run_simple method1861 def run_simple_mock(hostname, port, application, *args, **kwargs):1862 rv["result"] = f"running on {hostname}:{port} ..."18631864 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1865 hostname, port = "localhost", 80001866 app.run(hostname, port, debug=True)1867 assert rv["result"] == f"running on {hostname}:{port} ..."186818691870@pytest.mark.parametrize(1871 "host,port,server_name,expect_host,expect_port",1872 (1873 (None, None, "pocoo.org:8080", "pocoo.org", 8080),1874 ("localhost", None, "pocoo.org:8080", "localhost", 8080),1875 (None, 80, "pocoo.org:8080", "pocoo.org", 80),1876 ("localhost", 80, "pocoo.org:8080", "localhost", 80),1877 ("localhost", 0, "localhost:8080", "localhost", 0),1878 (None, None, "localhost:8080", "localhost", 8080),1879 (None, None, "localhost:0", "localhost", 0),1880 ),1881)1882def test_run_from_config(1883 monkeypatch, host, port, server_name, expect_host, expect_port, app1884):1885 def run_simple_mock(hostname, port, *args, **kwargs):1886 assert hostname == expect_host1887 assert port == expect_port18881889 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1890 app.config["SERVER_NAME"] = server_name1891 app.run(host, port)189218931894def test_max_cookie_size(app, client, recwarn):1895 app.config["MAX_COOKIE_SIZE"] = 10018961897 # outside app context, default to Werkzeug static value,1898 # which is also the default config1899 response = flask.Response()1900 default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1901 assert response.max_cookie_size == default19021903 # inside app context, use app config1904 with app.app_context():1905 assert flask.Response().max_cookie_size == 10019061907 @app.route("/")1908 def index():1909 r = flask.Response("", status=204)1910 r.set_cookie("foo", "bar" * 100)1911 return r19121913 client.get("/")1914 assert len(recwarn) == 11915 w = recwarn.pop()1916 assert "cookie is too large" in str(w.message)19171918 app.config["MAX_COOKIE_SIZE"] = 019191920 client.get("/")1921 assert len(recwarn) == 0192219231924@require_cpython_gc1925def test_app_freed_on_zero_refcount():1926 # A Flask instance should not create a reference cycle that prevents CPython1927 # from freeing it when all external references to it are released (see #3761).1928 gc.disable()1929 try:1930 app = flask.Flask(__name__)1931 assert app.view_functions["static"]1932 weak = weakref.ref(app)1933 assert weak() is not None1934 del app1935 assert weak() is None1936 finally:1937 gc.enable()