Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

1,944 lines · 52.3 KiB · Python

Last changed by

Merge commit from forkDavid Lordbefore adoption73d6504

History of this file

Take it

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

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

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 pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

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 pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

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 pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

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 pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

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 pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

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 pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

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 pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

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 pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

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 pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

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 pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

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 pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

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–383why, 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)383

Merge commit from forkDavid Lordbefore adoption73d6504

lines 384–388why, one step back
384 # Set session with initial secret key, and two valid expiring keys
385 app.secret_key, app.config["SECRET_KEY_FALLBACKS"] = (386 "0 key",387 ["-1 key", "-2 key"],388 )

enable secret key rotation (#5632)David Lordbefore adoptiona20bcff

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

Merge commit from forkDavid Lordbefore adoption73d6504

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

enable secret key rotation (#5632)David Lordbefore adoptiona20bcff

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

Merge commit from forkDavid Lordbefore adoption73d6504

lines 394–398why, one step back
394 # Rotate the valid keys, session can be loaded
395 app.secret_key, app.config["SECRET_KEY_FALLBACKS"] = (396 "+1 key",397 ["0 key", "-1 key"],398 )

enable secret key rotation (#5632)David Lordbefore adoptiona20bcff

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

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 400–455why, one step back
400
401402def test_session_expiration(app, client):403 permanent = True404405 @app.route("/")406 def index():407 flask.session["test"] = 42408 flask.session.permanent = permanent409 return ""410411 @app.route("/test")412 def test():413 return str(flask.session.permanent)414415 rv = client.get("/")416 assert "set-cookie" in rv.headers417 match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])418 expires = parse_date(match.group())419 expected = datetime.now(timezone.utc) + app.permanent_session_lifetime420 assert expires.year == expected.year421 assert expires.month == expected.month422 assert expires.day == expected.day423424 rv = client.get("/test")425 assert rv.data == b"True"426427 permanent = False428 rv = client.get("/")429 assert "set-cookie" in rv.headers430 match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])431 assert match is None432433434def test_session_stored_last(app, client):435 @app.after_request436 def modify_session(response):437 flask.session["foo"] = 42438 return response439440 @app.route("/")441 def dump_session_contents():442 return repr(flask.session.get("foo"))443444 assert client.get("/").data == b"None"445 assert client.get("/").data == b"42"446447448def test_session_special_types(app, client):449 now = datetime.now(timezone.utc).replace(microsecond=0)450 the_uuid = uuid.uuid4()451452 @app.route("/")453 def dump_session_contents():454 flask.session["t"] = (1, 2, 3)455 flask.session["b"] = b"\xff"

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

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

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 457–467why, one step back
457 flask.session["u"] = the_uuid
458 flask.session["d"] = now459 flask.session["t_tag"] = {" t": "not-a-tuple"}460 flask.session["di_t_tag"] = {" t__": "not-a-tuple"}461 flask.session["di_tag"] = {" di": "not-a-dict"}462 return "", 204463464 with client:465 client.get("/")466 s = flask.session467 assert s["t"] == (1, 2, 3)

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

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

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

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

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

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

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

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

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 472–537why, one step back
472 assert s["u"] == the_uuid
473 assert s["d"] == now474 assert s["t_tag"] == {" t": "not-a-tuple"}475 assert s["di_t_tag"] == {" t__": "not-a-tuple"}476 assert s["di_tag"] == {" di": "not-a-dict"}477478479def test_session_cookie_setting(app):480 is_permanent = True481482 @app.route("/bump")483 def bump():484 rv = flask.session["foo"] = flask.session.get("foo", 0) + 1485 flask.session.permanent = is_permanent486 return str(rv)487488 @app.route("/read")489 def read():490 return str(flask.session.get("foo", 0))491492 def run_test(expect_header):493 with app.test_client() as c:494 assert c.get("/bump").data == b"1"495 assert c.get("/bump").data == b"2"496 assert c.get("/bump").data == b"3"497498 rv = c.get("/read")499 set_cookie = rv.headers.get("set-cookie")500 assert (set_cookie is not None) == expect_header501 assert rv.data == b"3"502503 is_permanent = True504 app.config["SESSION_REFRESH_EACH_REQUEST"] = True505 run_test(expect_header=True)506507 is_permanent = True508 app.config["SESSION_REFRESH_EACH_REQUEST"] = False509 run_test(expect_header=False)510511 is_permanent = False512 app.config["SESSION_REFRESH_EACH_REQUEST"] = True513 run_test(expect_header=False)514515 is_permanent = False516 app.config["SESSION_REFRESH_EACH_REQUEST"] = False517 run_test(expect_header=False)518519520def test_session_vary_cookie(app, client):521 @app.route("/set")522 def set_session():523 flask.session["test"] = "test"524 return ""525526 @app.route("/get")527 def get():528 return flask.session.get("test")529530 @app.route("/getitem")531 def getitem():532 return flask.session["test"]533534 @app.route("/setdefault")535 def setdefault():536 return flask.session.setdefault("test", "default")537

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

