Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

1,974 lines · 53.0 KiB · Python

Last changed by

drop support for Python 3.10 (#6168)David Lordbefore adoption728c5e4

History of this file

Take it

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

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 1why, one step back
1import gc

update domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2

line 2why, one step back
2import importlib.metadata

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 3why, one step back
3import re

enable secret key rotation (#5632)David Lordbefore adoptiona20bcff

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

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 5–6why, one step back
5import uuid
6import 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 adoption73739a2

line 8why, one step back
8from datetime import datetime

drop support for Python 3.10 (#6168)David Lordbefore adoption728c5e4

line 9why, one step back
9from datetime import UTC

add `app.query` route decorator (#6133)David Lordbefore adoptiond8eaaba

line 10why, one step back
10from functools import partial

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 11–23why, one step back
11from platform import python_implementation
1213import pytest14import werkzeug.serving15from markupsafe import Markup16from werkzeug.exceptions import BadRequest17from werkzeug.exceptions import Forbidden18from werkzeug.exceptions import NotFound19from werkzeug.http import parse_date20from werkzeug.routing import BuildError21from werkzeug.routing import RequestRedirect2223import flask

Merge branch 'stable'David Lordbefore adoptiondaca74d

line 24why, one step back
24from flask.globals import app_ctx

fix provide_automatic_options override (#5917)David Lordbefore adoption12e95c9

line 25why, one step back
25from flask.testing import FlaskClient

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 26–55why, one step back
26
27require_cpython_gc = pytest.mark.skipif(28 python_implementation() != "CPython",29 reason="Requires CPython GC behavior",30)313233def test_options_work(app, client):34 @app.route("/", methods=["GET", "POST"])35 def index():36 return "Hello World"3738 rv = client.open("/", method="OPTIONS")39 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]40 assert rv.data == b""414243def test_options_on_multiple_rules(app, client):44 @app.route("/", methods=["GET", "POST"])45 def index():46 return "Hello World"4748 @app.route("/", methods=["PUT"])49 def index_put():50 return "Aha!"5152 rv = client.open("/", method="OPTIONS")53 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST", "PUT"]5455

add `app.query` route decorator (#6133)David Lordbefore adoptiond8eaaba

line 56why, one step back
56@pytest.mark.parametrize("method", ["get", "query", "post", "put", "delete", "patch"])

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 57–58why, one step back
57def test_method_route(app, client, method):
58 method_route = getattr(app, method)

add `app.query` route decorator (#6133)David Lordbefore adoptiond8eaaba

lines 59–61why, one step back
59 client_method = getattr(
60 client, method, partial(client.open, method=method.capitalize())61 )

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 62–74why, one step back
62
63 @method_route("/")64 def hello():65 return "Hello"6667 assert client_method("/").data == b"Hello"686970def test_method_route_no_methods(app):71 with pytest.raises(TypeError):72 app.get("/", methods=["GET", "POST"])7374

fix provide_automatic_options override (#5917)David Lordbefore adoption12e95c9

lines 75–78why, one step back
75def test_provide_automatic_options_attr_disable(
76 app: flask.Flask, client: FlaskClient77) -> None:78 """Automatic options can be disabled by the view func attribute."""

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 79–83why, one step back
79
80 def index():81 return "Hello World!"8283 index.provide_automatic_options = False

fix provide_automatic_options override (#5917)David Lordbefore adoption12e95c9

lines 84–85why, one step back
84 app.add_url_rule("/", view_func=index)
85 rv = client.options()

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 86–88why, one step back
86 assert rv.status_code == 405
8788

fix provide_automatic_options override (#5917)David Lordbefore adoption12e95c9

lines 89–97why, one step back
89def test_provide_automatic_options_attr_enable(
90 app: flask.Flask, client: FlaskClient91) -> None:92 """When default automatic options is disabled in config, it can still be93 enabled by the view function attribute.94 """95 app.config["PROVIDE_AUTOMATIC_OPTIONS"] = False9697 def index():

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 98–99why, one step back
98 return "Hello World!"
99

fix provide_automatic_options override (#5917)David Lordbefore adoption12e95c9

lines 100–103why, one step back
100 index.provide_automatic_options = True
101 app.add_url_rule("/", view_func=index)102 rv = client.options()103 assert rv.allow == {"GET", "HEAD", "OPTIONS"}

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 104–105why, one step back
104
105

fix provide_automatic_options override (#5917)David Lordbefore adoption12e95c9

lines 106–111why, one step back
106def test_provide_automatic_options_arg_disable(
107 app: flask.Flask, client: FlaskClient108) -> None:109 """Automatic options can be disabled by the route argument."""110111 @app.get("/", provide_automatic_options=False)

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 112why, one step back
112 def index():

fix provide_automatic_options override (#5917)David Lordbefore adoption12e95c9

line 113why, one step back
113 return "Hello World!"

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 114why, one step back
114

fix provide_automatic_options override (#5917)David Lordbefore adoption12e95c9

line 115why, one step back
115 rv = client.options()

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 116–118why, one step back
116 assert rv.status_code == 405
117118

fix provide_automatic_options override (#5917)David Lordbefore adoption12e95c9

lines 119–122why, one step back
119def test_provide_automatic_options_method_disable(
120 app: flask.Flask, client: FlaskClient121) -> None:122 """Automatic options is ignored if the route handles options."""

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 123why, one step back
123

fix provide_automatic_options override (#5917)David Lordbefore adoption12e95c9

lines 124–126why, one step back
124 @app.route("/", methods=["OPTIONS"])
125 def index():126 return "", {"X-Test": "test"}

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 127why, one step back
127

fix provide_automatic_options override (#5917)David Lordbefore adoption12e95c9

lines 128–129why, one step back
128 rv = client.options()
129 assert rv.headers["X-Test"] == "test"

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 130–196why, one step back
130
131132def test_request_dispatching(app, client):133 @app.route("/")134 def index():135 return flask.request.method136137 @app.route("/more", methods=["GET", "POST"])138 def more():139 return flask.request.method140141 assert client.get("/").data == b"GET"142 rv = client.post("/")143 assert rv.status_code == 405144 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]145 rv = client.head("/")146 assert rv.status_code == 200147 assert not rv.data # head truncates148 assert client.post("/more").data == b"POST"149 assert client.get("/more").data == b"GET"150 rv = client.delete("/more")151 assert rv.status_code == 405152 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]153154155def test_disallow_string_for_allowed_methods(app):156 with pytest.raises(TypeError):157 app.add_url_rule("/", methods="GET POST", endpoint="test")158159160def test_url_mapping(app, client):161 random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"162163 def index():164 return flask.request.method165166 def more():167 return flask.request.method168169 def options():170 return random_uuid4171172 app.add_url_rule("/", "index", index)173 app.add_url_rule("/more", "more", more, methods=["GET", "POST"])174175 # Issue 1288: Test that automatic options are not added176 # when non-uppercase 'options' in methods177 app.add_url_rule("/options", "options", options, methods=["options"])178179 assert client.get("/").data == b"GET"180 rv = client.post("/")181 assert rv.status_code == 405182 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]183 rv = client.head("/")184 assert rv.status_code == 200185 assert not rv.data # head truncates186 assert client.post("/more").data == b"POST"187 assert client.get("/more").data == b"GET"188 rv = client.delete("/more")189 assert rv.status_code == 405190 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]191 rv = client.open("/options", method="OPTIONS")192 assert rv.status_code == 200193 assert random_uuid4 in rv.data.decode("utf-8")194195196def test_werkzeug_routing(app, client):

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

lines 197–198why, one step back
197 from werkzeug.routing import Rule
198 from werkzeug.routing import Submount

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 199–217why, one step back
199
200 app.url_map.add(201 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])202 )203204 def bar():205 return "bar"206207 def index():208 return "index"209210 app.view_functions["bar"] = bar211 app.view_functions["index"] = index212213 assert client.get("/foo/").data == b"index"214 assert client.get("/foo/bar").data == b"bar"215216217def test_endpoint_decorator(app, client):

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

lines 218–219why, one step back
218 from werkzeug.routing import Rule
219 from werkzeug.routing import Submount

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 220–236why, one step back
220
221 app.url_map.add(222 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])223 )224225 @app.endpoint("bar")226 def bar():227 return "bar"228229 @app.endpoint("index")230 def index():231 return "index"232233 assert client.get("/foo/").data == b"index"234 assert client.get("/foo/bar").data == b"bar"235236

Merge branch 'stable'David Lordbefore adoptiondaca74d

lines 237–239why, one step back
237def test_session_accessed(app: flask.Flask, client: FlaskClient) -> None:
238 @app.post("/")239 def do_set():

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 240–242why, one step back
240 flask.session["value"] = flask.request.form["value"]
241 return "value set"242

Merge branch 'stable'David Lordbefore adoptiondaca74d

lines 243–245why, one step back
243 @app.get("/")
244 def do_get():245 return flask.session.get("value", "None")

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 246why, one step back
246

Merge branch 'stable'David Lordbefore adoptiondaca74d

lines 247–276why, one step back
247 @app.get("/nothing")
248 def do_nothing() -> str:249 return ""250251 with client:252 rv = client.get("/nothing")253 assert "cookie" not in rv.vary254 assert not app_ctx._session.accessed255 assert not app_ctx._session.modified256257 with client:258 rv = client.post(data={"value": "42"})259 assert rv.text == "value set"260 assert "cookie" in rv.vary261 assert app_ctx._session.accessed262 assert app_ctx._session.modified263264 with client:265 rv = client.get()266 assert rv.text == "42"267 assert "cookie" in rv.vary268 assert app_ctx._session.accessed269 assert not app_ctx._session.modified270271 with client:272 rv = client.get("/nothing")273 assert rv.text == ""274 assert "cookie" not in rv.vary275 assert not app_ctx._session.accessed276 assert not app_ctx._session.modified

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 277–319why, one step back
277
278279def test_session_path(app, client):280 app.config.update(APPLICATION_ROOT="/foo")281282 @app.route("/")283 def index():284 flask.session["testing"] = 42285 return "Hello World"286287 rv = client.get("/", "http://example.com:8080/foo")288 assert "path=/foo" in rv.headers["set-cookie"].lower()289290291def test_session_using_application_root(app, client):292 class PrefixPathMiddleware:293 def __init__(self, app, prefix):294 self.app = app295 self.prefix = prefix296297 def __call__(self, environ, start_response):298 environ["SCRIPT_NAME"] = self.prefix299 return self.app(environ, start_response)300301 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, "/bar")302 app.config.update(APPLICATION_ROOT="/bar")303304 @app.route("/")305 def index():306 flask.session["testing"] = 42307 return "Hello World"308309 rv = client.get("/", "http://example.com:8080/")310 assert "path=/bar" in rv.headers["set-cookie"].lower()311312313def test_session_using_session_settings(app, client):314 app.config.update(315 SERVER_NAME="www.example.com:8080",316 APPLICATION_ROOT="/test",317 SESSION_COOKIE_DOMAIN=".example.com",318 SESSION_COOKIE_HTTPONLY=False,319 SESSION_COOKIE_SECURE=True,

add SESSION_COOKIE_PARTITIONED config (#5499)David Lordbefore adoptionce08bc7

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

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 321–342why, one step back
321 SESSION_COOKIE_SAMESITE="Lax",
322 SESSION_COOKIE_PATH="/",323 )324325 @app.route("/")326 def index():327 flask.session["testing"] = 42328 return "Hello World"329330 @app.route("/clear")331 def clear():332 flask.session.pop("testing", None)333 return "Goodbye World"334335 rv = client.get("/", "http://www.example.com:8080/test/")336 cookie = rv.headers["set-cookie"].lower()337 # or condition for Werkzeug < 2.3338 assert "domain=example.com" in cookie or "domain=.example.com" in cookie339 assert "path=/" in cookie340 assert "secure" in cookie341 assert "httponly" not in cookie342 assert "samesite" in cookie

add SESSION_COOKIE_PARTITIONED config (#5499)David Lordbefore adoptionce08bc7

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

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 344–352why, one step back
344
345 rv = client.get("/clear", "http://www.example.com:8080/test/")346 cookie = rv.headers["set-cookie"].lower()347 assert "session=;" in cookie348 # or condition for Werkzeug < 2.3349 assert "domain=example.com" in cookie or "domain=.example.com" in cookie350 assert "path=/" in cookie351 assert "secure" in cookie352 assert "samesite" in cookie

add SESSION_COOKIE_PARTITIONED config (#5499)David Lordbefore adoptionce08bc7

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

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 354–393why, one step back
354
355356def test_session_using_samesite_attribute(app, client):357 @app.route("/")358 def index():359 flask.session["testing"] = 42360 return "Hello World"361362 app.config.update(SESSION_COOKIE_SAMESITE="invalid")363364 with pytest.raises(ValueError):365 client.get("/")366367 app.config.update(SESSION_COOKIE_SAMESITE=None)368 rv = client.get("/")369 cookie = rv.headers["set-cookie"].lower()370 assert "samesite" not in cookie371372 app.config.update(SESSION_COOKIE_SAMESITE="Strict")373 rv = client.get("/")374 cookie = rv.headers["set-cookie"].lower()375 assert "samesite=strict" in cookie376377 app.config.update(SESSION_COOKIE_SAMESITE="Lax")378 rv = client.get("/")379 cookie = rv.headers["set-cookie"].lower()380 assert "samesite=lax" in cookie381382383def test_missing_session(app):384 app.secret_key = None385386 def expect_exception(f, *args, **kwargs):387 e = pytest.raises(RuntimeError, f, *args, **kwargs)388 assert e.value.args and "session is unavailable" in e.value.args[0]389390 with app.test_request_context():391 assert flask.session.get("missing_key") is None392 expect_exception(flask.session.__setitem__, "foo", 42)393 expect_exception(flask.session.pop, "foo")

enable secret key rotation (#5632)David Lordbefore adoptiona20bcff

lines 394–405why, one step back
394
395396def test_session_secret_key_fallbacks(app, client) -> None:397 @app.post("/")398 def set_session() -> str:399 flask.session["a"] = 1400 return ""401402 @app.get("/")403 def get_session() -> dict[str, t.Any]:404 return dict(flask.session)405

Merge branch 'stable'David Lordbefore adoptione7e5380

lines 406–410why, one step back
406 # Set session with initial secret key, and two valid expiring keys
407 app.secret_key, app.config["SECRET_KEY_FALLBACKS"] = (408 "0 key",409 ["-1 key", "-2 key"],410 )

enable secret key rotation (#5632)David Lordbefore adoptiona20bcff

lines 411–413why, one step back
411 client.post()
412 assert client.get().json == {"a": 1}413 # Change secret key, session can't be loaded and appears empty

Merge branch 'stable'David Lordbefore adoptione7e5380

line 414why, one step back
414 app.secret_key = "? key"

enable secret key rotation (#5632)David Lordbefore adoptiona20bcff

line 415why, one step back
415 assert client.get().json == {}

Merge branch 'stable'David Lordbefore adoptione7e5380

lines 416–420why, one step back
416 # Rotate the valid keys, session can be loaded
417 app.secret_key, app.config["SECRET_KEY_FALLBACKS"] = (418 "+1 key",419 ["0 key", "-1 key"],420 )

enable secret key rotation (#5632)David Lordbefore adoptiona20bcff

line 421why, one step back
421 assert client.get().json == {"a": 1}

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 422–440why, one step back
422
423424def test_session_expiration(app, client):425 permanent = True426427 @app.route("/")428 def index():429 flask.session["test"] = 42430 flask.session.permanent = permanent431 return ""432433 @app.route("/test")434 def test():435 return str(flask.session.permanent)436437 rv = client.get("/")438 assert "set-cookie" in rv.headers439 match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])440 expires = parse_date(match.group())

drop support for Python 3.10 (#6168)David Lordbefore adoption728c5e4

line 441why, one step back
441 expected = datetime.now(UTC) + app.permanent_session_lifetime

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 442–470why, one step back
442 assert expires.year == expected.year
443 assert expires.month == expected.month444 assert expires.day == expected.day445446 rv = client.get("/test")447 assert rv.data == b"True"448449 permanent = False450 rv = client.get("/")451 assert "set-cookie" in rv.headers452 match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])453 assert match is None454455456def test_session_stored_last(app, client):457 @app.after_request458 def modify_session(response):459 flask.session["foo"] = 42460 return response461462 @app.route("/")463 def dump_session_contents():464 return repr(flask.session.get("foo"))465466 assert client.get("/").data == b"None"467 assert client.get("/").data == b"42"468469470def test_session_special_types(app, client):

drop support for Python 3.10 (#6168)David Lordbefore adoption728c5e4

line 471why, one step back
471 now = datetime.now(UTC).replace(microsecond=0)

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 472–489why, one step back
472 the_uuid = uuid.uuid4()
473474 @app.route("/")475 def dump_session_contents():476 flask.session["t"] = (1, 2, 3)477 flask.session["b"] = b"\xff"478 flask.session["m"] = Markup("<html>")479 flask.session["u"] = the_uuid480 flask.session["d"] = now481 flask.session["t_tag"] = {" t": "not-a-tuple"}482 flask.session["di_t_tag"] = {" t__": "not-a-tuple"}483 flask.session["di_tag"] = {" di": "not-a-dict"}484 return "", 204485486 with client:487 client.get("/")488 s = flask.session489 assert s["t"] == (1, 2, 3)

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

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

Merge branch '2.2.x'David Lordbefore adoption73739a2

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

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

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

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 493–559why, one step back
493 assert s["m"] == Markup("<html>")
494 assert s["u"] == the_uuid495 assert s["d"] == now496 assert s["t_tag"] == {" t": "not-a-tuple"}497 assert s["di_t_tag"] == {" t__": "not-a-tuple"}498 assert s["di_tag"] == {" di": "not-a-dict"}499500501def test_session_cookie_setting(app):502 is_permanent = True503504 @app.route("/bump")505 def bump():506 rv = flask.session["foo"] = flask.session.get("foo", 0) + 1507 flask.session.permanent = is_permanent508 return str(rv)509510 @app.route("/read")511 def read():512 return str(flask.session.get("foo", 0))513514 def run_test(expect_header):515 with app.test_client() as c:516 assert c.get("/bump").data == b"1"517 assert c.get("/bump").data == b"2"518 assert c.get("/bump").data == b"3"519520 rv = c.get("/read")521 set_cookie = rv.headers.get("set-cookie")522 assert (set_cookie is not None) == expect_header523 assert rv.data == b"3"524525 is_permanent = True526 app.config["SESSION_REFRESH_EACH_REQUEST"] = True527 run_test(expect_header=True)528529 is_permanent = True530 app.config["SESSION_REFRESH_EACH_REQUEST"] = False531 run_test(expect_header=False)532533 is_permanent = False534 app.config["SESSION_REFRESH_EACH_REQUEST"] = True535 run_test(expect_header=False)536537 is_permanent = False538 app.config["SESSION_REFRESH_EACH_REQUEST"] = False539 run_test(expect_header=False)540541542def test_session_vary_cookie(app, client):543 @app.route("/set")544 def set_session():545 flask.session["test"] = "test"546 return ""547548 @app.route("/get")549 def get():550 return flask.session.get("test")551552 @app.route("/getitem")553 def getitem():554 return flask.session["test"]555556 @app.route("/setdefault")557 def setdefault():558 return flask.session.setdefault("test", "default")559

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

lines 560–564why, one step back
560 @app.route("/clear")
561 def clear():562 flask.session.clear()563 return ""564

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 565–596why, one step back
565 @app.route("/vary-cookie-header-set")
566 def vary_cookie_header_set():567 response = flask.Response()568 response.vary.add("Cookie")569 flask.session["test"] = "test"570 return response571572 @app.route("/vary-header-set")573 def vary_header_set():574 response = flask.Response()575 response.vary.update(("Accept-Encoding", "Accept-Language"))576 flask.session["test"] = "test"577 return response578579 @app.route("/no-vary-header")580 def no_vary_header():581 return ""582583 def expect(path, header_value="Cookie"):584 rv = client.get(path)585586 if header_value:587 # The 'Vary' key should exist in the headers only once.588 assert len(rv.headers.get_all("Vary")) == 1589 assert rv.headers["Vary"] == header_value590 else:591 assert "Vary" not in rv.headers592593 expect("/set")594 expect("/get")595 expect("/getitem")596 expect("/setdefault")

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

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

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 598–600why, one step back
598 expect("/vary-cookie-header-set")
599 expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")600 expect("/no-vary-header", None)

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

lines 601–617why, one step back
601
602603def test_session_refresh_vary(app, client):604 @app.get("/login")605 def login():606 flask.session["user_id"] = 1607 flask.session.permanent = True608 return ""609610 @app.get("/ignored")611 def ignored():612 return ""613614 rv = client.get("/login")615 assert rv.headers["Vary"] == "Cookie"616 rv = client.get("/ignored")617 assert rv.headers["Vary"] == "Cookie"

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 618–818why, one step back
618
619620def test_flashes(app, req_ctx):621 assert not flask.session.modified622 flask.flash("Zap")623 flask.session.modified = False624 flask.flash("Zip")625 assert flask.session.modified626 assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]627628629def test_extended_flashing(app):630 # Be sure app.testing=True below, else tests can fail silently.631 #632 # Specifically, if app.testing is not set to True, the AssertionErrors633 # in the view functions will cause a 500 response to the test client634 # instead of propagating exceptions.635636 @app.route("/")637 def index():638 flask.flash("Hello World")639 flask.flash("Hello World", "error")640 flask.flash(Markup("<em>Testing</em>"), "warning")641 return ""642643 @app.route("/test/")644 def test():645 messages = flask.get_flashed_messages()646 assert list(messages) == [647 "Hello World",648 "Hello World",649 Markup("<em>Testing</em>"),650 ]651 return ""652653 @app.route("/test_with_categories/")654 def test_with_categories():655 messages = flask.get_flashed_messages(with_categories=True)656 assert len(messages) == 3657 assert list(messages) == [658 ("message", "Hello World"),659 ("error", "Hello World"),660 ("warning", Markup("<em>Testing</em>")),661 ]662 return ""663664 @app.route("/test_filter/")665 def test_filter():666 messages = flask.get_flashed_messages(667 category_filter=["message"], with_categories=True668 )669 assert list(messages) == [("message", "Hello World")]670 return ""671672 @app.route("/test_filters/")673 def test_filters():674 messages = flask.get_flashed_messages(675 category_filter=["message", "warning"], with_categories=True676 )677 assert list(messages) == [678 ("message", "Hello World"),679 ("warning", Markup("<em>Testing</em>")),680 ]681 return ""682683 @app.route("/test_filters_without_returning_categories/")684 def test_filters2():685 messages = flask.get_flashed_messages(category_filter=["message", "warning"])686 assert len(messages) == 2687 assert messages[0] == "Hello World"688 assert messages[1] == Markup("<em>Testing</em>")689 return ""690691 # Create new test client on each test to clean flashed messages.692693 client = app.test_client()694 client.get("/")695 client.get("/test_with_categories/")696697 client = app.test_client()698 client.get("/")699 client.get("/test_filter/")700701 client = app.test_client()702 client.get("/")703 client.get("/test_filters/")704705 client = app.test_client()706 client.get("/")707 client.get("/test_filters_without_returning_categories/")708709710def test_request_processing(app, client):711 evts = []712713 @app.before_request714 def before_request():715 evts.append("before")716717 @app.after_request718 def after_request(response):719 response.data += b"|after"720 evts.append("after")721 return response722723 @app.route("/")724 def index():725 assert "before" in evts726 assert "after" not in evts727 return "request"728729 assert "after" not in evts730 rv = client.get("/").data731 assert "after" in evts732 assert rv == b"request|after"733734735def test_request_preprocessing_early_return(app, client):736 evts = []737738 @app.before_request739 def before_request1():740 evts.append(1)741742 @app.before_request743 def before_request2():744 evts.append(2)745 return "hello"746747 @app.before_request748 def before_request3():749 evts.append(3)750 return "bye"751752 @app.route("/")753 def index():754 evts.append("index")755 return "damnit"756757 rv = client.get("/").data.strip()758 assert rv == b"hello"759 assert evts == [1, 2]760761762def test_after_request_processing(app, client):763 @app.route("/")764 def index():765 @flask.after_this_request766 def foo(response):767 response.headers["X-Foo"] = "a header"768 return response769770 return "Test"771772 resp = client.get("/")773 assert resp.status_code == 200774 assert resp.headers["X-Foo"] == "a header"775776777def test_teardown_request_handler(app, client):778 called = []779780 @app.teardown_request781 def teardown_request(exc):782 called.append(True)783 return "Ignored"784785 @app.route("/")786 def root():787 return "Response"788789 rv = client.get("/")790 assert rv.status_code == 200791 assert b"Response" in rv.data792 assert len(called) == 1793794795def test_teardown_request_handler_debug_mode(app, client):796 called = []797798 @app.teardown_request799 def teardown_request(exc):800 called.append(True)801 return "Ignored"802803 @app.route("/")804 def root():805 return "Response"806807 rv = client.get("/")808 assert rv.status_code == 200809 assert b"Response" in rv.data810 assert len(called) == 1811812813def test_teardown_request_handler_error(app, client):814 called = []815 app.testing = False816817 @app.teardown_request818 def teardown_request1(exc):

fix flake8 bugbear findingsDavid Lordbefore adoptionc49ce2e

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

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 820–830why, one step back
820 called.append(True)
821 # This raises a new error and blows away sys.exc_info(), so we can822 # test that all teardown_requests get passed the same original823 # exception.824 try:825 raise TypeError()826 except Exception:827 pass828829 @app.teardown_request830 def teardown_request2(exc):

fix flake8 bugbear findingsDavid Lordbefore adoptionc49ce2e

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

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 832–842why, one step back
832 called.append(True)
833 # This raises a new error and blows away sys.exc_info(), so we can834 # test that all teardown_requests get passed the same original835 # exception.836 try:837 raise TypeError()838 except Exception:839 pass840841 @app.route("/")842 def fails():

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

line 843why, one step back
843 raise ZeroDivisionError

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 844–909why, one step back
844
845 rv = client.get("/")846 assert rv.status_code == 500847 assert b"Internal Server Error" in rv.data848 assert len(called) == 2849850851def test_before_after_request_order(app, client):852 called = []853854 @app.before_request855 def before1():856 called.append(1)857858 @app.before_request859 def before2():860 called.append(2)861862 @app.after_request863 def after1(response):864 called.append(4)865 return response866867 @app.after_request868 def after2(response):869 called.append(3)870 return response871872 @app.teardown_request873 def finish1(exc):874 called.append(6)875876 @app.teardown_request877 def finish2(exc):878 called.append(5)879880 @app.route("/")881 def index():882 return "42"883884 rv = client.get("/")885 assert rv.data == b"42"886 assert called == [1, 2, 3, 4, 5, 6]887888889def test_error_handling(app, client):890 app.testing = False891892 @app.errorhandler(404)893 def not_found(e):894 return "not found", 404895896 @app.errorhandler(500)897 def internal_server_error(e):898 return "internal server error", 500899900 @app.errorhandler(Forbidden)901 def forbidden(e):902 return "forbidden", 403903904 @app.route("/")905 def index():906 flask.abort(404)907908 @app.route("/error")909 def error():

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

line 910why, one step back
910 raise ZeroDivisionError

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 911–935why, one step back
911
912 @app.route("/forbidden")913 def error2():914 flask.abort(403)915916 rv = client.get("/")917 assert rv.status_code == 404918 assert rv.data == b"not found"919 rv = client.get("/error")920 assert rv.status_code == 500921 assert b"internal server error" == rv.data922 rv = client.get("/forbidden")923 assert rv.status_code == 403924 assert b"forbidden" == rv.data925926927def test_error_handling_processing(app, client):928 app.testing = False929930 @app.errorhandler(500)931 def internal_server_error(e):932 return "internal server error", 500933934 @app.route("/")935 def broken_func():

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

line 936why, one step back
936 raise ZeroDivisionError

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 937–1105why, one step back
937
938 @app.after_request939 def after_request(resp):940 resp.mimetype = "text/x-special"941 return resp942943 resp = client.get("/")944 assert resp.mimetype == "text/x-special"945 assert resp.data == b"internal server error"946947948def test_baseexception_error_handling(app, client):949 app.testing = False950951 @app.route("/")952 def broken_func():953 raise KeyboardInterrupt()954955 with pytest.raises(KeyboardInterrupt):956 client.get("/")957958959def test_before_request_and_routing_errors(app, client):960 @app.before_request961 def attach_something():962 flask.g.something = "value"963964 @app.errorhandler(404)965 def return_something(error):966 return flask.g.something, 404967968 rv = client.get("/")969 assert rv.status_code == 404970 assert rv.data == b"value"971972973def test_user_error_handling(app, client):974 class MyException(Exception):975 pass976977 @app.errorhandler(MyException)978 def handle_my_exception(e):979 assert isinstance(e, MyException)980 return "42"981982 @app.route("/")983 def index():984 raise MyException()985986 assert client.get("/").data == b"42"987988989def test_http_error_subclass_handling(app, client):990 class ForbiddenSubclass(Forbidden):991 pass992993 @app.errorhandler(ForbiddenSubclass)994 def handle_forbidden_subclass(e):995 assert isinstance(e, ForbiddenSubclass)996 return "banana"997998 @app.errorhandler(403)999 def handle_403(e):1000 assert not isinstance(e, ForbiddenSubclass)1001 assert isinstance(e, Forbidden)1002 return "apple"10031004 @app.route("/1")1005 def index1():1006 raise ForbiddenSubclass()10071008 @app.route("/2")1009 def index2():1010 flask.abort(403)10111012 @app.route("/3")1013 def index3():1014 raise Forbidden()10151016 assert client.get("/1").data == b"banana"1017 assert client.get("/2").data == b"apple"1018 assert client.get("/3").data == b"apple"101910201021def test_errorhandler_precedence(app, client):1022 class E1(Exception):1023 pass10241025 class E2(Exception):1026 pass10271028 class E3(E1, E2):1029 pass10301031 @app.errorhandler(E2)1032 def handle_e2(e):1033 return "E2"10341035 @app.errorhandler(Exception)1036 def handle_exception(e):1037 return "Exception"10381039 @app.route("/E1")1040 def raise_e1():1041 raise E110421043 @app.route("/E3")1044 def raise_e3():1045 raise E310461047 rv = client.get("/E1")1048 assert rv.data == b"Exception"10491050 rv = client.get("/E3")1051 assert rv.data == b"E2"105210531054@pytest.mark.parametrize(1055 ("debug", "trap", "expect_key", "expect_abort"),1056 [(False, None, True, True), (True, None, False, True), (False, True, False, False)],1057)1058def test_trap_bad_request_key_error(app, client, debug, trap, expect_key, expect_abort):1059 app.config["DEBUG"] = debug1060 app.config["TRAP_BAD_REQUEST_ERRORS"] = trap10611062 @app.route("/key")1063 def fail():1064 flask.request.form["missing_key"]10651066 @app.route("/abort")1067 def allow_abort():1068 flask.abort(400)10691070 if expect_key:1071 rv = client.get("/key")1072 assert rv.status_code == 4001073 assert b"missing_key" not in rv.data1074 else:1075 with pytest.raises(KeyError) as exc_info:1076 client.get("/key")10771078 assert exc_info.errisinstance(BadRequest)1079 assert "missing_key" in exc_info.value.get_description()10801081 if expect_abort:1082 rv = client.get("/abort")1083 assert rv.status_code == 4001084 else:1085 with pytest.raises(BadRequest):1086 client.get("/abort")108710881089def test_trapping_of_all_http_exceptions(app, client):1090 app.config["TRAP_HTTP_EXCEPTIONS"] = True10911092 @app.route("/fail")1093 def fail():1094 flask.abort(404)10951096 with pytest.raises(NotFound):1097 client.get("/fail")109810991100def test_error_handler_after_processor_error(app, client):1101 app.testing = False11021103 @app.before_request1104 def before_request():1105 if _trigger == "before":

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

line 1106why, one step back
1106 raise ZeroDivisionError

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 1107–1110why, one step back
1107
1108 @app.after_request1109 def after_request(response):1110 if _trigger == "after":

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

lines 1111–1112why, one step back
1111 raise ZeroDivisionError
1112

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 1113–1425why, one step back
1113 return response
11141115 @app.route("/")1116 def index():1117 return "Foo"11181119 @app.errorhandler(500)1120 def internal_server_error(e):1121 return "Hello Server Error", 50011221123 for _trigger in "before", "after":1124 rv = client.get("/")1125 assert rv.status_code == 5001126 assert rv.data == b"Hello Server Error"112711281129def test_enctype_debug_helper(app, client):1130 from flask.debughelpers import DebugFilesKeyError11311132 app.debug = True11331134 @app.route("/fail", methods=["POST"])1135 def index():1136 return flask.request.files["foo"].filename11371138 with pytest.raises(DebugFilesKeyError) as e:1139 client.post("/fail", data={"foo": "index.txt"})1140 assert "no file contents were transmitted" in str(e.value)1141 assert "This was submitted: 'index.txt'" in str(e.value)114211431144def test_response_types(app, client):1145 @app.route("/text")1146 def from_text():1147 return "Hällo Wörld"11481149 @app.route("/bytes")1150 def from_bytes():1151 return "Hällo Wörld".encode()11521153 @app.route("/full_tuple")1154 def from_full_tuple():1155 return (1156 "Meh",1157 400,1158 {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1159 )11601161 @app.route("/text_headers")1162 def from_text_headers():1163 return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}11641165 @app.route("/text_status")1166 def from_text_status():1167 return "Hi, status!", 40011681169 @app.route("/response_headers")1170 def from_response_headers():1171 return (1172 flask.Response(1173 "Hello world", 404, {"Content-Type": "text/html", "X-Foo": "Baz"}1174 ),1175 {"Content-Type": "text/plain", "X-Foo": "Bar", "X-Bar": "Foo"},1176 )11771178 @app.route("/response_status")1179 def from_response_status():1180 return app.response_class("Hello world", 400), 50011811182 @app.route("/wsgi")1183 def from_wsgi():1184 return NotFound()11851186 @app.route("/dict")1187 def from_dict():1188 return {"foo": "bar"}, 20111891190 @app.route("/list")1191 def from_list():1192 return ["foo", "bar"], 20111931194 assert client.get("/text").data == "Hällo Wörld".encode()1195 assert client.get("/bytes").data == "Hällo Wörld".encode()11961197 rv = client.get("/full_tuple")1198 assert rv.data == b"Meh"1199 assert rv.headers["X-Foo"] == "Testing"1200 assert rv.status_code == 4001201 assert rv.mimetype == "text/plain"12021203 rv = client.get("/text_headers")1204 assert rv.data == b"Hello"1205 assert rv.headers["X-Foo"] == "Test"1206 assert rv.status_code == 2001207 assert rv.mimetype == "text/plain"12081209 rv = client.get("/text_status")1210 assert rv.data == b"Hi, status!"1211 assert rv.status_code == 4001212 assert rv.mimetype == "text/html"12131214 rv = client.get("/response_headers")1215 assert rv.data == b"Hello world"1216 assert rv.content_type == "text/plain"1217 assert rv.headers.getlist("X-Foo") == ["Bar"]1218 assert rv.headers["X-Bar"] == "Foo"1219 assert rv.status_code == 40412201221 rv = client.get("/response_status")1222 assert rv.data == b"Hello world"1223 assert rv.status_code == 50012241225 rv = client.get("/wsgi")1226 assert b"Not Found" in rv.data1227 assert rv.status_code == 40412281229 rv = client.get("/dict")1230 assert rv.json == {"foo": "bar"}1231 assert rv.status_code == 20112321233 rv = client.get("/list")1234 assert rv.json == ["foo", "bar"]1235 assert rv.status_code == 201123612371238def test_response_type_errors():1239 app = flask.Flask(__name__)1240 app.testing = True12411242 @app.route("/none")1243 def from_none():1244 pass12451246 @app.route("/small_tuple")1247 def from_small_tuple():1248 return ("Hello",)12491250 @app.route("/large_tuple")1251 def from_large_tuple():1252 return "Hello", 234, {"X-Foo": "Bar"}, "???"12531254 @app.route("/bad_type")1255 def from_bad_type():1256 return True12571258 @app.route("/bad_wsgi")1259 def from_bad_wsgi():1260 return lambda: None12611262 c = app.test_client()12631264 with pytest.raises(TypeError) as e:1265 c.get("/none")12661267 assert "returned None" in str(e.value)1268 assert "from_none" in str(e.value)12691270 with pytest.raises(TypeError) as e:1271 c.get("/small_tuple")12721273 assert "tuple must have the form" in str(e.value)12741275 with pytest.raises(TypeError):1276 c.get("/large_tuple")12771278 with pytest.raises(TypeError) as e:1279 c.get("/bad_type")12801281 assert "it was a bool" in str(e.value)12821283 with pytest.raises(TypeError):1284 c.get("/bad_wsgi")128512861287def test_make_response(app, req_ctx):1288 rv = flask.make_response()1289 assert rv.status_code == 2001290 assert rv.data == b""1291 assert rv.mimetype == "text/html"12921293 rv = flask.make_response("Awesome")1294 assert rv.status_code == 2001295 assert rv.data == b"Awesome"1296 assert rv.mimetype == "text/html"12971298 rv = flask.make_response("W00t", 404)1299 assert rv.status_code == 4041300 assert rv.data == b"W00t"1301 assert rv.mimetype == "text/html"13021303 rv = flask.make_response(c for c in "Hello")1304 assert rv.status_code == 2001305 assert rv.data == b"Hello"1306 assert rv.mimetype == "text/html"130713081309def test_make_response_with_response_instance(app, req_ctx):1310 rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1311 assert rv.status_code == 4001312 assert rv.data == b'{"msg":"W00t"}\n'1313 assert rv.mimetype == "application/json"13141315 rv = flask.make_response(flask.Response(""), 400)1316 assert rv.status_code == 4001317 assert rv.data == b""1318 assert rv.mimetype == "text/html"13191320 rv = flask.make_response(1321 flask.Response("", headers={"Content-Type": "text/html"}),1322 400,1323 [("X-Foo", "bar")],1324 )1325 assert rv.status_code == 4001326 assert rv.headers["Content-Type"] == "text/html"1327 assert rv.headers["X-Foo"] == "bar"132813291330@pytest.mark.parametrize("compact", [True, False])1331def test_jsonify_no_prettyprint(app, compact):1332 app.json.compact = compact1333 rv = app.json.response({"msg": {"submsg": "W00t"}, "msg2": "foobar"})1334 data = rv.data.strip()1335 assert (b" " not in data) is compact1336 assert (b"\n" not in data) is compact133713381339def test_jsonify_mimetype(app, req_ctx):1340 app.json.mimetype = "application/vnd.api+json"1341 msg = {"msg": {"submsg": "W00t"}}1342 rv = flask.make_response(flask.jsonify(msg), 200)1343 assert rv.mimetype == "application/vnd.api+json"134413451346def test_json_dump_dataclass(app, req_ctx):1347 from dataclasses import make_dataclass13481349 Data = make_dataclass("Data", [("name", str)])1350 value = app.json.dumps(Data("Flask"))1351 value = app.json.loads(value)1352 assert value == {"name": "Flask"}135313541355def test_jsonify_args_and_kwargs_check(app, req_ctx):1356 with pytest.raises(TypeError) as e:1357 flask.jsonify("fake args", kwargs="fake")1358 assert "args or kwargs" in str(e.value)135913601361def test_url_generation(app, req_ctx):1362 @app.route("/hello/<name>", methods=["POST"])1363 def hello():1364 pass13651366 assert flask.url_for("hello", name="test x") == "/hello/test%20x"1367 assert (1368 flask.url_for("hello", name="test x", _external=True)1369 == "http://localhost/hello/test%20x"1370 )137113721373def test_build_error_handler(app):1374 # Test base case, a URL which results in a BuildError.1375 with app.test_request_context():1376 pytest.raises(BuildError, flask.url_for, "spam")13771378 # Verify the error is re-raised if not the current exception.1379 try:1380 with app.test_request_context():1381 flask.url_for("spam")1382 except BuildError as err:1383 error = err1384 try:1385 raise RuntimeError("Test case where BuildError is not current.")1386 except RuntimeError:1387 pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})13881389 # Test a custom handler.1390 def handler(error, endpoint, values):1391 # Just a test.1392 return "/test_handler/"13931394 app.url_build_error_handlers.append(handler)1395 with app.test_request_context():1396 assert flask.url_for("spam") == "/test_handler/"139713981399def test_build_error_handler_reraise(app):1400 # Test a custom handler which reraises the BuildError1401 def handler_raises_build_error(error, endpoint, values):1402 raise error14031404 app.url_build_error_handlers.append(handler_raises_build_error)14051406 with app.test_request_context():1407 pytest.raises(BuildError, flask.url_for, "not.existing")140814091410def test_url_for_passes_special_values_to_build_error_handler(app):1411 @app.url_build_error_handlers.append1412 def handler(error, endpoint, values):1413 assert values == {1414 "_external": False,1415 "_anchor": None,1416 "_method": None,1417 "_scheme": None,1418 }1419 return "handled"14201421 with app.test_request_context():1422 flask.url_for("/")142314241425def test_static_files(app, client):

all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8

lines 1426–1432why, one step back
1426 with client.get("/static/index.html") as rv:
1427 assert rv.status_code == 2001428 assert rv.data.strip() == b"<h1>Hello World!</h1>"1429 with app.test_request_context():1430 assert (1431 flask.url_for("static", filename="index.html") == "/static/index.html"1432 )

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 1433–1438why, one step back
1433
14341435def test_static_url_path():1436 app = flask.Flask(__name__, static_url_path="/foo")1437 app.testing = True1438

all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8

lines 1439–1441why, one step back
1439 with app.test_client().get("/foo/index.html") as rv:
1440 assert rv.status_code == 2001441

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 1442–1449why, one step back
1442 with app.test_request_context():
1443 assert flask.url_for("static", filename="index.html") == "/foo/index.html"144414451446def test_static_url_path_with_ending_slash():1447 app = flask.Flask(__name__, static_url_path="/foo/")1448 app.testing = True1449

all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8

lines 1450–1452why, one step back
1450 with app.test_client().get("/foo/index.html") as rv:
1451 assert rv.status_code == 2001452

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 1453–1459why, one step back
1453 with app.test_request_context():
1454 assert flask.url_for("static", filename="index.html") == "/foo/index.html"145514561457def test_static_url_empty_path(app):1458 app = flask.Flask(__name__, static_folder="", static_url_path="")1459

all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8

lines 1460–1461why, one step back
1460 with app.test_client().open("/static/index.html", method="GET") as rv:
1461 assert rv.status_code == 200

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 1462why, one step back
1462

all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8

line 1463why, one step back
1463

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 1464–1466why, one step back
1464def test_static_url_empty_path_default(app):
1465 app = flask.Flask(__name__, static_folder="")1466

all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8

lines 1467–1468why, one step back
1467 with app.test_client().open("/static/index.html", method="GET") as rv:
1468 assert rv.status_code == 200

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 1469why, one step back
1469

all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8

line 1470why, one step back
1470

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 1471–1475why, one step back
1471def test_static_folder_with_pathlib_path(app):
1472 from pathlib import Path14731474 app = flask.Flask(__name__, static_folder=Path("static"))1475

all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8

lines 1476–1477why, one step back
1476 with app.test_client().open("/static/index.html", method="GET") as rv:
1477 assert rv.status_code == 200

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 1478why, one step back
1478

all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8

line 1479why, one step back
1479

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 1480–1493why, one step back
1480def test_static_folder_with_ending_slash():
1481 app = flask.Flask(__name__, static_folder="static/")14821483 @app.route("/<path:path>")1484 def catch_all(path):1485 return path14861487 rv = app.test_client().get("/catch/all")1488 assert rv.data == b"catch/all"148914901491def test_static_route_with_host_matching():1492 app = flask.Flask(__name__, host_matching=True, static_host="example.com")1493 c = app.test_client()

all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8

lines 1494–1497why, one step back
1494
1495 with c.get("http://example.com/static/index.html") as rv:1496 assert rv.status_code == 2001497

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 1498–1515why, one step back
1498 with app.test_request_context():
1499 rv = flask.url_for("static", filename="index.html", _external=True)1500 assert rv == "http://example.com/static/index.html"1501 # Providing static_host without host_matching=True should error.1502 with pytest.raises(AssertionError):1503 flask.Flask(__name__, static_host="example.com")1504 # Providing host_matching=True with static_folder1505 # but without static_host should error.1506 with pytest.raises(AssertionError):1507 flask.Flask(__name__, host_matching=True)1508 # Providing host_matching=True without static_host1509 # but with static_folder=None should not error.1510 flask.Flask(__name__, host_matching=True, static_folder=None)151115121513def test_request_locals():1514 assert repr(flask.g) == "<LocalProxy unbound>"1515 assert not flask.g

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

lines 1516–1517why, one step back
1516
1517

update domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2

lines 1518–1520why, one step back
1518werkzeug_3_2 = importlib.metadata.version("werkzeug") >= "3.2."
15191520

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

line 1521why, one step back
1521@pytest.mark.parametrize(

update domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2

line 1522why, one step back
1522 ("subdomain_matching", "host_matching", "expect_subdomain", "expect_host"),

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

line 1523why, one step back
1523 [

update domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2

lines 1524–1526why, one step back
1524 (False, False, "default", "default"),
1525 (True, False, "abc", "<invalid>"),1526 (False, True, "abc", "default"),

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

lines 1527–1531why, one step back
1527 ],
1528)1529def test_server_name_matching(1530 subdomain_matching: bool,1531 host_matching: bool,

update domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2

lines 1532–1533why, one step back
1532 expect_subdomain: str,
1533 expect_host: str,

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

lines 1534–1550why, one step back
1534) -> None:
1535 app = flask.Flask(1536 __name__,1537 subdomain_matching=subdomain_matching,1538 host_matching=host_matching,1539 static_host="example.test" if host_matching else None,1540 )1541 app.config["SERVER_NAME"] = "example.test"15421543 @app.route("/", defaults={"name": "default"}, host="<name>")1544 @app.route("/", subdomain="<name>", host="<name>.example.test")1545 def index(name: str) -> str:1546 return name15471548 client = app.test_client()15491550 r = client.get(base_url="http://example.test")

update domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2

line 1551why, one step back
1551 assert r.text == "default"

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

lines 1552–1553why, one step back
1552
1553 r = client.get(base_url="http://abc.example.test")

update domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2

line 1554why, one step back
1554 assert r.text == expect_subdomain

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

lines 1555–1558why, one step back
1555
1556 with pytest.warns() if subdomain_matching else nullcontext():1557 r = client.get(base_url="http://xyz.other.test")1558

update domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2

lines 1559–1562why, one step back
1559 if werkzeug_3_2:
1560 assert r.text == "default"1561 else:1562 assert r.text == expect_host

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 1563–1597why, one step back
1563
15641565def test_server_name_subdomain():1566 app = flask.Flask(__name__, subdomain_matching=True)1567 client = app.test_client()15681569 @app.route("/")1570 def index():1571 return "default"15721573 @app.route("/", subdomain="foo")1574 def subdomain():1575 return "subdomain"15761577 app.config["SERVER_NAME"] = "dev.local:5000"1578 rv = client.get("/")1579 assert rv.data == b"default"15801581 rv = client.get("/", "http://dev.local:5000")1582 assert rv.data == b"default"15831584 rv = client.get("/", "https://dev.local:5000")1585 assert rv.data == b"default"15861587 app.config["SERVER_NAME"] = "dev.local:443"1588 rv = client.get("/", "https://dev.local")15891590 # Werkzeug 1.0 fixes matching https scheme with 443 port1591 if rv.status_code != 404:1592 assert rv.data == b"default"15931594 app.config["SERVER_NAME"] = "dev.local"1595 rv = client.get("/", "https://dev.local")1596 assert rv.data == b"default"1597

update domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2

line 1598why, one step back
1598 with pytest.warns(match="Current server name"):

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 1599why, one step back
1599 rv = client.get("/", "http://foo.localhost")

update domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2

lines 1600–1603why, one step back
1600
1601 if werkzeug_3_2:1602 assert rv.status_code == 2001603 else:

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 1604–1615why, one step back
1604 assert rv.status_code == 404
16051606 rv = client.get("/", "http://foo.dev.local")1607 assert rv.data == b"subdomain"160816091610@pytest.mark.parametrize("key", ["TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None])1611def test_exception_propagation(app, client, key):1612 app.testing = False16131614 @app.route("/")1615 def index():

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

line 1616why, one step back
1616 raise ZeroDivisionError

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 1617–1838why, one step back
1617
1618 if key is not None:1619 app.config[key] = True16201621 with pytest.raises(ZeroDivisionError):1622 client.get("/")1623 else:1624 assert client.get("/").status_code == 500162516261627@pytest.mark.parametrize("debug", [True, False])1628@pytest.mark.parametrize("use_debugger", [True, False])1629@pytest.mark.parametrize("use_reloader", [True, False])1630@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1631def test_werkzeug_passthrough_errors(1632 monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1633):1634 rv = {}16351636 # Mocks werkzeug.serving.run_simple method1637 def run_simple_mock(*args, **kwargs):1638 rv["passthrough_errors"] = kwargs.get("passthrough_errors")16391640 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1641 app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1642 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)164316441645def test_url_processors(app, client):1646 @app.url_defaults1647 def add_language_code(endpoint, values):1648 if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1649 endpoint, "lang_code"1650 ):1651 values.setdefault("lang_code", flask.g.lang_code)16521653 @app.url_value_preprocessor1654 def pull_lang_code(endpoint, values):1655 flask.g.lang_code = values.pop("lang_code", None)16561657 @app.route("/<lang_code>/")1658 def index():1659 return flask.url_for("about")16601661 @app.route("/<lang_code>/about")1662 def about():1663 return flask.url_for("something_else")16641665 @app.route("/foo")1666 def something_else():1667 return flask.url_for("about", lang_code="en")16681669 assert client.get("/de/").data == b"/de/about"1670 assert client.get("/de/about").data == b"/foo"1671 assert client.get("/foo").data == b"/en/about"167216731674def test_inject_blueprint_url_defaults(app):1675 bp = flask.Blueprint("foo", __name__, template_folder="template")16761677 @bp.url_defaults1678 def bp_defaults(endpoint, values):1679 values["page"] = "login"16801681 @bp.route("/<page>")1682 def view(page):1683 pass16841685 app.register_blueprint(bp)16861687 values = dict()1688 app.inject_url_defaults("foo.view", values)1689 expected = dict(page="login")1690 assert values == expected16911692 with app.test_request_context("/somepage"):1693 url = flask.url_for("foo.view")1694 expected = "/login"1695 assert url == expected169616971698def test_nonascii_pathinfo(app, client):1699 @app.route("/киртест")1700 def index():1701 return "Hello World!"17021703 rv = client.get("/киртест")1704 assert rv.data == b"Hello World!"170517061707def test_no_setup_after_first_request(app, client):1708 app.debug = True17091710 @app.route("/")1711 def index():1712 return "Awesome"17131714 assert client.get("/").data == b"Awesome"17151716 with pytest.raises(AssertionError) as exc_info:1717 app.add_url_rule("/foo", endpoint="late")17181719 assert "setup method 'add_url_rule'" in str(exc_info.value)172017211722def test_routing_redirect_debugging(monkeypatch, app, client):1723 app.config["DEBUG"] = True17241725 @app.route("/user/", methods=["GET", "POST"])1726 def user():1727 return flask.request.form["status"]17281729 # default redirect code preserves form data1730 rv = client.post("/user", data={"status": "success"}, follow_redirects=True)1731 assert rv.data == b"success"17321733 # 301 and 302 raise error1734 monkeypatch.setattr(RequestRedirect, "code", 301)17351736 with client, pytest.raises(AssertionError) as exc_info:1737 client.post("/user", data={"status": "error"}, follow_redirects=True)17381739 assert "canonical URL 'http://localhost/user/'" in str(exc_info.value)174017411742def test_route_decorator_custom_endpoint(app, client):1743 app.debug = True17441745 @app.route("/foo/")1746 def foo():1747 return flask.request.endpoint17481749 @app.route("/bar/", endpoint="bar")1750 def for_bar():1751 return flask.request.endpoint17521753 @app.route("/bar/123", endpoint="123")1754 def for_bar_foo():1755 return flask.request.endpoint17561757 with app.test_request_context():1758 assert flask.url_for("foo") == "/foo/"1759 assert flask.url_for("bar") == "/bar/"1760 assert flask.url_for("123") == "/bar/123"17611762 assert client.get("/foo/").data == b"foo"1763 assert client.get("/bar/").data == b"bar"1764 assert client.get("/bar/123").data == b"123"176517661767def test_get_method_on_g(app_ctx):1768 assert flask.g.get("x") is None1769 assert flask.g.get("x", 11) == 111770 flask.g.x = 421771 assert flask.g.get("x") == 421772 assert flask.g.x == 42177317741775def test_g_iteration_protocol(app_ctx):1776 flask.g.foo = 231777 flask.g.bar = 421778 assert "foo" in flask.g1779 assert "foos" not in flask.g1780 assert sorted(flask.g) == ["bar", "foo"]178117821783def test_subdomain_basic_support():1784 app = flask.Flask(__name__, subdomain_matching=True)1785 app.config["SERVER_NAME"] = "localhost.localdomain"1786 client = app.test_client()17871788 @app.route("/")1789 def normal_index():1790 return "normal index"17911792 @app.route("/", subdomain="test")1793 def test_index():1794 return "test index"17951796 rv = client.get("/", "http://localhost.localdomain/")1797 assert rv.data == b"normal index"17981799 rv = client.get("/", "http://test.localhost.localdomain/")1800 assert rv.data == b"test index"180118021803def test_subdomain_matching():1804 app = flask.Flask(__name__, subdomain_matching=True)1805 client = app.test_client()1806 app.config["SERVER_NAME"] = "localhost.localdomain"18071808 @app.route("/", subdomain="<user>")1809 def index(user):1810 return f"index for {user}"18111812 rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1813 assert rv.data == b"index for mitsuhiko"181418151816def test_subdomain_matching_with_ports():1817 app = flask.Flask(__name__, subdomain_matching=True)1818 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1819 client = app.test_client()18201821 @app.route("/", subdomain="<user>")1822 def index(user):1823 return f"index for {user}"18241825 rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1826 assert rv.data == b"index for mitsuhiko"182718281829@pytest.mark.parametrize("matching", (False, True))1830def test_subdomain_matching_other_name(matching):1831 app = flask.Flask(__name__, subdomain_matching=matching)1832 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1833 client = app.test_client()18341835 @app.route("/")1836 def index():1837 return "", 2041838

update domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2

lines 1839–1840why, one step back
1839 with pytest.warns(match="Current server name") if matching else nullcontext():
1840 # ip address can't match name, but will fall back to default

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 1841why, one step back
1841 rv = client.get("/", "http://127.0.0.1:3000/")

update domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2

lines 1842–1845why, one step back
1842
1843 if werkzeug_3_2:1844 assert rv.status_code == 2041845 else:

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 1846–1915why, one step back
1846 assert rv.status_code == 404 if matching else 204
18471848 # allow all subdomains if matching is disabled1849 rv = client.get("/", "http://www.localhost.localdomain:3000/")1850 assert rv.status_code == 404 if matching else 204185118521853def test_multi_route_rules(app, client):1854 @app.route("/")1855 @app.route("/<test>/")1856 def index(test="a"):1857 return test18581859 rv = client.open("/")1860 assert rv.data == b"a"1861 rv = client.open("/b/")1862 assert rv.data == b"b"186318641865def test_multi_route_class_views(app, client):1866 class View:1867 def __init__(self, app):1868 app.add_url_rule("/", "index", self.index)1869 app.add_url_rule("/<test>/", "index", self.index)18701871 def index(self, test="a"):1872 return test18731874 _ = View(app)1875 rv = client.open("/")1876 assert rv.data == b"a"1877 rv = client.open("/b/")1878 assert rv.data == b"b"187918801881def test_run_defaults(monkeypatch, app):1882 rv = {}18831884 # Mocks werkzeug.serving.run_simple method1885 def run_simple_mock(*args, **kwargs):1886 rv["result"] = "running..."18871888 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1889 app.run()1890 assert rv["result"] == "running..."189118921893def test_run_server_port(monkeypatch, app):1894 rv = {}18951896 # Mocks werkzeug.serving.run_simple method1897 def run_simple_mock(hostname, port, application, *args, **kwargs):1898 rv["result"] = f"running on {hostname}:{port} ..."18991900 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1901 hostname, port = "localhost", 80001902 app.run(hostname, port, debug=True)1903 assert rv["result"] == f"running on {hostname}:{port} ..."190419051906@pytest.mark.parametrize(1907 "host,port,server_name,expect_host,expect_port",1908 (1909 (None, None, "pocoo.org:8080", "pocoo.org", 8080),1910 ("localhost", None, "pocoo.org:8080", "localhost", 8080),1911 (None, 80, "pocoo.org:8080", "pocoo.org", 80),1912 ("localhost", 80, "pocoo.org:8080", "localhost", 80),1913 ("localhost", 0, "localhost:8080", "localhost", 0),1914 (None, None, "localhost:8080", "localhost", 8080),1915 (None, None, "localhost:0", "localhost", 0),

Fix `.partition(":")` usage on potential IPv6 addresses (#6096)David Lordbefore adoption05e9c6b

line 1916why, one step back
1916 (None, None, "[::1]:8080", "::1", 8080),

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 1917–1974why, one step back
1917 ),
1918)1919def test_run_from_config(1920 monkeypatch, host, port, server_name, expect_host, expect_port, app1921):1922 def run_simple_mock(hostname, port, *args, **kwargs):1923 assert hostname == expect_host1924 assert port == expect_port19251926 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1927 app.config["SERVER_NAME"] = server_name1928 app.run(host, port)192919301931def test_max_cookie_size(app, client, recwarn):1932 app.config["MAX_COOKIE_SIZE"] = 10019331934 # outside app context, default to Werkzeug static value,1935 # which is also the default config1936 response = flask.Response()1937 default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1938 assert response.max_cookie_size == default19391940 # inside app context, use app config1941 with app.app_context():1942 assert flask.Response().max_cookie_size == 10019431944 @app.route("/")1945 def index():1946 r = flask.Response("", status=204)1947 r.set_cookie("foo", "bar" * 100)1948 return r19491950 client.get("/")1951 assert len(recwarn) == 11952 w = recwarn.pop()1953 assert "cookie is too large" in str(w.message)19541955 app.config["MAX_COOKIE_SIZE"] = 019561957 client.get("/")1958 assert len(recwarn) == 0195919601961@require_cpython_gc1962def test_app_freed_on_zero_refcount():1963 # A Flask instance should not create a reference cycle that prevents CPython1964 # from freeing it when all external references to it are released (see #3761).1965 gc.disable()1966 try:1967 app = flask.Flask(__name__)1968 assert app.view_functions["static"]1969 weak = weakref.ref(app)1970 assert weak() is not None1971 del app1972 assert weak() is None1973 finally:1974 gc.enable()