test_basic.py
This file
Path
tests/test_basic.py
1,970 lines · 52.9 KiB · Python
Last changed by
all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
History of this fileTake it
The walk stopped after 200 commits: lines older than ed5b240 point at it.
Merge branch '2.2.x'David Lordbefore adoptioned5b240
line 1why, one step back1import gcupdate domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2
line 2why, one step back2import importlib.metadataMerge branch '2.2.x'David Lordbefore adoptioned5b240
line 3why, one step back3import reenable secret key rotation (#5632)David Lordbefore adoptiona20bcff
line 4why, one step back4import typing as tMerge branch '2.2.x'David Lordbefore adoptioned5b240
lines 5–6why, one step back5import uuid6import weakrefsetting `SERVER_NAME` does not restrict routing for both `subdomain_matching` and `host_matching` (#5634)David Lordbefore adoption10bdf61
line 7why, one step back7from contextlib import nullcontextMerge branch '2.2.x'David Lordbefore adoptioned5b240
lines 8–13why, one step back8from datetime import datetime9from datetime import timezone10from platform import python_implementation1112import pytest13import werkzeug.servingMerge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689
line 14why, one step back14from markupsafe import MarkupMerge branch '2.2.x'David Lordbefore adoptioned5b240
lines 15–22why, one step back15from werkzeug.exceptions import BadRequest16from werkzeug.exceptions import Forbidden17from werkzeug.exceptions import NotFound18from werkzeug.http import parse_date19from werkzeug.routing import BuildError20from werkzeug.routing import RequestRedirect2122import flaskMerge branch 'stable'David Lordbefore adoptiondaca74d
line 23why, one step back23from flask.globals import app_ctxfix provide_automatic_options override (#5917)David Lordbefore adoption12e95c9
line 24why, one step back24from flask.testing import FlaskClientMerge branch '2.2.x'David Lordbefore adoptioned5b240
lines 25–71why, one step back2526require_cpython_gc = pytest.mark.skipif(27 python_implementation() != "CPython",28 reason="Requires CPython GC behavior",29)303132def test_options_work(app, client):33 @app.route("/", methods=["GET", "POST"])34 def index():35 return "Hello World"3637 rv = client.open("/", method="OPTIONS")38 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]39 assert rv.data == b""404142def test_options_on_multiple_rules(app, client):43 @app.route("/", methods=["GET", "POST"])44 def index():45 return "Hello World"4647 @app.route("/", methods=["PUT"])48 def index_put():49 return "Aha!"5051 rv = client.open("/", method="OPTIONS")52 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST", "PUT"]535455@pytest.mark.parametrize("method", ["get", "post", "put", "delete", "patch"])56def test_method_route(app, client, method):57 method_route = getattr(app, method)58 client_method = getattr(client, method)5960 @method_route("/")61 def hello():62 return "Hello"6364 assert client_method("/").data == b"Hello"656667def test_method_route_no_methods(app):68 with pytest.raises(TypeError):69 app.get("/", methods=["GET", "POST"])7071fix provide_automatic_options override (#5917)David Lordbefore adoption12e95c9
lines 72–75why, one step back72def test_provide_automatic_options_attr_disable(73 app: flask.Flask, client: FlaskClient74) -> None:75 """Automatic options can be disabled by the view func attribute."""Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 76–80why, one step back7677 def index():78 return "Hello World!"7980 index.provide_automatic_options = Falsefix provide_automatic_options override (#5917)David Lordbefore adoption12e95c9
lines 81–82why, one step back81 app.add_url_rule("/", view_func=index)82 rv = client.options()Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 83–85why, one step back83 assert rv.status_code == 4058485fix provide_automatic_options override (#5917)David Lordbefore adoption12e95c9
lines 86–94why, one step back86def test_provide_automatic_options_attr_enable(87 app: flask.Flask, client: FlaskClient88) -> None:89 """When default automatic options is disabled in config, it can still be90 enabled by the view function attribute.91 """92 app.config["PROVIDE_AUTOMATIC_OPTIONS"] = False9394 def index():Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 95–96why, one step back95 return "Hello World!"96fix provide_automatic_options override (#5917)David Lordbefore adoption12e95c9
lines 97–100why, one step back97 index.provide_automatic_options = True98 app.add_url_rule("/", view_func=index)99 rv = client.options()100 assert rv.allow == {"GET", "HEAD", "OPTIONS"}Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 101–102why, one step back101102fix provide_automatic_options override (#5917)David Lordbefore adoption12e95c9
lines 103–108why, one step back103def test_provide_automatic_options_arg_disable(104 app: flask.Flask, client: FlaskClient105) -> None:106 """Automatic options can be disabled by the route argument."""107108 @app.get("/", provide_automatic_options=False)Merge branch '2.2.x'David Lordbefore adoptioned5b240
line 109why, one step back109 def index():fix provide_automatic_options override (#5917)David Lordbefore adoption12e95c9
line 110why, one step back110 return "Hello World!"Merge branch '2.2.x'David Lordbefore adoptioned5b240
line 111why, one step back111fix provide_automatic_options override (#5917)David Lordbefore adoption12e95c9
line 112why, one step back112 rv = client.options()Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 113–115why, one step back113 assert rv.status_code == 405114115fix provide_automatic_options override (#5917)David Lordbefore adoption12e95c9
lines 116–119why, one step back116def test_provide_automatic_options_method_disable(117 app: flask.Flask, client: FlaskClient118) -> None:119 """Automatic options is ignored if the route handles options."""Merge branch '2.2.x'David Lordbefore adoptioned5b240
line 120why, one step back120fix provide_automatic_options override (#5917)David Lordbefore adoption12e95c9
lines 121–123why, one step back121 @app.route("/", methods=["OPTIONS"])122 def index():123 return "", {"X-Test": "test"}Merge branch '2.2.x'David Lordbefore adoptioned5b240
line 124why, one step back124fix provide_automatic_options override (#5917)David Lordbefore adoption12e95c9
lines 125–126why, one step back125 rv = client.options()126 assert rv.headers["X-Test"] == "test"Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 127–193why, one step back127128129def 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 back194 from werkzeug.routing import Rule195 from werkzeug.routing import SubmountMerge branch '2.2.x'David Lordbefore adoptioned5b240
lines 196–214why, one step back196197 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 back215 from werkzeug.routing import Rule216 from werkzeug.routing import SubmountMerge branch '2.2.x'David Lordbefore adoptioned5b240
lines 217–233why, one step back217218 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"232233Merge branch 'stable'David Lordbefore adoptiondaca74d
lines 234–236why, one step back234def test_session_accessed(app: flask.Flask, client: FlaskClient) -> None:235 @app.post("/")236 def do_set():Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 237–239why, one step back237 flask.session["value"] = flask.request.form["value"]238 return "value set"239Merge branch 'stable'David Lordbefore adoptiondaca74d
lines 240–242why, one step back240 @app.get("/")241 def do_get():242 return flask.session.get("value", "None")Merge branch '2.2.x'David Lordbefore adoptioned5b240
line 243why, one step back243Merge branch 'stable'David Lordbefore adoptiondaca74d
lines 244–273why, one step back244 @app.get("/nothing")245 def do_nothing() -> str:246 return ""247248 with client:249 rv = client.get("/nothing")250 assert "cookie" not in rv.vary251 assert not app_ctx._session.accessed252 assert not app_ctx._session.modified253254 with client:255 rv = client.post(data={"value": "42"})256 assert rv.text == "value set"257 assert "cookie" in rv.vary258 assert app_ctx._session.accessed259 assert app_ctx._session.modified260261 with client:262 rv = client.get()263 assert rv.text == "42"264 assert "cookie" in rv.vary265 assert app_ctx._session.accessed266 assert not app_ctx._session.modified267268 with client:269 rv = client.get("/nothing")270 assert rv.text == ""271 assert "cookie" not in rv.vary272 assert not app_ctx._session.accessed273 assert not app_ctx._session.modifiedMerge branch '2.2.x'David Lordbefore adoptioned5b240
lines 274–275why, one step back274275Merge pull request #5054 from pallets/session-domainDavid Lordbefore adoptionc9a5660
lines 276–277why, one step back276def test_session_path(app, client):277 app.config.update(APPLICATION_ROOT="/foo")Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 278–316why, one step back278279 @app.route("/")280 def index():281 flask.session["testing"] = 42282 return "Hello World"283284 rv = client.get("/", "http://example.com:8080/foo")285 assert "path=/foo" in rv.headers["set-cookie"].lower()286287288def test_session_using_application_root(app, client):289 class PrefixPathMiddleware:290 def __init__(self, app, prefix):291 self.app = app292 self.prefix = prefix293294 def __call__(self, environ, start_response):295 environ["SCRIPT_NAME"] = self.prefix296 return self.app(environ, start_response)297298 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, "/bar")299 app.config.update(APPLICATION_ROOT="/bar")300301 @app.route("/")302 def index():303 flask.session["testing"] = 42304 return "Hello World"305306 rv = client.get("/", "http://example.com:8080/")307 assert "path=/bar" in rv.headers["set-cookie"].lower()308309310def test_session_using_session_settings(app, client):311 app.config.update(312 SERVER_NAME="www.example.com:8080",313 APPLICATION_ROOT="/test",314 SESSION_COOKIE_DOMAIN=".example.com",315 SESSION_COOKIE_HTTPONLY=False,316 SESSION_COOKIE_SECURE=True,add SESSION_COOKIE_PARTITIONED config (#5499)David Lordbefore adoptionce08bc7
line 317why, one step back317 SESSION_COOKIE_PARTITIONED=True,Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 318–333why, one step back318 SESSION_COOKIE_SAMESITE="Lax",319 SESSION_COOKIE_PATH="/",320 )321322 @app.route("/")323 def index():324 flask.session["testing"] = 42325 return "Hello World"326327 @app.route("/clear")328 def clear():329 flask.session.pop("testing", None)330 return "Goodbye World"331332 rv = client.get("/", "http://www.example.com:8080/test/")333 cookie = rv.headers["set-cookie"].lower()Merge branch '2.2.x'David Lordbefore adoptionfa0ceb6
lines 334–335why, one step back334 # or condition for Werkzeug < 2.3335 assert "domain=example.com" in cookie or "domain=.example.com" in cookieMerge branch '2.2.x'David Lordbefore adoptioned5b240
lines 336–339why, one step back336 assert "path=/" in cookie337 assert "secure" in cookie338 assert "httponly" not in cookie339 assert "samesite" in cookieadd SESSION_COOKIE_PARTITIONED config (#5499)David Lordbefore adoptionce08bc7
line 340why, one step back340 assert "partitioned" in cookieMerge branch '2.2.x'David Lordbefore adoptioned5b240
lines 341–344why, one step back341342 rv = client.get("/clear", "http://www.example.com:8080/test/")343 cookie = rv.headers["set-cookie"].lower()344 assert "session=;" in cookieMerge branch '2.2.x'David Lordbefore adoptionfa0ceb6
lines 345–346why, one step back345 # or condition for Werkzeug < 2.3346 assert "domain=example.com" in cookie or "domain=.example.com" in cookieMerge branch '2.2.x'David Lordbefore adoptioned5b240
lines 347–349why, one step back347 assert "path=/" in cookie348 assert "secure" in cookie349 assert "samesite" in cookieadd SESSION_COOKIE_PARTITIONED config (#5499)David Lordbefore adoptionce08bc7
line 350why, one step back350 assert "partitioned" in cookieMerge branch '2.2.x'David Lordbefore adoptioned5b240
lines 351–390why, one step back351352353def test_session_using_samesite_attribute(app, client):354 @app.route("/")355 def index():356 flask.session["testing"] = 42357 return "Hello World"358359 app.config.update(SESSION_COOKIE_SAMESITE="invalid")360361 with pytest.raises(ValueError):362 client.get("/")363364 app.config.update(SESSION_COOKIE_SAMESITE=None)365 rv = client.get("/")366 cookie = rv.headers["set-cookie"].lower()367 assert "samesite" not in cookie368369 app.config.update(SESSION_COOKIE_SAMESITE="Strict")370 rv = client.get("/")371 cookie = rv.headers["set-cookie"].lower()372 assert "samesite=strict" in cookie373374 app.config.update(SESSION_COOKIE_SAMESITE="Lax")375 rv = client.get("/")376 cookie = rv.headers["set-cookie"].lower()377 assert "samesite=lax" in cookie378379380def test_missing_session(app):381 app.secret_key = None382383 def expect_exception(f, *args, **kwargs):384 e = pytest.raises(RuntimeError, f, *args, **kwargs)385 assert e.value.args and "session is unavailable" in e.value.args[0]386387 with app.test_request_context():388 assert flask.session.get("missing_key") is None389 expect_exception(flask.session.__setitem__, "foo", 42)390 expect_exception(flask.session.pop, "foo")enable secret key rotation (#5632)David Lordbefore adoptiona20bcff
lines 391–402why, one step back391392393def test_session_secret_key_fallbacks(app, client) -> None:394 @app.post("/")395 def set_session() -> str:396 flask.session["a"] = 1397 return ""398399 @app.get("/")400 def get_session() -> dict[str, t.Any]:401 return dict(flask.session)402Merge branch 'stable'David Lordbefore adoptione7e5380
lines 403–407why, one step back403 # Set session with initial secret key, and two valid expiring keys404 app.secret_key, app.config["SECRET_KEY_FALLBACKS"] = (405 "0 key",406 ["-1 key", "-2 key"],407 )enable secret key rotation (#5632)David Lordbefore adoptiona20bcff
lines 408–410why, one step back408 client.post()409 assert client.get().json == {"a": 1}410 # Change secret key, session can't be loaded and appears emptyMerge branch 'stable'David Lordbefore adoptione7e5380
line 411why, one step back411 app.secret_key = "? key"enable secret key rotation (#5632)David Lordbefore adoptiona20bcff
line 412why, one step back412 assert client.get().json == {}Merge branch 'stable'David Lordbefore adoptione7e5380
lines 413–417why, one step back413 # Rotate the valid keys, session can be loaded414 app.secret_key, app.config["SECRET_KEY_FALLBACKS"] = (415 "+1 key",416 ["0 key", "-1 key"],417 )enable secret key rotation (#5632)David Lordbefore adoptiona20bcff
line 418why, one step back418 assert client.get().json == {"a": 1}Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 419–474why, one step back419420421def test_session_expiration(app, client):422 permanent = True423424 @app.route("/")425 def index():426 flask.session["test"] = 42427 flask.session.permanent = permanent428 return ""429430 @app.route("/test")431 def test():432 return str(flask.session.permanent)433434 rv = client.get("/")435 assert "set-cookie" in rv.headers436 match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])437 expires = parse_date(match.group())438 expected = datetime.now(timezone.utc) + app.permanent_session_lifetime439 assert expires.year == expected.year440 assert expires.month == expected.month441 assert expires.day == expected.day442443 rv = client.get("/test")444 assert rv.data == b"True"445446 permanent = False447 rv = client.get("/")448 assert "set-cookie" in rv.headers449 match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])450 assert match is None451452453def test_session_stored_last(app, client):454 @app.after_request455 def modify_session(response):456 flask.session["foo"] = 42457 return response458459 @app.route("/")460 def dump_session_contents():461 return repr(flask.session.get("foo"))462463 assert client.get("/").data == b"None"464 assert client.get("/").data == b"42"465466467def test_session_special_types(app, client):468 now = datetime.now(timezone.utc).replace(microsecond=0)469 the_uuid = uuid.uuid4()470471 @app.route("/")472 def dump_session_contents():473 flask.session["t"] = (1, 2, 3)474 flask.session["b"] = b"\xff"Merge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689
line 475why, one step back475 flask.session["m"] = Markup("<html>")Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 476–486why, one step back476 flask.session["u"] = the_uuid477 flask.session["d"] = now478 flask.session["t_tag"] = {" t": "not-a-tuple"}479 flask.session["di_t_tag"] = {" t__": "not-a-tuple"}480 flask.session["di_tag"] = {" di": "not-a-dict"}481 return "", 204482483 with client:484 client.get("/")485 s = flask.session486 assert s["t"] == (1, 2, 3)use ruff linter and formatter (#5331)David Lordbefore adoption9a12f34
line 487why, one step back487 assert type(s["b"]) is bytes # noqa: E721Merge branch '2.2.x'David Lordbefore adoptioned5b240
line 488why, one step back488 assert s["b"] == b"\xff"use ruff linter and formatter (#5331)David Lordbefore adoption9a12f34
line 489why, one step back489 assert type(s["m"]) is Markup # noqa: E721Merge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689
line 490why, one step back490 assert s["m"] == Markup("<html>")Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 491–556why, one step back491 assert s["u"] == the_uuid492 assert s["d"] == now493 assert s["t_tag"] == {" t": "not-a-tuple"}494 assert s["di_t_tag"] == {" t__": "not-a-tuple"}495 assert s["di_tag"] == {" di": "not-a-dict"}496497498def test_session_cookie_setting(app):499 is_permanent = True500501 @app.route("/bump")502 def bump():503 rv = flask.session["foo"] = flask.session.get("foo", 0) + 1504 flask.session.permanent = is_permanent505 return str(rv)506507 @app.route("/read")508 def read():509 return str(flask.session.get("foo", 0))510511 def run_test(expect_header):512 with app.test_client() as c:513 assert c.get("/bump").data == b"1"514 assert c.get("/bump").data == b"2"515 assert c.get("/bump").data == b"3"516517 rv = c.get("/read")518 set_cookie = rv.headers.get("set-cookie")519 assert (set_cookie is not None) == expect_header520 assert rv.data == b"3"521522 is_permanent = True523 app.config["SESSION_REFRESH_EACH_REQUEST"] = True524 run_test(expect_header=True)525526 is_permanent = True527 app.config["SESSION_REFRESH_EACH_REQUEST"] = False528 run_test(expect_header=False)529530 is_permanent = False531 app.config["SESSION_REFRESH_EACH_REQUEST"] = True532 run_test(expect_header=False)533534 is_permanent = False535 app.config["SESSION_REFRESH_EACH_REQUEST"] = False536 run_test(expect_header=False)537538539def test_session_vary_cookie(app, client):540 @app.route("/set")541 def set_session():542 flask.session["test"] = "test"543 return ""544545 @app.route("/get")546 def get():547 return flask.session.get("test")548549 @app.route("/getitem")550 def getitem():551 return flask.session["test"]552553 @app.route("/setdefault")554 def setdefault():555 return flask.session.setdefault("test", "default")556Merge pull request from GHSA-m2qf-hxjv-5gpqDavid Lordbefore adoption70f906c
lines 557–561why, one step back557 @app.route("/clear")558 def clear():559 flask.session.clear()560 return ""561Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 562–593why, one step back562 @app.route("/vary-cookie-header-set")563 def vary_cookie_header_set():564 response = flask.Response()565 response.vary.add("Cookie")566 flask.session["test"] = "test"567 return response568569 @app.route("/vary-header-set")570 def vary_header_set():571 response = flask.Response()572 response.vary.update(("Accept-Encoding", "Accept-Language"))573 flask.session["test"] = "test"574 return response575576 @app.route("/no-vary-header")577 def no_vary_header():578 return ""579580 def expect(path, header_value="Cookie"):581 rv = client.get(path)582583 if header_value:584 # The 'Vary' key should exist in the headers only once.585 assert len(rv.headers.get_all("Vary")) == 1586 assert rv.headers["Vary"] == header_value587 else:588 assert "Vary" not in rv.headers589590 expect("/set")591 expect("/get")592 expect("/getitem")593 expect("/setdefault")Merge pull request from GHSA-m2qf-hxjv-5gpqDavid Lordbefore adoption70f906c
line 594why, one step back594 expect("/clear")Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 595–597why, one step back595 expect("/vary-cookie-header-set")596 expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")597 expect("/no-vary-header", None)Merge pull request from GHSA-m2qf-hxjv-5gpqDavid Lordbefore adoption70f906c
lines 598–614why, one step back598599600def test_session_refresh_vary(app, client):601 @app.get("/login")602 def login():603 flask.session["user_id"] = 1604 flask.session.permanent = True605 return ""606607 @app.get("/ignored")608 def ignored():609 return ""610611 rv = client.get("/login")612 assert rv.headers["Vary"] == "Cookie"613 rv = client.get("/ignored")614 assert rv.headers["Vary"] == "Cookie"Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 615–636why, one step back615616617def test_flashes(app, req_ctx):618 assert not flask.session.modified619 flask.flash("Zap")620 flask.session.modified = False621 flask.flash("Zip")622 assert flask.session.modified623 assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]624625626def test_extended_flashing(app):627 # Be sure app.testing=True below, else tests can fail silently.628 #629 # Specifically, if app.testing is not set to True, the AssertionErrors630 # in the view functions will cause a 500 response to the test client631 # instead of propagating exceptions.632633 @app.route("/")634 def index():635 flask.flash("Hello World")636 flask.flash("Hello World", "error")Merge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689
line 637why, one step back637 flask.flash(Markup("<em>Testing</em>"), "warning")Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 638–645why, one step back638 return ""639640 @app.route("/test/")641 def test():642 messages = flask.get_flashed_messages()643 assert list(messages) == [644 "Hello World",645 "Hello World",Merge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689
line 646why, one step back646 Markup("<em>Testing</em>"),Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 647–656why, one step back647 ]648 return ""649650 @app.route("/test_with_categories/")651 def test_with_categories():652 messages = flask.get_flashed_messages(with_categories=True)653 assert len(messages) == 3654 assert list(messages) == [655 ("message", "Hello World"),656 ("error", "Hello World"),Merge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689
line 657why, one step back657 ("warning", Markup("<em>Testing</em>")),Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 658–675why, one step back658 ]659 return ""660661 @app.route("/test_filter/")662 def test_filter():663 messages = flask.get_flashed_messages(664 category_filter=["message"], with_categories=True665 )666 assert list(messages) == [("message", "Hello World")]667 return ""668669 @app.route("/test_filters/")670 def test_filters():671 messages = flask.get_flashed_messages(672 category_filter=["message", "warning"], with_categories=True673 )674 assert list(messages) == [675 ("message", "Hello World"),Merge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689
line 676why, one step back676 ("warning", Markup("<em>Testing</em>")),Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 677–684why, one step back677 ]678 return ""679680 @app.route("/test_filters_without_returning_categories/")681 def test_filters2():682 messages = flask.get_flashed_messages(category_filter=["message", "warning"])683 assert len(messages) == 2684 assert messages[0] == "Hello World"Merge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689
line 685why, one step back685 assert messages[1] == Markup("<em>Testing</em>")Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 686–815why, one step back686 return ""687688 # Create new test client on each test to clean flashed messages.689690 client = app.test_client()691 client.get("/")692 client.get("/test_with_categories/")693694 client = app.test_client()695 client.get("/")696 client.get("/test_filter/")697698 client = app.test_client()699 client.get("/")700 client.get("/test_filters/")701702 client = app.test_client()703 client.get("/")704 client.get("/test_filters_without_returning_categories/")705706707def test_request_processing(app, client):708 evts = []709710 @app.before_request711 def before_request():712 evts.append("before")713714 @app.after_request715 def after_request(response):716 response.data += b"|after"717 evts.append("after")718 return response719720 @app.route("/")721 def index():722 assert "before" in evts723 assert "after" not in evts724 return "request"725726 assert "after" not in evts727 rv = client.get("/").data728 assert "after" in evts729 assert rv == b"request|after"730731732def test_request_preprocessing_early_return(app, client):733 evts = []734735 @app.before_request736 def before_request1():737 evts.append(1)738739 @app.before_request740 def before_request2():741 evts.append(2)742 return "hello"743744 @app.before_request745 def before_request3():746 evts.append(3)747 return "bye"748749 @app.route("/")750 def index():751 evts.append("index")752 return "damnit"753754 rv = client.get("/").data.strip()755 assert rv == b"hello"756 assert evts == [1, 2]757758759def test_after_request_processing(app, client):760 @app.route("/")761 def index():762 @flask.after_this_request763 def foo(response):764 response.headers["X-Foo"] = "a header"765 return response766767 return "Test"768769 resp = client.get("/")770 assert resp.status_code == 200771 assert resp.headers["X-Foo"] == "a header"772773774def test_teardown_request_handler(app, client):775 called = []776777 @app.teardown_request778 def teardown_request(exc):779 called.append(True)780 return "Ignored"781782 @app.route("/")783 def root():784 return "Response"785786 rv = client.get("/")787 assert rv.status_code == 200788 assert b"Response" in rv.data789 assert len(called) == 1790791792def test_teardown_request_handler_debug_mode(app, client):793 called = []794795 @app.teardown_request796 def teardown_request(exc):797 called.append(True)798 return "Ignored"799800 @app.route("/")801 def root():802 return "Response"803804 rv = client.get("/")805 assert rv.status_code == 200806 assert b"Response" in rv.data807 assert len(called) == 1808809810def test_teardown_request_handler_error(app, client):811 called = []812 app.testing = False813814 @app.teardown_request815 def teardown_request1(exc):fix flake8 bugbear findingsDavid Lordbefore adoptionc49ce2e
line 816why, one step back816 assert type(exc) is ZeroDivisionErrorMerge branch '2.2.x'David Lordbefore adoptioned5b240
lines 817–827why, one step back817 called.append(True)818 # This raises a new error and blows away sys.exc_info(), so we can819 # test that all teardown_requests get passed the same original820 # exception.821 try:822 raise TypeError()823 except Exception:824 pass825826 @app.teardown_request827 def teardown_request2(exc):fix flake8 bugbear findingsDavid Lordbefore adoptionc49ce2e
line 828why, one step back828 assert type(exc) is ZeroDivisionErrorMerge branch '2.2.x'David Lordbefore adoptioned5b240
lines 829–839why, one step back829 called.append(True)830 # This raises a new error and blows away sys.exc_info(), so we can831 # test that all teardown_requests get passed the same original832 # exception.833 try:834 raise TypeError()835 except Exception:836 pass837838 @app.route("/")839 def fails():use ruff linter and formatter (#5331)David Lordbefore adoption9a12f34
line 840why, one step back840 raise ZeroDivisionErrorMerge branch '2.2.x'David Lordbefore adoptioned5b240
lines 841–906why, one step back841842 rv = client.get("/")843 assert rv.status_code == 500844 assert b"Internal Server Error" in rv.data845 assert len(called) == 2846847848def test_before_after_request_order(app, client):849 called = []850851 @app.before_request852 def before1():853 called.append(1)854855 @app.before_request856 def before2():857 called.append(2)858859 @app.after_request860 def after1(response):861 called.append(4)862 return response863864 @app.after_request865 def after2(response):866 called.append(3)867 return response868869 @app.teardown_request870 def finish1(exc):871 called.append(6)872873 @app.teardown_request874 def finish2(exc):875 called.append(5)876877 @app.route("/")878 def index():879 return "42"880881 rv = client.get("/")882 assert rv.data == b"42"883 assert called == [1, 2, 3, 4, 5, 6]884885886def test_error_handling(app, client):887 app.testing = False888889 @app.errorhandler(404)890 def not_found(e):891 return "not found", 404892893 @app.errorhandler(500)894 def internal_server_error(e):895 return "internal server error", 500896897 @app.errorhandler(Forbidden)898 def forbidden(e):899 return "forbidden", 403900901 @app.route("/")902 def index():903 flask.abort(404)904905 @app.route("/error")906 def error():use ruff linter and formatter (#5331)David Lordbefore adoption9a12f34
line 907why, one step back907 raise ZeroDivisionErrorMerge branch '2.2.x'David Lordbefore adoptioned5b240
lines 908–932why, one step back908909 @app.route("/forbidden")910 def error2():911 flask.abort(403)912913 rv = client.get("/")914 assert rv.status_code == 404915 assert rv.data == b"not found"916 rv = client.get("/error")917 assert rv.status_code == 500918 assert b"internal server error" == rv.data919 rv = client.get("/forbidden")920 assert rv.status_code == 403921 assert b"forbidden" == rv.data922923924def test_error_handling_processing(app, client):925 app.testing = False926927 @app.errorhandler(500)928 def internal_server_error(e):929 return "internal server error", 500930931 @app.route("/")932 def broken_func():use ruff linter and formatter (#5331)David Lordbefore adoption9a12f34
line 933why, one step back933 raise ZeroDivisionErrorMerge branch '2.2.x'David Lordbefore adoptioned5b240
lines 934–1102why, one step back934935 @app.after_request936 def after_request(resp):937 resp.mimetype = "text/x-special"938 return resp939940 resp = client.get("/")941 assert resp.mimetype == "text/x-special"942 assert resp.data == b"internal server error"943944945def test_baseexception_error_handling(app, client):946 app.testing = False947948 @app.route("/")949 def broken_func():950 raise KeyboardInterrupt()951952 with pytest.raises(KeyboardInterrupt):953 client.get("/")954955956def test_before_request_and_routing_errors(app, client):957 @app.before_request958 def attach_something():959 flask.g.something = "value"960961 @app.errorhandler(404)962 def return_something(error):963 return flask.g.something, 404964965 rv = client.get("/")966 assert rv.status_code == 404967 assert rv.data == b"value"968969970def test_user_error_handling(app, client):971 class MyException(Exception):972 pass973974 @app.errorhandler(MyException)975 def handle_my_exception(e):976 assert isinstance(e, MyException)977 return "42"978979 @app.route("/")980 def index():981 raise MyException()982983 assert client.get("/").data == b"42"984985986def test_http_error_subclass_handling(app, client):987 class ForbiddenSubclass(Forbidden):988 pass989990 @app.errorhandler(ForbiddenSubclass)991 def handle_forbidden_subclass(e):992 assert isinstance(e, ForbiddenSubclass)993 return "banana"994995 @app.errorhandler(403)996 def handle_403(e):997 assert not isinstance(e, ForbiddenSubclass)998 assert isinstance(e, Forbidden)999 return "apple"10001001 @app.route("/1")1002 def index1():1003 raise ForbiddenSubclass()10041005 @app.route("/2")1006 def index2():1007 flask.abort(403)10081009 @app.route("/3")1010 def index3():1011 raise Forbidden()10121013 assert client.get("/1").data == b"banana"1014 assert client.get("/2").data == b"apple"1015 assert client.get("/3").data == b"apple"101610171018def test_errorhandler_precedence(app, client):1019 class E1(Exception):1020 pass10211022 class E2(Exception):1023 pass10241025 class E3(E1, E2):1026 pass10271028 @app.errorhandler(E2)1029 def handle_e2(e):1030 return "E2"10311032 @app.errorhandler(Exception)1033 def handle_exception(e):1034 return "Exception"10351036 @app.route("/E1")1037 def raise_e1():1038 raise E110391040 @app.route("/E3")1041 def raise_e3():1042 raise E310431044 rv = client.get("/E1")1045 assert rv.data == b"Exception"10461047 rv = client.get("/E3")1048 assert rv.data == b"E2"104910501051@pytest.mark.parametrize(1052 ("debug", "trap", "expect_key", "expect_abort"),1053 [(False, None, True, True), (True, None, False, True), (False, True, False, False)],1054)1055def test_trap_bad_request_key_error(app, client, debug, trap, expect_key, expect_abort):1056 app.config["DEBUG"] = debug1057 app.config["TRAP_BAD_REQUEST_ERRORS"] = trap10581059 @app.route("/key")1060 def fail():1061 flask.request.form["missing_key"]10621063 @app.route("/abort")1064 def allow_abort():1065 flask.abort(400)10661067 if expect_key:1068 rv = client.get("/key")1069 assert rv.status_code == 4001070 assert b"missing_key" not in rv.data1071 else:1072 with pytest.raises(KeyError) as exc_info:1073 client.get("/key")10741075 assert exc_info.errisinstance(BadRequest)1076 assert "missing_key" in exc_info.value.get_description()10771078 if expect_abort:1079 rv = client.get("/abort")1080 assert rv.status_code == 4001081 else:1082 with pytest.raises(BadRequest):1083 client.get("/abort")108410851086def test_trapping_of_all_http_exceptions(app, client):1087 app.config["TRAP_HTTP_EXCEPTIONS"] = True10881089 @app.route("/fail")1090 def fail():1091 flask.abort(404)10921093 with pytest.raises(NotFound):1094 client.get("/fail")109510961097def test_error_handler_after_processor_error(app, client):1098 app.testing = False10991100 @app.before_request1101 def before_request():1102 if _trigger == "before":use ruff linter and formatter (#5331)David Lordbefore adoption9a12f34
line 1103why, one step back1103 raise ZeroDivisionErrorMerge branch '2.2.x'David Lordbefore adoptioned5b240
lines 1104–1107why, one step back11041105 @app.after_request1106 def after_request(response):1107 if _trigger == "after":use ruff linter and formatter (#5331)David Lordbefore adoption9a12f34
lines 1108–1109why, one step back1108 raise ZeroDivisionError1109Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 1110–1422why, one step back1110 return response11111112 @app.route("/")1113 def index():1114 return "Foo"11151116 @app.errorhandler(500)1117 def internal_server_error(e):1118 return "Hello Server Error", 50011191120 for _trigger in "before", "after":1121 rv = client.get("/")1122 assert rv.status_code == 5001123 assert rv.data == b"Hello Server Error"112411251126def test_enctype_debug_helper(app, client):1127 from flask.debughelpers import DebugFilesKeyError11281129 app.debug = True11301131 @app.route("/fail", methods=["POST"])1132 def index():1133 return flask.request.files["foo"].filename11341135 with pytest.raises(DebugFilesKeyError) as e:1136 client.post("/fail", data={"foo": "index.txt"})1137 assert "no file contents were transmitted" in str(e.value)1138 assert "This was submitted: 'index.txt'" in str(e.value)113911401141def test_response_types(app, client):1142 @app.route("/text")1143 def from_text():1144 return "Hällo Wörld"11451146 @app.route("/bytes")1147 def from_bytes():1148 return "Hällo Wörld".encode()11491150 @app.route("/full_tuple")1151 def from_full_tuple():1152 return (1153 "Meh",1154 400,1155 {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1156 )11571158 @app.route("/text_headers")1159 def from_text_headers():1160 return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}11611162 @app.route("/text_status")1163 def from_text_status():1164 return "Hi, status!", 40011651166 @app.route("/response_headers")1167 def from_response_headers():1168 return (1169 flask.Response(1170 "Hello world", 404, {"Content-Type": "text/html", "X-Foo": "Baz"}1171 ),1172 {"Content-Type": "text/plain", "X-Foo": "Bar", "X-Bar": "Foo"},1173 )11741175 @app.route("/response_status")1176 def from_response_status():1177 return app.response_class("Hello world", 400), 50011781179 @app.route("/wsgi")1180 def from_wsgi():1181 return NotFound()11821183 @app.route("/dict")1184 def from_dict():1185 return {"foo": "bar"}, 20111861187 @app.route("/list")1188 def from_list():1189 return ["foo", "bar"], 20111901191 assert client.get("/text").data == "Hällo Wörld".encode()1192 assert client.get("/bytes").data == "Hällo Wörld".encode()11931194 rv = client.get("/full_tuple")1195 assert rv.data == b"Meh"1196 assert rv.headers["X-Foo"] == "Testing"1197 assert rv.status_code == 4001198 assert rv.mimetype == "text/plain"11991200 rv = client.get("/text_headers")1201 assert rv.data == b"Hello"1202 assert rv.headers["X-Foo"] == "Test"1203 assert rv.status_code == 2001204 assert rv.mimetype == "text/plain"12051206 rv = client.get("/text_status")1207 assert rv.data == b"Hi, status!"1208 assert rv.status_code == 4001209 assert rv.mimetype == "text/html"12101211 rv = client.get("/response_headers")1212 assert rv.data == b"Hello world"1213 assert rv.content_type == "text/plain"1214 assert rv.headers.getlist("X-Foo") == ["Bar"]1215 assert rv.headers["X-Bar"] == "Foo"1216 assert rv.status_code == 40412171218 rv = client.get("/response_status")1219 assert rv.data == b"Hello world"1220 assert rv.status_code == 50012211222 rv = client.get("/wsgi")1223 assert b"Not Found" in rv.data1224 assert rv.status_code == 40412251226 rv = client.get("/dict")1227 assert rv.json == {"foo": "bar"}1228 assert rv.status_code == 20112291230 rv = client.get("/list")1231 assert rv.json == ["foo", "bar"]1232 assert rv.status_code == 201123312341235def test_response_type_errors():1236 app = flask.Flask(__name__)1237 app.testing = True12381239 @app.route("/none")1240 def from_none():1241 pass12421243 @app.route("/small_tuple")1244 def from_small_tuple():1245 return ("Hello",)12461247 @app.route("/large_tuple")1248 def from_large_tuple():1249 return "Hello", 234, {"X-Foo": "Bar"}, "???"12501251 @app.route("/bad_type")1252 def from_bad_type():1253 return True12541255 @app.route("/bad_wsgi")1256 def from_bad_wsgi():1257 return lambda: None12581259 c = app.test_client()12601261 with pytest.raises(TypeError) as e:1262 c.get("/none")12631264 assert "returned None" in str(e.value)1265 assert "from_none" in str(e.value)12661267 with pytest.raises(TypeError) as e:1268 c.get("/small_tuple")12691270 assert "tuple must have the form" in str(e.value)12711272 with pytest.raises(TypeError):1273 c.get("/large_tuple")12741275 with pytest.raises(TypeError) as e:1276 c.get("/bad_type")12771278 assert "it was a bool" in str(e.value)12791280 with pytest.raises(TypeError):1281 c.get("/bad_wsgi")128212831284def test_make_response(app, req_ctx):1285 rv = flask.make_response()1286 assert rv.status_code == 2001287 assert rv.data == b""1288 assert rv.mimetype == "text/html"12891290 rv = flask.make_response("Awesome")1291 assert rv.status_code == 2001292 assert rv.data == b"Awesome"1293 assert rv.mimetype == "text/html"12941295 rv = flask.make_response("W00t", 404)1296 assert rv.status_code == 4041297 assert rv.data == b"W00t"1298 assert rv.mimetype == "text/html"12991300 rv = flask.make_response(c for c in "Hello")1301 assert rv.status_code == 2001302 assert rv.data == b"Hello"1303 assert rv.mimetype == "text/html"130413051306def test_make_response_with_response_instance(app, req_ctx):1307 rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1308 assert rv.status_code == 4001309 assert rv.data == b'{"msg":"W00t"}\n'1310 assert rv.mimetype == "application/json"13111312 rv = flask.make_response(flask.Response(""), 400)1313 assert rv.status_code == 4001314 assert rv.data == b""1315 assert rv.mimetype == "text/html"13161317 rv = flask.make_response(1318 flask.Response("", headers={"Content-Type": "text/html"}),1319 400,1320 [("X-Foo", "bar")],1321 )1322 assert rv.status_code == 4001323 assert rv.headers["Content-Type"] == "text/html"1324 assert rv.headers["X-Foo"] == "bar"132513261327@pytest.mark.parametrize("compact", [True, False])1328def test_jsonify_no_prettyprint(app, compact):1329 app.json.compact = compact1330 rv = app.json.response({"msg": {"submsg": "W00t"}, "msg2": "foobar"})1331 data = rv.data.strip()1332 assert (b" " not in data) is compact1333 assert (b"\n" not in data) is compact133413351336def test_jsonify_mimetype(app, req_ctx):1337 app.json.mimetype = "application/vnd.api+json"1338 msg = {"msg": {"submsg": "W00t"}}1339 rv = flask.make_response(flask.jsonify(msg), 200)1340 assert rv.mimetype == "application/vnd.api+json"134113421343def test_json_dump_dataclass(app, req_ctx):1344 from dataclasses import make_dataclass13451346 Data = make_dataclass("Data", [("name", str)])1347 value = app.json.dumps(Data("Flask"))1348 value = app.json.loads(value)1349 assert value == {"name": "Flask"}135013511352def test_jsonify_args_and_kwargs_check(app, req_ctx):1353 with pytest.raises(TypeError) as e:1354 flask.jsonify("fake args", kwargs="fake")1355 assert "args or kwargs" in str(e.value)135613571358def test_url_generation(app, req_ctx):1359 @app.route("/hello/<name>", methods=["POST"])1360 def hello():1361 pass13621363 assert flask.url_for("hello", name="test x") == "/hello/test%20x"1364 assert (1365 flask.url_for("hello", name="test x", _external=True)1366 == "http://localhost/hello/test%20x"1367 )136813691370def test_build_error_handler(app):1371 # Test base case, a URL which results in a BuildError.1372 with app.test_request_context():1373 pytest.raises(BuildError, flask.url_for, "spam")13741375 # Verify the error is re-raised if not the current exception.1376 try:1377 with app.test_request_context():1378 flask.url_for("spam")1379 except BuildError as err:1380 error = err1381 try:1382 raise RuntimeError("Test case where BuildError is not current.")1383 except RuntimeError:1384 pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})13851386 # Test a custom handler.1387 def handler(error, endpoint, values):1388 # Just a test.1389 return "/test_handler/"13901391 app.url_build_error_handlers.append(handler)1392 with app.test_request_context():1393 assert flask.url_for("spam") == "/test_handler/"139413951396def test_build_error_handler_reraise(app):1397 # Test a custom handler which reraises the BuildError1398 def handler_raises_build_error(error, endpoint, values):1399 raise error14001401 app.url_build_error_handlers.append(handler_raises_build_error)14021403 with app.test_request_context():1404 pytest.raises(BuildError, flask.url_for, "not.existing")140514061407def test_url_for_passes_special_values_to_build_error_handler(app):1408 @app.url_build_error_handlers.append1409 def handler(error, endpoint, values):1410 assert values == {1411 "_external": False,1412 "_anchor": None,1413 "_method": None,1414 "_scheme": None,1415 }1416 return "handled"14171418 with app.test_request_context():1419 flask.url_for("/")142014211422def test_static_files(app, client):all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
lines 1423–1429why, one step back1423 with client.get("/static/index.html") as rv:1424 assert rv.status_code == 2001425 assert rv.data.strip() == b"<h1>Hello World!</h1>"1426 with app.test_request_context():1427 assert (1428 flask.url_for("static", filename="index.html") == "/static/index.html"1429 )Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 1430–1435why, one step back143014311432def test_static_url_path():1433 app = flask.Flask(__name__, static_url_path="/foo")1434 app.testing = True1435all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
lines 1436–1438why, one step back1436 with app.test_client().get("/foo/index.html") as rv:1437 assert rv.status_code == 2001438Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 1439–1446why, one step back1439 with app.test_request_context():1440 assert flask.url_for("static", filename="index.html") == "/foo/index.html"144114421443def test_static_url_path_with_ending_slash():1444 app = flask.Flask(__name__, static_url_path="/foo/")1445 app.testing = True1446all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
lines 1447–1449why, one step back1447 with app.test_client().get("/foo/index.html") as rv:1448 assert rv.status_code == 2001449Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 1450–1456why, one step back1450 with app.test_request_context():1451 assert flask.url_for("static", filename="index.html") == "/foo/index.html"145214531454def test_static_url_empty_path(app):1455 app = flask.Flask(__name__, static_folder="", static_url_path="")1456all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
lines 1457–1458why, one step back1457 with app.test_client().open("/static/index.html", method="GET") as rv:1458 assert rv.status_code == 200Merge branch '2.2.x'David Lordbefore adoptioned5b240
line 1459why, one step back1459all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
line 1460why, one step back1460Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 1461–1463why, one step back1461def test_static_url_empty_path_default(app):1462 app = flask.Flask(__name__, static_folder="")1463all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
lines 1464–1465why, one step back1464 with app.test_client().open("/static/index.html", method="GET") as rv:1465 assert rv.status_code == 200Merge branch '2.2.x'David Lordbefore adoptioned5b240
line 1466why, one step back1466all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
line 1467why, one step back1467Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 1468–1472why, one step back1468def test_static_folder_with_pathlib_path(app):1469 from pathlib import Path14701471 app = flask.Flask(__name__, static_folder=Path("static"))1472all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
lines 1473–1474why, one step back1473 with app.test_client().open("/static/index.html", method="GET") as rv:1474 assert rv.status_code == 200Merge branch '2.2.x'David Lordbefore adoptioned5b240
line 1475why, one step back1475all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
line 1476why, one step back1476Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 1477–1490why, one step back1477def test_static_folder_with_ending_slash():1478 app = flask.Flask(__name__, static_folder="static/")14791480 @app.route("/<path:path>")1481 def catch_all(path):1482 return path14831484 rv = app.test_client().get("/catch/all")1485 assert rv.data == b"catch/all"148614871488def test_static_route_with_host_matching():1489 app = flask.Flask(__name__, host_matching=True, static_host="example.com")1490 c = app.test_client()all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
lines 1491–1494why, one step back14911492 with c.get("http://example.com/static/index.html") as rv:1493 assert rv.status_code == 2001494Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 1495–1512why, one step back1495 with app.test_request_context():1496 rv = flask.url_for("static", filename="index.html", _external=True)1497 assert rv == "http://example.com/static/index.html"1498 # Providing static_host without host_matching=True should error.1499 with pytest.raises(AssertionError):1500 flask.Flask(__name__, static_host="example.com")1501 # Providing host_matching=True with static_folder1502 # but without static_host should error.1503 with pytest.raises(AssertionError):1504 flask.Flask(__name__, host_matching=True)1505 # Providing host_matching=True without static_host1506 # but with static_folder=None should not error.1507 flask.Flask(__name__, host_matching=True, static_folder=None)150815091510def test_request_locals():1511 assert repr(flask.g) == "<LocalProxy unbound>"1512 assert not flask.gsetting `SERVER_NAME` does not restrict routing for both `subdomain_matching` and `host_matching` (#5634)David Lordbefore adoption10bdf61
lines 1513–1514why, one step back15131514update domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2
lines 1515–1517why, one step back1515werkzeug_3_2 = importlib.metadata.version("werkzeug") >= "3.2."15161517setting `SERVER_NAME` does not restrict routing for both `subdomain_matching` and `host_matching` (#5634)David Lordbefore adoption10bdf61
line 1518why, one step back1518@pytest.mark.parametrize(update domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2
line 1519why, one step back1519 ("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 1520why, one step back1520 [update domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2
lines 1521–1523why, one step back1521 (False, False, "default", "default"),1522 (True, False, "abc", "<invalid>"),1523 (False, True, "abc", "default"),setting `SERVER_NAME` does not restrict routing for both `subdomain_matching` and `host_matching` (#5634)David Lordbefore adoption10bdf61
lines 1524–1528why, one step back1524 ],1525)1526def test_server_name_matching(1527 subdomain_matching: bool,1528 host_matching: bool,update domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2
lines 1529–1530why, one step back1529 expect_subdomain: str,1530 expect_host: str,setting `SERVER_NAME` does not restrict routing for both `subdomain_matching` and `host_matching` (#5634)David Lordbefore adoption10bdf61
lines 1531–1547why, one step back1531) -> None:1532 app = flask.Flask(1533 __name__,1534 subdomain_matching=subdomain_matching,1535 host_matching=host_matching,1536 static_host="example.test" if host_matching else None,1537 )1538 app.config["SERVER_NAME"] = "example.test"15391540 @app.route("/", defaults={"name": "default"}, host="<name>")1541 @app.route("/", subdomain="<name>", host="<name>.example.test")1542 def index(name: str) -> str:1543 return name15441545 client = app.test_client()15461547 r = client.get(base_url="http://example.test")update domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2
line 1548why, one step back1548 assert r.text == "default"setting `SERVER_NAME` does not restrict routing for both `subdomain_matching` and `host_matching` (#5634)David Lordbefore adoption10bdf61
lines 1549–1550why, one step back15491550 r = client.get(base_url="http://abc.example.test")update domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2
line 1551why, one step back1551 assert r.text == expect_subdomainsetting `SERVER_NAME` does not restrict routing for both `subdomain_matching` and `host_matching` (#5634)David Lordbefore adoption10bdf61
lines 1552–1555why, one step back15521553 with pytest.warns() if subdomain_matching else nullcontext():1554 r = client.get(base_url="http://xyz.other.test")1555update domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2
lines 1556–1559why, one step back1556 if werkzeug_3_2:1557 assert r.text == "default"1558 else:1559 assert r.text == expect_hostMerge branch '2.2.x'David Lordbefore adoptioned5b240
lines 1560–1594why, one step back156015611562def test_server_name_subdomain():1563 app = flask.Flask(__name__, subdomain_matching=True)1564 client = app.test_client()15651566 @app.route("/")1567 def index():1568 return "default"15691570 @app.route("/", subdomain="foo")1571 def subdomain():1572 return "subdomain"15731574 app.config["SERVER_NAME"] = "dev.local:5000"1575 rv = client.get("/")1576 assert rv.data == b"default"15771578 rv = client.get("/", "http://dev.local:5000")1579 assert rv.data == b"default"15801581 rv = client.get("/", "https://dev.local:5000")1582 assert rv.data == b"default"15831584 app.config["SERVER_NAME"] = "dev.local:443"1585 rv = client.get("/", "https://dev.local")15861587 # Werkzeug 1.0 fixes matching https scheme with 443 port1588 if rv.status_code != 404:1589 assert rv.data == b"default"15901591 app.config["SERVER_NAME"] = "dev.local"1592 rv = client.get("/", "https://dev.local")1593 assert rv.data == b"default"1594update domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2
line 1595why, one step back1595 with pytest.warns(match="Current server name"):Merge branch '2.2.x'David Lordbefore adoptioned5b240
line 1596why, one step back1596 rv = client.get("/", "http://foo.localhost")update domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2
lines 1597–1600why, one step back15971598 if werkzeug_3_2:1599 assert rv.status_code == 2001600 else:Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 1601–1612why, one step back1601 assert rv.status_code == 40416021603 rv = client.get("/", "http://foo.dev.local")1604 assert rv.data == b"subdomain"160516061607@pytest.mark.parametrize("key", ["TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None])1608def test_exception_propagation(app, client, key):1609 app.testing = False16101611 @app.route("/")1612 def index():use ruff linter and formatter (#5331)David Lordbefore adoption9a12f34
line 1613why, one step back1613 raise ZeroDivisionErrorMerge branch '2.2.x'David Lordbefore adoptioned5b240
lines 1614–1835why, one step back16141615 if key is not None:1616 app.config[key] = True16171618 with pytest.raises(ZeroDivisionError):1619 client.get("/")1620 else:1621 assert client.get("/").status_code == 500162216231624@pytest.mark.parametrize("debug", [True, False])1625@pytest.mark.parametrize("use_debugger", [True, False])1626@pytest.mark.parametrize("use_reloader", [True, False])1627@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1628def test_werkzeug_passthrough_errors(1629 monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1630):1631 rv = {}16321633 # Mocks werkzeug.serving.run_simple method1634 def run_simple_mock(*args, **kwargs):1635 rv["passthrough_errors"] = kwargs.get("passthrough_errors")16361637 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1638 app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1639 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)164016411642def test_url_processors(app, client):1643 @app.url_defaults1644 def add_language_code(endpoint, values):1645 if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1646 endpoint, "lang_code"1647 ):1648 values.setdefault("lang_code", flask.g.lang_code)16491650 @app.url_value_preprocessor1651 def pull_lang_code(endpoint, values):1652 flask.g.lang_code = values.pop("lang_code", None)16531654 @app.route("/<lang_code>/")1655 def index():1656 return flask.url_for("about")16571658 @app.route("/<lang_code>/about")1659 def about():1660 return flask.url_for("something_else")16611662 @app.route("/foo")1663 def something_else():1664 return flask.url_for("about", lang_code="en")16651666 assert client.get("/de/").data == b"/de/about"1667 assert client.get("/de/about").data == b"/foo"1668 assert client.get("/foo").data == b"/en/about"166916701671def test_inject_blueprint_url_defaults(app):1672 bp = flask.Blueprint("foo", __name__, template_folder="template")16731674 @bp.url_defaults1675 def bp_defaults(endpoint, values):1676 values["page"] = "login"16771678 @bp.route("/<page>")1679 def view(page):1680 pass16811682 app.register_blueprint(bp)16831684 values = dict()1685 app.inject_url_defaults("foo.view", values)1686 expected = dict(page="login")1687 assert values == expected16881689 with app.test_request_context("/somepage"):1690 url = flask.url_for("foo.view")1691 expected = "/login"1692 assert url == expected169316941695def test_nonascii_pathinfo(app, client):1696 @app.route("/киртест")1697 def index():1698 return "Hello World!"16991700 rv = client.get("/киртест")1701 assert rv.data == b"Hello World!"170217031704def test_no_setup_after_first_request(app, client):1705 app.debug = True17061707 @app.route("/")1708 def index():1709 return "Awesome"17101711 assert client.get("/").data == b"Awesome"17121713 with pytest.raises(AssertionError) as exc_info:1714 app.add_url_rule("/foo", endpoint="late")17151716 assert "setup method 'add_url_rule'" in str(exc_info.value)171717181719def test_routing_redirect_debugging(monkeypatch, app, client):1720 app.config["DEBUG"] = True17211722 @app.route("/user/", methods=["GET", "POST"])1723 def user():1724 return flask.request.form["status"]17251726 # default redirect code preserves form data1727 rv = client.post("/user", data={"status": "success"}, follow_redirects=True)1728 assert rv.data == b"success"17291730 # 301 and 302 raise error1731 monkeypatch.setattr(RequestRedirect, "code", 301)17321733 with client, pytest.raises(AssertionError) as exc_info:1734 client.post("/user", data={"status": "error"}, follow_redirects=True)17351736 assert "canonical URL 'http://localhost/user/'" in str(exc_info.value)173717381739def test_route_decorator_custom_endpoint(app, client):1740 app.debug = True17411742 @app.route("/foo/")1743 def foo():1744 return flask.request.endpoint17451746 @app.route("/bar/", endpoint="bar")1747 def for_bar():1748 return flask.request.endpoint17491750 @app.route("/bar/123", endpoint="123")1751 def for_bar_foo():1752 return flask.request.endpoint17531754 with app.test_request_context():1755 assert flask.url_for("foo") == "/foo/"1756 assert flask.url_for("bar") == "/bar/"1757 assert flask.url_for("123") == "/bar/123"17581759 assert client.get("/foo/").data == b"foo"1760 assert client.get("/bar/").data == b"bar"1761 assert client.get("/bar/123").data == b"123"176217631764def test_get_method_on_g(app_ctx):1765 assert flask.g.get("x") is None1766 assert flask.g.get("x", 11) == 111767 flask.g.x = 421768 assert flask.g.get("x") == 421769 assert flask.g.x == 42177017711772def test_g_iteration_protocol(app_ctx):1773 flask.g.foo = 231774 flask.g.bar = 421775 assert "foo" in flask.g1776 assert "foos" not in flask.g1777 assert sorted(flask.g) == ["bar", "foo"]177817791780def test_subdomain_basic_support():1781 app = flask.Flask(__name__, subdomain_matching=True)1782 app.config["SERVER_NAME"] = "localhost.localdomain"1783 client = app.test_client()17841785 @app.route("/")1786 def normal_index():1787 return "normal index"17881789 @app.route("/", subdomain="test")1790 def test_index():1791 return "test index"17921793 rv = client.get("/", "http://localhost.localdomain/")1794 assert rv.data == b"normal index"17951796 rv = client.get("/", "http://test.localhost.localdomain/")1797 assert rv.data == b"test index"179817991800def test_subdomain_matching():1801 app = flask.Flask(__name__, subdomain_matching=True)1802 client = app.test_client()1803 app.config["SERVER_NAME"] = "localhost.localdomain"18041805 @app.route("/", subdomain="<user>")1806 def index(user):1807 return f"index for {user}"18081809 rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1810 assert rv.data == b"index for mitsuhiko"181118121813def test_subdomain_matching_with_ports():1814 app = flask.Flask(__name__, subdomain_matching=True)1815 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1816 client = app.test_client()18171818 @app.route("/", subdomain="<user>")1819 def index(user):1820 return f"index for {user}"18211822 rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1823 assert rv.data == b"index for mitsuhiko"182418251826@pytest.mark.parametrize("matching", (False, True))1827def test_subdomain_matching_other_name(matching):1828 app = flask.Flask(__name__, subdomain_matching=matching)1829 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1830 client = app.test_client()18311832 @app.route("/")1833 def index():1834 return "", 2041835update domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2
lines 1836–1837why, one step back1836 with pytest.warns(match="Current server name") if matching else nullcontext():1837 # ip address can't match name, but will fall back to defaultMerge branch '2.2.x'David Lordbefore adoptioned5b240
line 1838why, one step back1838 rv = client.get("/", "http://127.0.0.1:3000/")update domain matching tests for Werkzeug 3.2David Lordbefore adoption5e621a2
lines 1839–1842why, one step back18391840 if werkzeug_3_2:1841 assert rv.status_code == 2041842 else:Merge branch '2.2.x'David Lordbefore adoptioned5b240
lines 1843–1970why, one step back1843 assert rv.status_code == 404 if matching else 20418441845 # allow all subdomains if matching is disabled1846 rv = client.get("/", "http://www.localhost.localdomain:3000/")1847 assert rv.status_code == 404 if matching else 204184818491850def test_multi_route_rules(app, client):1851 @app.route("/")1852 @app.route("/<test>/")1853 def index(test="a"):1854 return test18551856 rv = client.open("/")1857 assert rv.data == b"a"1858 rv = client.open("/b/")1859 assert rv.data == b"b"186018611862def test_multi_route_class_views(app, client):1863 class View:1864 def __init__(self, app):1865 app.add_url_rule("/", "index", self.index)1866 app.add_url_rule("/<test>/", "index", self.index)18671868 def index(self, test="a"):1869 return test18701871 _ = View(app)1872 rv = client.open("/")1873 assert rv.data == b"a"1874 rv = client.open("/b/")1875 assert rv.data == b"b"187618771878def test_run_defaults(monkeypatch, app):1879 rv = {}18801881 # Mocks werkzeug.serving.run_simple method1882 def run_simple_mock(*args, **kwargs):1883 rv["result"] = "running..."18841885 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1886 app.run()1887 assert rv["result"] == "running..."188818891890def test_run_server_port(monkeypatch, app):1891 rv = {}18921893 # Mocks werkzeug.serving.run_simple method1894 def run_simple_mock(hostname, port, application, *args, **kwargs):1895 rv["result"] = f"running on {hostname}:{port} ..."18961897 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1898 hostname, port = "localhost", 80001899 app.run(hostname, port, debug=True)1900 assert rv["result"] == f"running on {hostname}:{port} ..."190119021903@pytest.mark.parametrize(1904 "host,port,server_name,expect_host,expect_port",1905 (1906 (None, None, "pocoo.org:8080", "pocoo.org", 8080),1907 ("localhost", None, "pocoo.org:8080", "localhost", 8080),1908 (None, 80, "pocoo.org:8080", "pocoo.org", 80),1909 ("localhost", 80, "pocoo.org:8080", "localhost", 80),1910 ("localhost", 0, "localhost:8080", "localhost", 0),1911 (None, None, "localhost:8080", "localhost", 8080),1912 (None, None, "localhost:0", "localhost", 0),1913 ),1914)1915def test_run_from_config(1916 monkeypatch, host, port, server_name, expect_host, expect_port, app1917):1918 def run_simple_mock(hostname, port, *args, **kwargs):1919 assert hostname == expect_host1920 assert port == expect_port19211922 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1923 app.config["SERVER_NAME"] = server_name1924 app.run(host, port)192519261927def test_max_cookie_size(app, client, recwarn):1928 app.config["MAX_COOKIE_SIZE"] = 10019291930 # outside app context, default to Werkzeug static value,1931 # which is also the default config1932 response = flask.Response()1933 default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1934 assert response.max_cookie_size == default19351936 # inside app context, use app config1937 with app.app_context():1938 assert flask.Response().max_cookie_size == 10019391940 @app.route("/")1941 def index():1942 r = flask.Response("", status=204)1943 r.set_cookie("foo", "bar" * 100)1944 return r19451946 client.get("/")1947 assert len(recwarn) == 11948 w = recwarn.pop()1949 assert "cookie is too large" in str(w.message)19501951 app.config["MAX_COOKIE_SIZE"] = 019521953 client.get("/")1954 assert len(recwarn) == 0195519561957@require_cpython_gc1958def test_app_freed_on_zero_refcount():1959 # A Flask instance should not create a reference cycle that prevents CPython1960 # from freeing it when all external references to it are released (see #3761).1961 gc.disable()1962 try:1963 app = flask.Flask(__name__)1964 assert app.view_functions["static"]1965 weak = weakref.ref(app)1966 assert weak() is not None1967 del app1968 assert weak() is None1969 finally:1970 gc.enable()