lines 538–542why, one step back
538 @app.route("/clear")
539 def clear():540 flask.session.clear()541 return ""542

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 543–574why, one step back
543 @app.route("/vary-cookie-header-set")
544 def vary_cookie_header_set():545 response = flask.Response()546 response.vary.add("Cookie")547 flask.session["test"] = "test"548 return response549550 @app.route("/vary-header-set")551 def vary_header_set():552 response = flask.Response()553 response.vary.update(("Accept-Encoding", "Accept-Language"))554 flask.session["test"] = "test"555 return response556557 @app.route("/no-vary-header")558 def no_vary_header():559 return ""560561 def expect(path, header_value="Cookie"):562 rv = client.get(path)563564 if header_value:565 # The 'Vary' key should exist in the headers only once.566 assert len(rv.headers.get_all("Vary")) == 1567 assert rv.headers["Vary"] == header_value568 else:569 assert "Vary" not in rv.headers570571 expect("/set")572 expect("/get")573 expect("/getitem")574 expect("/setdefault")

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

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

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 576–578why, one step back
576 expect("/vary-cookie-header-set")
577 expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")578 expect("/no-vary-header", None)

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

lines 579–595why, one step back
579
580581def test_session_refresh_vary(app, client):582 @app.get("/login")583 def login():584 flask.session["user_id"] = 1585 flask.session.permanent = True586 return ""587588 @app.get("/ignored")589 def ignored():590 return ""591592 rv = client.get("/login")593 assert rv.headers["Vary"] == "Cookie"594 rv = client.get("/ignored")595 assert rv.headers["Vary"] == "Cookie"

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 596–617why, one step back
596
597598def test_flashes(app, req_ctx):599 assert not flask.session.modified600 flask.flash("Zap")601 flask.session.modified = False602 flask.flash("Zip")603 assert flask.session.modified604 assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]605606607def test_extended_flashing(app):608 # Be sure app.testing=True below, else tests can fail silently.609 #610 # Specifically, if app.testing is not set to True, the AssertionErrors611 # in the view functions will cause a 500 response to the test client612 # instead of propagating exceptions.613614 @app.route("/")615 def index():616 flask.flash("Hello World")617 flask.flash("Hello World", "error")

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

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

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 619–626why, one step back
619 return ""
620621 @app.route("/test/")622 def test():623 messages = flask.get_flashed_messages()624 assert list(messages) == [625 "Hello World",626 "Hello World",

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

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

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 628–637why, one step back
628 ]
629 return ""630631 @app.route("/test_with_categories/")632 def test_with_categories():633 messages = flask.get_flashed_messages(with_categories=True)634 assert len(messages) == 3635 assert list(messages) == [636 ("message", "Hello World"),637 ("error", "Hello World"),

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

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

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 639–656why, one step back
639 ]
640 return ""641642 @app.route("/test_filter/")643 def test_filter():644 messages = flask.get_flashed_messages(645 category_filter=["message"], with_categories=True646 )647 assert list(messages) == [("message", "Hello World")]648 return ""649650 @app.route("/test_filters/")651 def test_filters():652 messages = flask.get_flashed_messages(653 category_filter=["message", "warning"], with_categories=True654 )655 assert list(messages) == [656 ("message", "Hello World"),

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

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

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 658–665why, one step back
658 ]
659 return ""660661 @app.route("/test_filters_without_returning_categories/")662 def test_filters2():663 messages = flask.get_flashed_messages(category_filter=["message", "warning"])664 assert len(messages) == 2665 assert messages[0] == "Hello World"

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

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

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 667–796why, one step back
667 return ""
668669 # Create new test client on each test to clean flashed messages.670671 client = app.test_client()672 client.get("/")673 client.get("/test_with_categories/")674675 client = app.test_client()676 client.get("/")677 client.get("/test_filter/")678679 client = app.test_client()680 client.get("/")681 client.get("/test_filters/")682683 client = app.test_client()684 client.get("/")685 client.get("/test_filters_without_returning_categories/")686687688def test_request_processing(app, client):689 evts = []690691 @app.before_request692 def before_request():693 evts.append("before")694695 @app.after_request696 def after_request(response):697 response.data += b"|after"698 evts.append("after")699 return response700701 @app.route("/")702 def index():703 assert "before" in evts704 assert "after" not in evts705 return "request"706707 assert "after" not in evts708 rv = client.get("/").data709 assert "after" in evts710 assert rv == b"request|after"711712713def test_request_preprocessing_early_return(app, client):714 evts = []715716 @app.before_request717 def before_request1():718 evts.append(1)719720 @app.before_request721 def before_request2():722 evts.append(2)723 return "hello"724725 @app.before_request726 def before_request3():727 evts.append(3)728 return "bye"729730 @app.route("/")731 def index():732 evts.append("index")733 return "damnit"734735 rv = client.get("/").data.strip()736 assert rv == b"hello"737 assert evts == [1, 2]738739740def test_after_request_processing(app, client):741 @app.route("/")742 def index():743 @flask.after_this_request744 def foo(response):745 response.headers["X-Foo"] = "a header"746 return response747748 return "Test"749750 resp = client.get("/")751 assert resp.status_code == 200752 assert resp.headers["X-Foo"] == "a header"753754755def test_teardown_request_handler(app, client):756 called = []757758 @app.teardown_request759 def teardown_request(exc):760 called.append(True)761 return "Ignored"762763 @app.route("/")764 def root():765 return "Response"766767 rv = client.get("/")768 assert rv.status_code == 200769 assert b"Response" in rv.data770 assert len(called) == 1771772773def test_teardown_request_handler_debug_mode(app, client):774 called = []775776 @app.teardown_request777 def teardown_request(exc):778 called.append(True)779 return "Ignored"780781 @app.route("/")782 def root():783 return "Response"784785 rv = client.get("/")786 assert rv.status_code == 200787 assert b"Response" in rv.data788 assert len(called) == 1789790791def test_teardown_request_handler_error(app, client):792 called = []793 app.testing = False794795 @app.teardown_request796 def teardown_request1(exc):

fix flake8 bugbear findingsDavid Lordbefore adoptionc49ce2e

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

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 798–808why, one step back
798 called.append(True)
799 # This raises a new error and blows away sys.exc_info(), so we can800 # test that all teardown_requests get passed the same original801 # exception.802 try:803 raise TypeError()804 except Exception:805 pass806807 @app.teardown_request808 def teardown_request2(exc):

fix flake8 bugbear findingsDavid Lordbefore adoptionc49ce2e

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

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 810–820why, one step back
810 called.append(True)
811 # This raises a new error and blows away sys.exc_info(), so we can812 # test that all teardown_requests get passed the same original813 # exception.814 try:815 raise TypeError()816 except Exception:817 pass818819 @app.route("/")820 def fails():

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

line 821why, one step back
821 raise ZeroDivisionError

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 822–887why, one step back
822
823 rv = client.get("/")824 assert rv.status_code == 500825 assert b"Internal Server Error" in rv.data826 assert len(called) == 2827828829def test_before_after_request_order(app, client):830 called = []831832 @app.before_request833 def before1():834 called.append(1)835836 @app.before_request837 def before2():838 called.append(2)839840 @app.after_request841 def after1(response):842 called.append(4)843 return response844845 @app.after_request846 def after2(response):847 called.append(3)848 return response849850 @app.teardown_request851 def finish1(exc):852 called.append(6)853854 @app.teardown_request855 def finish2(exc):856 called.append(5)857858 @app.route("/")859 def index():860 return "42"861862 rv = client.get("/")863 assert rv.data == b"42"864 assert called == [1, 2, 3, 4, 5, 6]865866867def test_error_handling(app, client):868 app.testing = False869870 @app.errorhandler(404)871 def not_found(e):872 return "not found", 404873874 @app.errorhandler(500)875 def internal_server_error(e):876 return "internal server error", 500877878 @app.errorhandler(Forbidden)879 def forbidden(e):880 return "forbidden", 403881882 @app.route("/")883 def index():884 flask.abort(404)885886 @app.route("/error")887 def error():

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

line 888why, one step back
888 raise ZeroDivisionError

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 889–913why, one step back
889
890 @app.route("/forbidden")891 def error2():892 flask.abort(403)893894 rv = client.get("/")895 assert rv.status_code == 404896 assert rv.data == b"not found"897 rv = client.get("/error")898 assert rv.status_code == 500899 assert b"internal server error" == rv.data900 rv = client.get("/forbidden")901 assert rv.status_code == 403902 assert b"forbidden" == rv.data903904905def test_error_handling_processing(app, client):906 app.testing = False907908 @app.errorhandler(500)909 def internal_server_error(e):910 return "internal server error", 500911912 @app.route("/")913 def broken_func():

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

line 914why, one step back
914 raise ZeroDivisionError

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 915–1083why, one step back
915
916 @app.after_request917 def after_request(resp):918 resp.mimetype = "text/x-special"919 return resp920921 resp = client.get("/")922 assert resp.mimetype == "text/x-special"923 assert resp.data == b"internal server error"924925926def test_baseexception_error_handling(app, client):927 app.testing = False928929 @app.route("/")930 def broken_func():931 raise KeyboardInterrupt()932933 with pytest.raises(KeyboardInterrupt):934 client.get("/")935936937def test_before_request_and_routing_errors(app, client):938 @app.before_request939 def attach_something():940 flask.g.something = "value"941942 @app.errorhandler(404)943 def return_something(error):944 return flask.g.something, 404945946 rv = client.get("/")947 assert rv.status_code == 404948 assert rv.data == b"value"949950951def test_user_error_handling(app, client):952 class MyException(Exception):953 pass954955 @app.errorhandler(MyException)956 def handle_my_exception(e):957 assert isinstance(e, MyException)958 return "42"959960 @app.route("/")961 def index():962 raise MyException()963964 assert client.get("/").data == b"42"965966967def test_http_error_subclass_handling(app, client):968 class ForbiddenSubclass(Forbidden):969 pass970971 @app.errorhandler(ForbiddenSubclass)972 def handle_forbidden_subclass(e):973 assert isinstance(e, ForbiddenSubclass)974 return "banana"975976 @app.errorhandler(403)977 def handle_403(e):978 assert not isinstance(e, ForbiddenSubclass)979 assert isinstance(e, Forbidden)980 return "apple"981982 @app.route("/1")983 def index1():984 raise ForbiddenSubclass()985986 @app.route("/2")987 def index2():988 flask.abort(403)989990 @app.route("/3")991 def index3():992 raise Forbidden()993994 assert client.get("/1").data == b"banana"995 assert client.get("/2").data == b"apple"996 assert client.get("/3").data == b"apple"997998999def test_errorhandler_precedence(app, client):1000 class E1(Exception):1001 pass10021003 class E2(Exception):1004 pass10051006 class E3(E1, E2):1007 pass10081009 @app.errorhandler(E2)1010 def handle_e2(e):1011 return "E2"10121013 @app.errorhandler(Exception)1014 def handle_exception(e):1015 return "Exception"10161017 @app.route("/E1")1018 def raise_e1():1019 raise E110201021 @app.route("/E3")1022 def raise_e3():1023 raise E310241025 rv = client.get("/E1")1026 assert rv.data == b"Exception"10271028 rv = client.get("/E3")1029 assert rv.data == b"E2"103010311032@pytest.mark.parametrize(1033 ("debug", "trap", "expect_key", "expect_abort"),1034 [(False, None, True, True), (True, None, False, True), (False, True, False, False)],1035)1036def test_trap_bad_request_key_error(app, client, debug, trap, expect_key, expect_abort):1037 app.config["DEBUG"] = debug1038 app.config["TRAP_BAD_REQUEST_ERRORS"] = trap10391040 @app.route("/key")1041 def fail():1042 flask.request.form["missing_key"]10431044 @app.route("/abort")1045 def allow_abort():1046 flask.abort(400)10471048 if expect_key:1049 rv = client.get("/key")1050 assert rv.status_code == 4001051 assert b"missing_key" not in rv.data1052 else:1053 with pytest.raises(KeyError) as exc_info:1054 client.get("/key")10551056 assert exc_info.errisinstance(BadRequest)1057 assert "missing_key" in exc_info.value.get_description()10581059 if expect_abort:1060 rv = client.get("/abort")1061 assert rv.status_code == 4001062 else:1063 with pytest.raises(BadRequest):1064 client.get("/abort")106510661067def test_trapping_of_all_http_exceptions(app, client):1068 app.config["TRAP_HTTP_EXCEPTIONS"] = True10691070 @app.route("/fail")1071 def fail():1072 flask.abort(404)10731074 with pytest.raises(NotFound):1075 client.get("/fail")107610771078def test_error_handler_after_processor_error(app, client):1079 app.testing = False10801081 @app.before_request1082 def before_request():1083 if _trigger == "before":

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

line 1084why, one step back
1084 raise ZeroDivisionError

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 1085–1088why, one step back
1085
1086 @app.after_request1087 def after_request(response):1088 if _trigger == "after":

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

lines 1089–1090why, one step back
1089 raise ZeroDivisionError
1090

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 1091–1491why, one step back
1091 return response
10921093 @app.route("/")1094 def index():1095 return "Foo"10961097 @app.errorhandler(500)1098 def internal_server_error(e):1099 return "Hello Server Error", 50011001101 for _trigger in "before", "after":1102 rv = client.get("/")1103 assert rv.status_code == 5001104 assert rv.data == b"Hello Server Error"110511061107def test_enctype_debug_helper(app, client):1108 from flask.debughelpers import DebugFilesKeyError11091110 app.debug = True11111112 @app.route("/fail", methods=["POST"])1113 def index():1114 return flask.request.files["foo"].filename11151116 with pytest.raises(DebugFilesKeyError) as e:1117 client.post("/fail", data={"foo": "index.txt"})1118 assert "no file contents were transmitted" in str(e.value)1119 assert "This was submitted: 'index.txt'" in str(e.value)112011211122def test_response_types(app, client):1123 @app.route("/text")1124 def from_text():1125 return "Hällo Wörld"11261127 @app.route("/bytes")1128 def from_bytes():1129 return "Hällo Wörld".encode()11301131 @app.route("/full_tuple")1132 def from_full_tuple():1133 return (1134 "Meh",1135 400,1136 {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1137 )11381139 @app.route("/text_headers")1140 def from_text_headers():1141 return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}11421143 @app.route("/text_status")1144 def from_text_status():1145 return "Hi, status!", 40011461147 @app.route("/response_headers")1148 def from_response_headers():1149 return (1150 flask.Response(1151 "Hello world", 404, {"Content-Type": "text/html", "X-Foo": "Baz"}1152 ),1153 {"Content-Type": "text/plain", "X-Foo": "Bar", "X-Bar": "Foo"},1154 )11551156 @app.route("/response_status")1157 def from_response_status():1158 return app.response_class("Hello world", 400), 50011591160 @app.route("/wsgi")1161 def from_wsgi():1162 return NotFound()11631164 @app.route("/dict")1165 def from_dict():1166 return {"foo": "bar"}, 20111671168 @app.route("/list")1169 def from_list():1170 return ["foo", "bar"], 20111711172 assert client.get("/text").data == "Hällo Wörld".encode()1173 assert client.get("/bytes").data == "Hällo Wörld".encode()11741175 rv = client.get("/full_tuple")1176 assert rv.data == b"Meh"1177 assert rv.headers["X-Foo"] == "Testing"1178 assert rv.status_code == 4001179 assert rv.mimetype == "text/plain"11801181 rv = client.get("/text_headers")1182 assert rv.data == b"Hello"1183 assert rv.headers["X-Foo"] == "Test"1184 assert rv.status_code == 2001185 assert rv.mimetype == "text/plain"11861187 rv = client.get("/text_status")1188 assert rv.data == b"Hi, status!"1189 assert rv.status_code == 4001190 assert rv.mimetype == "text/html"11911192 rv = client.get("/response_headers")1193 assert rv.data == b"Hello world"1194 assert rv.content_type == "text/plain"1195 assert rv.headers.getlist("X-Foo") == ["Bar"]1196 assert rv.headers["X-Bar"] == "Foo"1197 assert rv.status_code == 40411981199 rv = client.get("/response_status")1200 assert rv.data == b"Hello world"1201 assert rv.status_code == 50012021203 rv = client.get("/wsgi")1204 assert b"Not Found" in rv.data1205 assert rv.status_code == 40412061207 rv = client.get("/dict")1208 assert rv.json == {"foo": "bar"}1209 assert rv.status_code == 20112101211 rv = client.get("/list")1212 assert rv.json == ["foo", "bar"]1213 assert rv.status_code == 201121412151216def test_response_type_errors():1217 app = flask.Flask(__name__)1218 app.testing = True12191220 @app.route("/none")1221 def from_none():1222 pass12231224 @app.route("/small_tuple")1225 def from_small_tuple():1226 return ("Hello",)12271228 @app.route("/large_tuple")1229 def from_large_tuple():1230 return "Hello", 234, {"X-Foo": "Bar"}, "???"12311232 @app.route("/bad_type")1233 def from_bad_type():1234 return True12351236 @app.route("/bad_wsgi")1237 def from_bad_wsgi():1238 return lambda: None12391240 c = app.test_client()12411242 with pytest.raises(TypeError) as e:1243 c.get("/none")12441245 assert "returned None" in str(e.value)1246 assert "from_none" in str(e.value)12471248 with pytest.raises(TypeError) as e:1249 c.get("/small_tuple")12501251 assert "tuple must have the form" in str(e.value)12521253 with pytest.raises(TypeError):1254 c.get("/large_tuple")12551256 with pytest.raises(TypeError) as e:1257 c.get("/bad_type")12581259 assert "it was a bool" in str(e.value)12601261 with pytest.raises(TypeError):1262 c.get("/bad_wsgi")126312641265def test_make_response(app, req_ctx):1266 rv = flask.make_response()1267 assert rv.status_code == 2001268 assert rv.data == b""1269 assert rv.mimetype == "text/html"12701271 rv = flask.make_response("Awesome")1272 assert rv.status_code == 2001273 assert rv.data == b"Awesome"1274 assert rv.mimetype == "text/html"12751276 rv = flask.make_response("W00t", 404)1277 assert rv.status_code == 4041278 assert rv.data == b"W00t"1279 assert rv.mimetype == "text/html"12801281 rv = flask.make_response(c for c in "Hello")1282 assert rv.status_code == 2001283 assert rv.data == b"Hello"1284 assert rv.mimetype == "text/html"128512861287def test_make_response_with_response_instance(app, req_ctx):1288 rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1289 assert rv.status_code == 4001290 assert rv.data == b'{"msg":"W00t"}\n'1291 assert rv.mimetype == "application/json"12921293 rv = flask.make_response(flask.Response(""), 400)1294 assert rv.status_code == 4001295 assert rv.data == b""1296 assert rv.mimetype == "text/html"12971298 rv = flask.make_response(1299 flask.Response("", headers={"Content-Type": "text/html"}),1300 400,1301 [("X-Foo", "bar")],1302 )1303 assert rv.status_code == 4001304 assert rv.headers["Content-Type"] == "text/html"1305 assert rv.headers["X-Foo"] == "bar"130613071308@pytest.mark.parametrize("compact", [True, False])1309def test_jsonify_no_prettyprint(app, compact):1310 app.json.compact = compact1311 rv = app.json.response({"msg": {"submsg": "W00t"}, "msg2": "foobar"})1312 data = rv.data.strip()1313 assert (b" " not in data) is compact1314 assert (b"\n" not in data) is compact131513161317def test_jsonify_mimetype(app, req_ctx):1318 app.json.mimetype = "application/vnd.api+json"1319 msg = {"msg": {"submsg": "W00t"}}1320 rv = flask.make_response(flask.jsonify(msg), 200)1321 assert rv.mimetype == "application/vnd.api+json"132213231324def test_json_dump_dataclass(app, req_ctx):1325 from dataclasses import make_dataclass13261327 Data = make_dataclass("Data", [("name", str)])1328 value = app.json.dumps(Data("Flask"))1329 value = app.json.loads(value)1330 assert value == {"name": "Flask"}133113321333def test_jsonify_args_and_kwargs_check(app, req_ctx):1334 with pytest.raises(TypeError) as e:1335 flask.jsonify("fake args", kwargs="fake")1336 assert "args or kwargs" in str(e.value)133713381339def test_url_generation(app, req_ctx):1340 @app.route("/hello/<name>", methods=["POST"])1341 def hello():1342 pass13431344 assert flask.url_for("hello", name="test x") == "/hello/test%20x"1345 assert (1346 flask.url_for("hello", name="test x", _external=True)1347 == "http://localhost/hello/test%20x"1348 )134913501351def test_build_error_handler(app):1352 # Test base case, a URL which results in a BuildError.1353 with app.test_request_context():1354 pytest.raises(BuildError, flask.url_for, "spam")13551356 # Verify the error is re-raised if not the current exception.1357 try:1358 with app.test_request_context():1359 flask.url_for("spam")1360 except BuildError as err:1361 error = err1362 try:1363 raise RuntimeError("Test case where BuildError is not current.")1364 except RuntimeError:1365 pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})13661367 # Test a custom handler.1368 def handler(error, endpoint, values):1369 # Just a test.1370 return "/test_handler/"13711372 app.url_build_error_handlers.append(handler)1373 with app.test_request_context():1374 assert flask.url_for("spam") == "/test_handler/"137513761377def test_build_error_handler_reraise(app):1378 # Test a custom handler which reraises the BuildError1379 def handler_raises_build_error(error, endpoint, values):1380 raise error13811382 app.url_build_error_handlers.append(handler_raises_build_error)13831384 with app.test_request_context():1385 pytest.raises(BuildError, flask.url_for, "not.existing")138613871388def test_url_for_passes_special_values_to_build_error_handler(app):1389 @app.url_build_error_handlers.append1390 def handler(error, endpoint, values):1391 assert values == {1392 "_external": False,1393 "_anchor": None,1394 "_method": None,1395 "_scheme": None,1396 }1397 return "handled"13981399 with app.test_request_context():1400 flask.url_for("/")140114021403def test_static_files(app, client):1404 rv = client.get("/static/index.html")1405 assert rv.status_code == 2001406 assert rv.data.strip() == b"<h1>Hello World!</h1>"1407 with app.test_request_context():1408 assert flask.url_for("static", filename="index.html") == "/static/index.html"1409 rv.close()141014111412def test_static_url_path():1413 app = flask.Flask(__name__, static_url_path="/foo")1414 app.testing = True1415 rv = app.test_client().get("/foo/index.html")1416 assert rv.status_code == 2001417 rv.close()14181419 with app.test_request_context():1420 assert flask.url_for("static", filename="index.html") == "/foo/index.html"142114221423def test_static_url_path_with_ending_slash():1424 app = flask.Flask(__name__, static_url_path="/foo/")1425 app.testing = True1426 rv = app.test_client().get("/foo/index.html")1427 assert rv.status_code == 2001428 rv.close()14291430 with app.test_request_context():1431 assert flask.url_for("static", filename="index.html") == "/foo/index.html"143214331434def test_static_url_empty_path(app):1435 app = flask.Flask(__name__, static_folder="", static_url_path="")1436 rv = app.test_client().open("/static/index.html", method="GET")1437 assert rv.status_code == 2001438 rv.close()143914401441def test_static_url_empty_path_default(app):1442 app = flask.Flask(__name__, static_folder="")1443 rv = app.test_client().open("/static/index.html", method="GET")1444 assert rv.status_code == 2001445 rv.close()144614471448def test_static_folder_with_pathlib_path(app):1449 from pathlib import Path14501451 app = flask.Flask(__name__, static_folder=Path("static"))1452 rv = app.test_client().open("/static/index.html", method="GET")1453 assert rv.status_code == 2001454 rv.close()145514561457def test_static_folder_with_ending_slash():1458 app = flask.Flask(__name__, static_folder="static/")14591460 @app.route("/<path:path>")1461 def catch_all(path):1462 return path14631464 rv = app.test_client().get("/catch/all")1465 assert rv.data == b"catch/all"146614671468def test_static_route_with_host_matching():1469 app = flask.Flask(__name__, host_matching=True, static_host="example.com")1470 c = app.test_client()1471 rv = c.get("http://example.com/static/index.html")1472 assert rv.status_code == 2001473 rv.close()1474 with app.test_request_context():1475 rv = flask.url_for("static", filename="index.html", _external=True)1476 assert rv == "http://example.com/static/index.html"1477 # Providing static_host without host_matching=True should error.1478 with pytest.raises(AssertionError):1479 flask.Flask(__name__, static_host="example.com")1480 # Providing host_matching=True with static_folder1481 # but without static_host should error.1482 with pytest.raises(AssertionError):1483 flask.Flask(__name__, host_matching=True)1484 # Providing host_matching=True without static_host1485 # but with static_folder=None should not error.1486 flask.Flask(__name__, host_matching=True, static_folder=None)148714881489def test_request_locals():1490 assert repr(flask.g) == "<LocalProxy unbound>"1491 assert not flask.g

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

lines 1492–1533why, one step back
1492
14931494@pytest.mark.parametrize(1495 ("subdomain_matching", "host_matching", "expect_base", "expect_abc", "expect_xyz"),1496 [1497 (False, False, "default", "default", "default"),1498 (True, False, "default", "abc", "<invalid>"),1499 (False, True, "default", "abc", "default"),1500 ],1501)1502def test_server_name_matching(1503 subdomain_matching: bool,1504 host_matching: bool,1505 expect_base: str,1506 expect_abc: str,1507 expect_xyz: str,1508) -> None:1509 app = flask.Flask(1510 __name__,1511 subdomain_matching=subdomain_matching,1512 host_matching=host_matching,1513 static_host="example.test" if host_matching else None,1514 )1515 app.config["SERVER_NAME"] = "example.test"15161517 @app.route("/", defaults={"name": "default"}, host="<name>")1518 @app.route("/", subdomain="<name>", host="<name>.example.test")1519 def index(name: str) -> str:1520 return name15211522 client = app.test_client()15231524 r = client.get(base_url="http://example.test")1525 assert r.text == expect_base15261527 r = client.get(base_url="http://abc.example.test")1528 assert r.text == expect_abc15291530 with pytest.warns() if subdomain_matching else nullcontext():1531 r = client.get(base_url="http://xyz.other.test")15321533 assert r.text == expect_xyz

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 1534–1586why, one step back
1534
15351536def test_server_name_subdomain():1537 app = flask.Flask(__name__, subdomain_matching=True)1538 client = app.test_client()15391540 @app.route("/")1541 def index():1542 return "default"15431544 @app.route("/", subdomain="foo")1545 def subdomain():1546 return "subdomain"15471548 app.config["SERVER_NAME"] = "dev.local:5000"1549 rv = client.get("/")1550 assert rv.data == b"default"15511552 rv = client.get("/", "http://dev.local:5000")1553 assert rv.data == b"default"15541555 rv = client.get("/", "https://dev.local:5000")1556 assert rv.data == b"default"15571558 app.config["SERVER_NAME"] = "dev.local:443"1559 rv = client.get("/", "https://dev.local")15601561 # Werkzeug 1.0 fixes matching https scheme with 443 port1562 if rv.status_code != 404:1563 assert rv.data == b"default"15641565 app.config["SERVER_NAME"] = "dev.local"1566 rv = client.get("/", "https://dev.local")1567 assert rv.data == b"default"15681569 # suppress Werkzeug 0.15 warning about name mismatch1570 with warnings.catch_warnings():1571 warnings.filterwarnings(1572 "ignore", "Current server name", UserWarning, "flask.app"1573 )1574 rv = client.get("/", "http://foo.localhost")1575 assert rv.status_code == 40415761577 rv = client.get("/", "http://foo.dev.local")1578 assert rv.data == b"subdomain"157915801581@pytest.mark.parametrize("key", ["TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None])1582def test_exception_propagation(app, client, key):1583 app.testing = False15841585 @app.route("/")1586 def index():

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

line 1587why, one step back
1587 raise ZeroDivisionError

Merge pull request #4958 from pallets/dependabot/github_actions/actions/setup-python-4.5.0David Lordbefore adoptionf822891

lines 1588–1944why, one step back
1588
1589 if key is not None:1590 app.config[key] = True15911592 with pytest.raises(ZeroDivisionError):1593 client.get("/")1594 else:1595 assert client.get("/").status_code == 500159615971598@pytest.mark.parametrize("debug", [True, False])1599@pytest.mark.parametrize("use_debugger", [True, False])1600@pytest.mark.parametrize("use_reloader", [True, False])1601@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1602def test_werkzeug_passthrough_errors(1603 monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1604):1605 rv = {}16061607 # Mocks werkzeug.serving.run_simple method1608 def run_simple_mock(*args, **kwargs):1609 rv["passthrough_errors"] = kwargs.get("passthrough_errors")16101611 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1612 app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1613 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)161416151616def test_url_processors(app, client):1617 @app.url_defaults1618 def add_language_code(endpoint, values):1619 if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1620 endpoint, "lang_code"1621 ):1622 values.setdefault("lang_code", flask.g.lang_code)16231624 @app.url_value_preprocessor1625 def pull_lang_code(endpoint, values):1626 flask.g.lang_code = values.pop("lang_code", None)16271628 @app.route("/<lang_code>/")1629 def index():1630 return flask.url_for("about")16311632 @app.route("/<lang_code>/about")1633 def about():1634 return flask.url_for("something_else")16351636 @app.route("/foo")1637 def something_else():1638 return flask.url_for("about", lang_code="en")16391640 assert client.get("/de/").data == b"/de/about"1641 assert client.get("/de/about").data == b"/foo"1642 assert client.get("/foo").data == b"/en/about"164316441645def test_inject_blueprint_url_defaults(app):1646 bp = flask.Blueprint("foo", __name__, template_folder="template")16471648 @bp.url_defaults1649 def bp_defaults(endpoint, values):1650 values["page"] = "login"16511652 @bp.route("/<page>")1653 def view(page):1654 pass16551656 app.register_blueprint(bp)16571658 values = dict()1659 app.inject_url_defaults("foo.view", values)1660 expected = dict(page="login")1661 assert values == expected16621663 with app.test_request_context("/somepage"):1664 url = flask.url_for("foo.view")1665 expected = "/login"1666 assert url == expected166716681669def test_nonascii_pathinfo(app, client):1670 @app.route("/киртест")1671 def index():1672 return "Hello World!"16731674 rv = client.get("/киртест")1675 assert rv.data == b"Hello World!"167616771678def test_no_setup_after_first_request(app, client):1679 app.debug = True16801681 @app.route("/")1682 def index():1683 return "Awesome"16841685 assert client.get("/").data == b"Awesome"16861687 with pytest.raises(AssertionError) as exc_info:1688 app.add_url_rule("/foo", endpoint="late")16891690 assert "setup method 'add_url_rule'" in str(exc_info.value)169116921693def test_routing_redirect_debugging(monkeypatch, app, client):1694 app.config["DEBUG"] = True16951696 @app.route("/user/", methods=["GET", "POST"])1697 def user():1698 return flask.request.form["status"]16991700 # default redirect code preserves form data1701 rv = client.post("/user", data={"status": "success"}, follow_redirects=True)1702 assert rv.data == b"success"17031704 # 301 and 302 raise error1705 monkeypatch.setattr(RequestRedirect, "code", 301)17061707 with client, pytest.raises(AssertionError) as exc_info:1708 client.post("/user", data={"status": "error"}, follow_redirects=True)17091710 assert "canonical URL 'http://localhost/user/'" in str(exc_info.value)171117121713def test_route_decorator_custom_endpoint(app, client):1714 app.debug = True17151716 @app.route("/foo/")1717 def foo():1718 return flask.request.endpoint17191720 @app.route("/bar/", endpoint="bar")1721 def for_bar():1722 return flask.request.endpoint17231724 @app.route("/bar/123", endpoint="123")1725 def for_bar_foo():1726 return flask.request.endpoint17271728 with app.test_request_context():1729 assert flask.url_for("foo") == "/foo/"1730 assert flask.url_for("bar") == "/bar/"1731 assert flask.url_for("123") == "/bar/123"17321733 assert client.get("/foo/").data == b"foo"1734 assert client.get("/bar/").data == b"bar"1735 assert client.get("/bar/123").data == b"123"173617371738def test_get_method_on_g(app_ctx):1739 assert flask.g.get("x") is None1740 assert flask.g.get("x", 11) == 111741 flask.g.x = 421742 assert flask.g.get("x") == 421743 assert flask.g.x == 42174417451746def test_g_iteration_protocol(app_ctx):1747 flask.g.foo = 231748 flask.g.bar = 421749 assert "foo" in flask.g1750 assert "foos" not in flask.g1751 assert sorted(flask.g) == ["bar", "foo"]175217531754def test_subdomain_basic_support():1755 app = flask.Flask(__name__, subdomain_matching=True)1756 app.config["SERVER_NAME"] = "localhost.localdomain"1757 client = app.test_client()17581759 @app.route("/")1760 def normal_index():1761 return "normal index"17621763 @app.route("/", subdomain="test")1764 def test_index():1765 return "test index"17661767 rv = client.get("/", "http://localhost.localdomain/")1768 assert rv.data == b"normal index"17691770 rv = client.get("/", "http://test.localhost.localdomain/")1771 assert rv.data == b"test index"177217731774def test_subdomain_matching():1775 app = flask.Flask(__name__, subdomain_matching=True)1776 client = app.test_client()1777 app.config["SERVER_NAME"] = "localhost.localdomain"17781779 @app.route("/", subdomain="<user>")1780 def index(user):1781 return f"index for {user}"17821783 rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1784 assert rv.data == b"index for mitsuhiko"178517861787def test_subdomain_matching_with_ports():1788 app = flask.Flask(__name__, subdomain_matching=True)1789 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1790 client = app.test_client()17911792 @app.route("/", subdomain="<user>")1793 def index(user):1794 return f"index for {user}"17951796 rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1797 assert rv.data == b"index for mitsuhiko"179817991800@pytest.mark.parametrize("matching", (False, True))1801def test_subdomain_matching_other_name(matching):1802 app = flask.Flask(__name__, subdomain_matching=matching)1803 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1804 client = app.test_client()18051806 @app.route("/")1807 def index():1808 return "", 20418091810 # suppress Werkzeug 0.15 warning about name mismatch1811 with warnings.catch_warnings():1812 warnings.filterwarnings(1813 "ignore", "Current server name", UserWarning, "flask.app"1814 )1815 # ip address can't match name1816 rv = client.get("/", "http://127.0.0.1:3000/")1817 assert rv.status_code == 404 if matching else 20418181819 # allow all subdomains if matching is disabled1820 rv = client.get("/", "http://www.localhost.localdomain:3000/")1821 assert rv.status_code == 404 if matching else 204182218231824def test_multi_route_rules(app, client):1825 @app.route("/")1826 @app.route("/<test>/")1827 def index(test="a"):1828 return test18291830 rv = client.open("/")1831 assert rv.data == b"a"1832 rv = client.open("/b/")1833 assert rv.data == b"b"183418351836def test_multi_route_class_views(app, client):1837 class View:1838 def __init__(self, app):1839 app.add_url_rule("/", "index", self.index)1840 app.add_url_rule("/<test>/", "index", self.index)18411842 def index(self, test="a"):1843 return test18441845 _ = View(app)1846 rv = client.open("/")1847 assert rv.data == b"a"1848 rv = client.open("/b/")1849 assert rv.data == b"b"185018511852def test_run_defaults(monkeypatch, app):1853 rv = {}18541855 # Mocks werkzeug.serving.run_simple method1856 def run_simple_mock(*args, **kwargs):1857 rv["result"] = "running..."18581859 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1860 app.run()1861 assert rv["result"] == "running..."186218631864def test_run_server_port(monkeypatch, app):1865 rv = {}18661867 # Mocks werkzeug.serving.run_simple method1868 def run_simple_mock(hostname, port, application, *args, **kwargs):1869 rv["result"] = f"running on {hostname}:{port} ..."18701871 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1872 hostname, port = "localhost", 80001873 app.run(hostname, port, debug=True)1874 assert rv["result"] == f"running on {hostname}:{port} ..."187518761877@pytest.mark.parametrize(1878 "host,port,server_name,expect_host,expect_port",1879 (1880 (None, None, "pocoo.org:8080", "pocoo.org", 8080),1881 ("localhost", None, "pocoo.org:8080", "localhost", 8080),1882 (None, 80, "pocoo.org:8080", "pocoo.org", 80),1883 ("localhost", 80, "pocoo.org:8080", "localhost", 80),1884 ("localhost", 0, "localhost:8080", "localhost", 0),1885 (None, None, "localhost:8080", "localhost", 8080),1886 (None, None, "localhost:0", "localhost", 0),1887 ),1888)1889def test_run_from_config(1890 monkeypatch, host, port, server_name, expect_host, expect_port, app1891):1892 def run_simple_mock(hostname, port, *args, **kwargs):1893 assert hostname == expect_host1894 assert port == expect_port18951896 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1897 app.config["SERVER_NAME"] = server_name1898 app.run(host, port)189919001901def test_max_cookie_size(app, client, recwarn):1902 app.config["MAX_COOKIE_SIZE"] = 10019031904 # outside app context, default to Werkzeug static value,1905 # which is also the default config1906 response = flask.Response()1907 default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1908 assert response.max_cookie_size == default19091910 # inside app context, use app config1911 with app.app_context():1912 assert flask.Response().max_cookie_size == 10019131914 @app.route("/")1915 def index():1916 r = flask.Response("", status=204)1917 r.set_cookie("foo", "bar" * 100)1918 return r19191920 client.get("/")1921 assert len(recwarn) == 11922 w = recwarn.pop()1923 assert "cookie is too large" in str(w.message)19241925 app.config["MAX_COOKIE_SIZE"] = 019261927 client.get("/")1928 assert len(recwarn) == 0192919301931@require_cpython_gc1932def test_app_freed_on_zero_refcount():1933 # A Flask instance should not create a reference cycle that prevents CPython1934 # from freeing it when all external references to it are released (see #3761).1935 gc.disable()1936 try:1937 app = flask.Flask(__name__)1938 assert app.view_functions["static"]1939 weak = weakref.ref(app)1940 assert weak() is not None1941 del app1942 assert weak() is None1943 finally:1944 gc.enable()