Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

2,029 lines · 54.5 KiB · Python

Last changed by

refactor error checks in register_error_handlerQingpeng Libefore adoption1e5dd43

History of this file

Take it

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

Break reference cycle created by default in Flask instances.Bogdan Opanchukbefore adoption8efea0c

line 1why, one step back
1import gc

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

lines 2–4why, one step back
2import re
3import time4import uuid

Merge branch '2.0.x'David Lordbefore adoptione37e871

line 5why, one step back
5import warnings

Break reference cycle created by default in Flask instances.Bogdan Opanchukbefore adoption8efea0c

line 6why, one step back
6import weakref

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

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

Break reference cycle created by default in Flask instances.Bogdan Opanchukbefore adoption8efea0c

line 8why, one step back
8from platform import python_implementation

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

lines 9–17why, one step back
9from threading import Thread
1011import pytest12import werkzeug.serving13from werkzeug.exceptions import BadRequest14from werkzeug.exceptions import Forbidden15from werkzeug.exceptions import NotFound16from werkzeug.http import parse_date17from werkzeug.routing import BuildError

Merge pull request #4492 from pallets/debug-messagesDavid Lordbefore adoptionce7b884

line 18why, one step back
18from werkzeug.routing import RequestRedirect

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

lines 19–22why, one step back
19
20import flask2122

Break reference cycle created by default in Flask instances.Bogdan Opanchukbefore adoption8efea0c

line 23why, one step back
23require_cpython_gc = pytest.mark.skipif(

update requirements (#3823)David Lordbefore adoption373f0dd

lines 24–25why, one step back
24 python_implementation() != "CPython",
25 reason="Requires CPython GC behavior",

Break reference cycle created by default in Flask instances.Bogdan Opanchukbefore adoption8efea0c

lines 26–28why, one step back
26)
2728

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

lines 29–51why, one step back
29def test_options_work(app, client):
30 @app.route("/", methods=["GET", "POST"])31 def index():32 return "Hello World"3334 rv = client.open("/", method="OPTIONS")35 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]36 assert rv.data == b""373839def test_options_on_multiple_rules(app, client):40 @app.route("/", methods=["GET", "POST"])41 def index():42 return "Hello World"4344 @app.route("/", methods=["PUT"])45 def index_put():46 return "Aha!"4748 rv = client.open("/", method="OPTIONS")49 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST", "PUT"]5051

Merge pull request #3907 from pgjones/sugarDavid Lordbefore adoption5fea7ca

lines 52–68why, one step back
52@pytest.mark.parametrize("method", ["get", "post", "put", "delete", "patch"])
53def test_method_route(app, client, method):54 method_route = getattr(app, method)55 client_method = getattr(client, method)5657 @method_route("/")58 def hello():59 return "Hello"6061 assert client_method("/").data == b"Hello"626364def test_method_route_no_methods(app):65 with pytest.raises(TypeError):66 app.get("/", methods=["GET", "POST"])6768

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

lines 69–152why, one step back
69def test_provide_automatic_options_attr():
70 app = flask.Flask(__name__)7172 def index():73 return "Hello World!"7475 index.provide_automatic_options = False76 app.route("/")(index)77 rv = app.test_client().open("/", method="OPTIONS")78 assert rv.status_code == 4057980 app = flask.Flask(__name__)8182 def index2():83 return "Hello World!"8485 index2.provide_automatic_options = True86 app.route("/", methods=["OPTIONS"])(index2)87 rv = app.test_client().open("/", method="OPTIONS")88 assert sorted(rv.allow) == ["OPTIONS"]899091def test_provide_automatic_options_kwarg(app, client):92 def index():93 return flask.request.method9495 def more():96 return flask.request.method9798 app.add_url_rule("/", view_func=index, provide_automatic_options=False)99 app.add_url_rule(100 "/more",101 view_func=more,102 methods=["GET", "POST"],103 provide_automatic_options=False,104 )105 assert client.get("/").data == b"GET"106107 rv = client.post("/")108 assert rv.status_code == 405109 assert sorted(rv.allow) == ["GET", "HEAD"]110111 rv = client.open("/", method="OPTIONS")112 assert rv.status_code == 405113114 rv = client.head("/")115 assert rv.status_code == 200116 assert not rv.data # head truncates117 assert client.post("/more").data == b"POST"118 assert client.get("/more").data == b"GET"119120 rv = client.delete("/more")121 assert rv.status_code == 405122 assert sorted(rv.allow) == ["GET", "HEAD", "POST"]123124 rv = client.open("/more", method="OPTIONS")125 assert rv.status_code == 405126127128def test_request_dispatching(app, client):129 @app.route("/")130 def index():131 return flask.request.method132133 @app.route("/more", methods=["GET", "POST"])134 def more():135 return flask.request.method136137 assert client.get("/").data == b"GET"138 rv = client.post("/")139 assert rv.status_code == 405140 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]141 rv = client.head("/")142 assert rv.status_code == 200143 assert not rv.data # head truncates144 assert client.post("/more").data == b"POST"145 assert client.get("/more").data == b"GET"146 rv = client.delete("/more")147 assert rv.status_code == 405148 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]149150151def test_disallow_string_for_allowed_methods(app):152 with pytest.raises(TypeError):

Merge branch '2.1.x'David Lordbefore adoptionf976d5b

line 153why, one step back
153 app.add_url_rule("/", methods="GET POST", endpoint="test")

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

lines 154–339why, one step back
154
155156def test_url_mapping(app, client):157 random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"158159 def index():160 return flask.request.method161162 def more():163 return flask.request.method164165 def options():166 return random_uuid4167168 app.add_url_rule("/", "index", index)169 app.add_url_rule("/more", "more", more, methods=["GET", "POST"])170171 # Issue 1288: Test that automatic options are not added172 # when non-uppercase 'options' in methods173 app.add_url_rule("/options", "options", options, methods=["options"])174175 assert client.get("/").data == b"GET"176 rv = client.post("/")177 assert rv.status_code == 405178 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]179 rv = client.head("/")180 assert rv.status_code == 200181 assert not rv.data # head truncates182 assert client.post("/more").data == b"POST"183 assert client.get("/more").data == b"GET"184 rv = client.delete("/more")185 assert rv.status_code == 405186 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]187 rv = client.open("/options", method="OPTIONS")188 assert rv.status_code == 200189 assert random_uuid4 in rv.data.decode("utf-8")190191192def test_werkzeug_routing(app, client):193 from werkzeug.routing import Submount, Rule194195 app.url_map.add(196 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])197 )198199 def bar():200 return "bar"201202 def index():203 return "index"204205 app.view_functions["bar"] = bar206 app.view_functions["index"] = index207208 assert client.get("/foo/").data == b"index"209 assert client.get("/foo/bar").data == b"bar"210211212def test_endpoint_decorator(app, client):213 from werkzeug.routing import Submount, Rule214215 app.url_map.add(216 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])217 )218219 @app.endpoint("bar")220 def bar():221 return "bar"222223 @app.endpoint("index")224 def index():225 return "index"226227 assert client.get("/foo/").data == b"index"228 assert client.get("/foo/bar").data == b"bar"229230231def test_session(app, client):232 @app.route("/set", methods=["POST"])233 def set():234 assert not flask.session.accessed235 assert not flask.session.modified236 flask.session["value"] = flask.request.form["value"]237 assert flask.session.accessed238 assert flask.session.modified239 return "value set"240241 @app.route("/get")242 def get():243 assert not flask.session.accessed244 assert not flask.session.modified245 v = flask.session.get("value", "None")246 assert flask.session.accessed247 assert not flask.session.modified248 return v249250 assert client.post("/set", data={"value": "42"}).data == b"value set"251 assert client.get("/get").data == b"42"252253254def test_session_using_server_name(app, client):255 app.config.update(SERVER_NAME="example.com")256257 @app.route("/")258 def index():259 flask.session["testing"] = 42260 return "Hello World"261262 rv = client.get("/", "http://example.com/")263 assert "domain=.example.com" in rv.headers["set-cookie"].lower()264 assert "httponly" in rv.headers["set-cookie"].lower()265266267def test_session_using_server_name_and_port(app, client):268 app.config.update(SERVER_NAME="example.com:8080")269270 @app.route("/")271 def index():272 flask.session["testing"] = 42273 return "Hello World"274275 rv = client.get("/", "http://example.com:8080/")276 assert "domain=.example.com" in rv.headers["set-cookie"].lower()277 assert "httponly" in rv.headers["set-cookie"].lower()278279280def test_session_using_server_name_port_and_path(app, client):281 app.config.update(SERVER_NAME="example.com:8080", APPLICATION_ROOT="/foo")282283 @app.route("/")284 def index():285 flask.session["testing"] = 42286 return "Hello World"287288 rv = client.get("/", "http://example.com:8080/foo")289 assert "domain=example.com" in rv.headers["set-cookie"].lower()290 assert "path=/foo" in rv.headers["set-cookie"].lower()291 assert "httponly" in rv.headers["set-cookie"].lower()292293294def test_session_using_application_root(app, client):295 class PrefixPathMiddleware:296 def __init__(self, app, prefix):297 self.app = app298 self.prefix = prefix299300 def __call__(self, environ, start_response):301 environ["SCRIPT_NAME"] = self.prefix302 return self.app(environ, start_response)303304 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, "/bar")305 app.config.update(APPLICATION_ROOT="/bar")306307 @app.route("/")308 def index():309 flask.session["testing"] = 42310 return "Hello World"311312 rv = client.get("/", "http://example.com:8080/")313 assert "path=/bar" in rv.headers["set-cookie"].lower()314315316def test_session_using_session_settings(app, client):317 app.config.update(318 SERVER_NAME="www.example.com:8080",319 APPLICATION_ROOT="/test",320 SESSION_COOKIE_DOMAIN=".example.com",321 SESSION_COOKIE_HTTPONLY=False,322 SESSION_COOKIE_SECURE=True,323 SESSION_COOKIE_SAMESITE="Lax",324 SESSION_COOKIE_PATH="/",325 )326327 @app.route("/")328 def index():329 flask.session["testing"] = 42330 return "Hello World"331332 rv = client.get("/", "http://www.example.com:8080/test/")333 cookie = rv.headers["set-cookie"].lower()334 assert "domain=.example.com" in cookie335 assert "path=/" in cookie336 assert "secure" in cookie337 assert "httponly" not in cookie338 assert "samesite" in cookie339

include samesite and secure when removing session cookie (#3726)Mathurshan Vimalesvaranbefore adoption22987b6

lines 340–352why, one step back
340 @app.route("/clear")
341 def clear():342 flask.session.pop("testing", None)343 return "Goodbye World"344345 rv = client.get("/clear", "http://www.example.com:8080/test/")346 cookie = rv.headers["set-cookie"].lower()347 assert "session=;" in cookie348 assert "domain=.example.com" in cookie349 assert "path=/" in cookie350 assert "secure" in cookie351 assert "samesite" in cookie352

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

lines 353–929why, one step back
353
354def test_session_using_samesite_attribute(app, client):355 @app.route("/")356 def index():357 flask.session["testing"] = 42358 return "Hello World"359360 app.config.update(SESSION_COOKIE_SAMESITE="invalid")361362 with pytest.raises(ValueError):363 client.get("/")364365 app.config.update(SESSION_COOKIE_SAMESITE=None)366 rv = client.get("/")367 cookie = rv.headers["set-cookie"].lower()368 assert "samesite" not in cookie369370 app.config.update(SESSION_COOKIE_SAMESITE="Strict")371 rv = client.get("/")372 cookie = rv.headers["set-cookie"].lower()373 assert "samesite=strict" in cookie374375 app.config.update(SESSION_COOKIE_SAMESITE="Lax")376 rv = client.get("/")377 cookie = rv.headers["set-cookie"].lower()378 assert "samesite=lax" in cookie379380381def test_session_localhost_warning(recwarn, app, client):382 app.config.update(SERVER_NAME="localhost:5000")383384 @app.route("/")385 def index():386 flask.session["testing"] = 42387 return "testing"388389 rv = client.get("/", "http://localhost:5000/")390 assert "domain" not in rv.headers["set-cookie"].lower()391 w = recwarn.pop(UserWarning)392 assert "'localhost' is not a valid cookie domain" in str(w.message)393394395def test_session_ip_warning(recwarn, app, client):396 app.config.update(SERVER_NAME="127.0.0.1:5000")397398 @app.route("/")399 def index():400 flask.session["testing"] = 42401 return "testing"402403 rv = client.get("/", "http://127.0.0.1:5000/")404 assert "domain=127.0.0.1" in rv.headers["set-cookie"].lower()405 w = recwarn.pop(UserWarning)406 assert "cookie domain is an IP" in str(w.message)407408409def test_missing_session(app):410 app.secret_key = None411412 def expect_exception(f, *args, **kwargs):413 e = pytest.raises(RuntimeError, f, *args, **kwargs)414 assert e.value.args and "session is unavailable" in e.value.args[0]415416 with app.test_request_context():417 assert flask.session.get("missing_key") is None418 expect_exception(flask.session.__setitem__, "foo", 42)419 expect_exception(flask.session.pop, "foo")420421422def test_session_expiration(app, client):423 permanent = True424425 @app.route("/")426 def index():427 flask.session["test"] = 42428 flask.session.permanent = permanent429 return ""430431 @app.route("/test")432 def test():433 return str(flask.session.permanent)434435 rv = client.get("/")436 assert "set-cookie" in rv.headers437 match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])438 expires = parse_date(match.group())439 expected = datetime.utcnow() + app.permanent_session_lifetime440 assert expires.year == expected.year441 assert expires.month == expected.month442 assert expires.day == expected.day443444 rv = client.get("/test")445 assert rv.data == b"True"446447 permanent = False448 rv = client.get("/")449 assert "set-cookie" in rv.headers450 match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])451 assert match is None452453454def test_session_stored_last(app, client):455 @app.after_request456 def modify_session(response):457 flask.session["foo"] = 42458 return response459460 @app.route("/")461 def dump_session_contents():462 return repr(flask.session.get("foo"))463464 assert client.get("/").data == b"None"465 assert client.get("/").data == b"42"466467468def test_session_special_types(app, client):469 now = datetime.utcnow().replace(microsecond=0)470 the_uuid = uuid.uuid4()471472 @app.route("/")473 def dump_session_contents():474 flask.session["t"] = (1, 2, 3)475 flask.session["b"] = b"\xff"476 flask.session["m"] = flask.Markup("<html>")477 flask.session["u"] = the_uuid478 flask.session["d"] = now479 flask.session["t_tag"] = {" t": "not-a-tuple"}480 flask.session["di_t_tag"] = {" t__": "not-a-tuple"}481 flask.session["di_tag"] = {" di": "not-a-dict"}482 return "", 204483484 with client:485 client.get("/")486 s = flask.session487 assert s["t"] == (1, 2, 3)488 assert type(s["b"]) == bytes489 assert s["b"] == b"\xff"490 assert type(s["m"]) == flask.Markup491 assert s["m"] == flask.Markup("<html>")492 assert s["u"] == the_uuid493 assert s["d"] == now494 assert s["t_tag"] == {" t": "not-a-tuple"}495 assert s["di_t_tag"] == {" t__": "not-a-tuple"}496 assert s["di_tag"] == {" di": "not-a-dict"}497498499def test_session_cookie_setting(app):500 is_permanent = True501502 @app.route("/bump")503 def bump():504 rv = flask.session["foo"] = flask.session.get("foo", 0) + 1505 flask.session.permanent = is_permanent506 return str(rv)507508 @app.route("/read")509 def read():510 return str(flask.session.get("foo", 0))511512 def run_test(expect_header):513 with app.test_client() as c:514 assert c.get("/bump").data == b"1"515 assert c.get("/bump").data == b"2"516 assert c.get("/bump").data == b"3"517518 rv = c.get("/read")519 set_cookie = rv.headers.get("set-cookie")520 assert (set_cookie is not None) == expect_header521 assert rv.data == b"3"522523 is_permanent = True524 app.config["SESSION_REFRESH_EACH_REQUEST"] = True525 run_test(expect_header=True)526527 is_permanent = True528 app.config["SESSION_REFRESH_EACH_REQUEST"] = False529 run_test(expect_header=False)530531 is_permanent = False532 app.config["SESSION_REFRESH_EACH_REQUEST"] = True533 run_test(expect_header=False)534535 is_permanent = False536 app.config["SESSION_REFRESH_EACH_REQUEST"] = False537 run_test(expect_header=False)538539540def test_session_vary_cookie(app, client):541 @app.route("/set")542 def set_session():543 flask.session["test"] = "test"544 return ""545546 @app.route("/get")547 def get():548 return flask.session.get("test")549550 @app.route("/getitem")551 def getitem():552 return flask.session["test"]553554 @app.route("/setdefault")555 def setdefault():556 return flask.session.setdefault("test", "default")557558 @app.route("/vary-cookie-header-set")559 def vary_cookie_header_set():560 response = flask.Response()561 response.vary.add("Cookie")562 flask.session["test"] = "test"563 return response564565 @app.route("/vary-header-set")566 def vary_header_set():567 response = flask.Response()568 response.vary.update(("Accept-Encoding", "Accept-Language"))569 flask.session["test"] = "test"570 return response571572 @app.route("/no-vary-header")573 def no_vary_header():574 return ""575576 def expect(path, header_value="Cookie"):577 rv = client.get(path)578579 if header_value:580 # The 'Vary' key should exist in the headers only once.581 assert len(rv.headers.get_all("Vary")) == 1582 assert rv.headers["Vary"] == header_value583 else:584 assert "Vary" not in rv.headers585586 expect("/set")587 expect("/get")588 expect("/getitem")589 expect("/setdefault")590 expect("/vary-cookie-header-set")591 expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")592 expect("/no-vary-header", None)593594595def test_flashes(app, req_ctx):596 assert not flask.session.modified597 flask.flash("Zap")598 flask.session.modified = False599 flask.flash("Zip")600 assert flask.session.modified601 assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]602603604def test_extended_flashing(app):605 # Be sure app.testing=True below, else tests can fail silently.606 #607 # Specifically, if app.testing is not set to True, the AssertionErrors608 # in the view functions will cause a 500 response to the test client609 # instead of propagating exceptions.610611 @app.route("/")612 def index():613 flask.flash("Hello World")614 flask.flash("Hello World", "error")615 flask.flash(flask.Markup("<em>Testing</em>"), "warning")616 return ""617618 @app.route("/test/")619 def test():620 messages = flask.get_flashed_messages()621 assert list(messages) == [622 "Hello World",623 "Hello World",624 flask.Markup("<em>Testing</em>"),625 ]626 return ""627628 @app.route("/test_with_categories/")629 def test_with_categories():630 messages = flask.get_flashed_messages(with_categories=True)631 assert len(messages) == 3632 assert list(messages) == [633 ("message", "Hello World"),634 ("error", "Hello World"),635 ("warning", flask.Markup("<em>Testing</em>")),636 ]637 return ""638639 @app.route("/test_filter/")640 def test_filter():641 messages = flask.get_flashed_messages(642 category_filter=["message"], with_categories=True643 )644 assert list(messages) == [("message", "Hello World")]645 return ""646647 @app.route("/test_filters/")648 def test_filters():649 messages = flask.get_flashed_messages(650 category_filter=["message", "warning"], with_categories=True651 )652 assert list(messages) == [653 ("message", "Hello World"),654 ("warning", flask.Markup("<em>Testing</em>")),655 ]656 return ""657658 @app.route("/test_filters_without_returning_categories/")659 def test_filters2():660 messages = flask.get_flashed_messages(category_filter=["message", "warning"])661 assert len(messages) == 2662 assert messages[0] == "Hello World"663 assert messages[1] == flask.Markup("<em>Testing</em>")664 return ""665666 # Create new test client on each test to clean flashed messages.667668 client = app.test_client()669 client.get("/")670 client.get("/test_with_categories/")671672 client = app.test_client()673 client.get("/")674 client.get("/test_filter/")675676 client = app.test_client()677 client.get("/")678 client.get("/test_filters/")679680 client = app.test_client()681 client.get("/")682 client.get("/test_filters_without_returning_categories/")683684685def test_request_processing(app, client):686 evts = []687688 @app.before_request689 def before_request():690 evts.append("before")691692 @app.after_request693 def after_request(response):694 response.data += b"|after"695 evts.append("after")696 return response697698 @app.route("/")699 def index():700 assert "before" in evts701 assert "after" not in evts702 return "request"703704 assert "after" not in evts705 rv = client.get("/").data706 assert "after" in evts707 assert rv == b"request|after"708709710def test_request_preprocessing_early_return(app, client):711 evts = []712713 @app.before_request714 def before_request1():715 evts.append(1)716717 @app.before_request718 def before_request2():719 evts.append(2)720 return "hello"721722 @app.before_request723 def before_request3():724 evts.append(3)725 return "bye"726727 @app.route("/")728 def index():729 evts.append("index")730 return "damnit"731732 rv = client.get("/").data.strip()733 assert rv == b"hello"734 assert evts == [1, 2]735736737def test_after_request_processing(app, client):738 @app.route("/")739 def index():740 @flask.after_this_request741 def foo(response):742 response.headers["X-Foo"] = "a header"743 return response744745 return "Test"746747 resp = client.get("/")748 assert resp.status_code == 200749 assert resp.headers["X-Foo"] == "a header"750751752def test_teardown_request_handler(app, client):753 called = []754755 @app.teardown_request756 def teardown_request(exc):757 called.append(True)758 return "Ignored"759760 @app.route("/")761 def root():762 return "Response"763764 rv = client.get("/")765 assert rv.status_code == 200766 assert b"Response" in rv.data767 assert len(called) == 1768769770def test_teardown_request_handler_debug_mode(app, client):771 called = []772773 @app.teardown_request774 def teardown_request(exc):775 called.append(True)776 return "Ignored"777778 @app.route("/")779 def root():780 return "Response"781782 rv = client.get("/")783 assert rv.status_code == 200784 assert b"Response" in rv.data785 assert len(called) == 1786787788def test_teardown_request_handler_error(app, client):789 called = []790 app.testing = False791792 @app.teardown_request793 def teardown_request1(exc):794 assert type(exc) == ZeroDivisionError795 called.append(True)796 # This raises a new error and blows away sys.exc_info(), so we can797 # test that all teardown_requests get passed the same original798 # exception.799 try:800 raise TypeError()801 except Exception:802 pass803804 @app.teardown_request805 def teardown_request2(exc):806 assert type(exc) == ZeroDivisionError807 called.append(True)808 # This raises a new error and blows away sys.exc_info(), so we can809 # test that all teardown_requests get passed the same original810 # exception.811 try:812 raise TypeError()813 except Exception:814 pass815816 @app.route("/")817 def fails():818 1 // 0819820 rv = client.get("/")821 assert rv.status_code == 500822 assert b"Internal Server Error" in rv.data823 assert len(called) == 2824825826def test_before_after_request_order(app, client):827 called = []828829 @app.before_request830 def before1():831 called.append(1)832833 @app.before_request834 def before2():835 called.append(2)836837 @app.after_request838 def after1(response):839 called.append(4)840 return response841842 @app.after_request843 def after2(response):844 called.append(3)845 return response846847 @app.teardown_request848 def finish1(exc):849 called.append(6)850851 @app.teardown_request852 def finish2(exc):853 called.append(5)854855 @app.route("/")856 def index():857 return "42"858859 rv = client.get("/")860 assert rv.data == b"42"861 assert called == [1, 2, 3, 4, 5, 6]862863864def test_error_handling(app, client):865 app.testing = False866867 @app.errorhandler(404)868 def not_found(e):869 return "not found", 404870871 @app.errorhandler(500)872 def internal_server_error(e):873 return "internal server error", 500874875 @app.errorhandler(Forbidden)876 def forbidden(e):877 return "forbidden", 403878879 @app.route("/")880 def index():881 flask.abort(404)882883 @app.route("/error")884 def error():885 1 // 0886887 @app.route("/forbidden")888 def error2():889 flask.abort(403)890891 rv = client.get("/")892 assert rv.status_code == 404893 assert rv.data == b"not found"894 rv = client.get("/error")895 assert rv.status_code == 500896 assert b"internal server error" == rv.data897 rv = client.get("/forbidden")898 assert rv.status_code == 403899 assert b"forbidden" == rv.data900901902def test_error_handling_processing(app, client):903 app.testing = False904905 @app.errorhandler(500)906 def internal_server_error(e):907 return "internal server error", 500908909 @app.route("/")910 def broken_func():911 1 // 0912913 @app.after_request914 def after_request(resp):915 resp.mimetype = "text/x-special"916 return resp917918 resp = client.get("/")919 assert resp.mimetype == "text/x-special"920 assert resp.data == b"internal server error"921922923def test_baseexception_error_handling(app, client):924 app.testing = False925926 @app.route("/")927 def broken_func():928 raise KeyboardInterrupt()929

Merge branch '2.1.x'David Lordbefore adoptionf976d5b

lines 930–932why, one step back
930 with client:
931 with pytest.raises(KeyboardInterrupt):932 client.get("/")

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

lines 933–1237why, one step back
933
934 ctx = flask._request_ctx_stack.top935 assert ctx.preserved936 assert type(ctx._preserved_exc) is KeyboardInterrupt937938939def test_before_request_and_routing_errors(app, client):940 @app.before_request941 def attach_something():942 flask.g.something = "value"943944 @app.errorhandler(404)945 def return_something(error):946 return flask.g.something, 404947948 rv = client.get("/")949 assert rv.status_code == 404950 assert rv.data == b"value"951952953def test_user_error_handling(app, client):954 class MyException(Exception):955 pass956957 @app.errorhandler(MyException)958 def handle_my_exception(e):959 assert isinstance(e, MyException)960 return "42"961962 @app.route("/")963 def index():964 raise MyException()965966 assert client.get("/").data == b"42"967968969def test_http_error_subclass_handling(app, client):970 class ForbiddenSubclass(Forbidden):971 pass972973 @app.errorhandler(ForbiddenSubclass)974 def handle_forbidden_subclass(e):975 assert isinstance(e, ForbiddenSubclass)976 return "banana"977978 @app.errorhandler(403)979 def handle_403(e):980 assert not isinstance(e, ForbiddenSubclass)981 assert isinstance(e, Forbidden)982 return "apple"983984 @app.route("/1")985 def index1():986 raise ForbiddenSubclass()987988 @app.route("/2")989 def index2():990 flask.abort(403)991992 @app.route("/3")993 def index3():994 raise Forbidden()995996 assert client.get("/1").data == b"banana"997 assert client.get("/2").data == b"apple"998 assert client.get("/3").data == b"apple"99910001001def test_errorhandler_precedence(app, client):1002 class E1(Exception):1003 pass10041005 class E2(Exception):1006 pass10071008 class E3(E1, E2):1009 pass10101011 @app.errorhandler(E2)1012 def handle_e2(e):1013 return "E2"10141015 @app.errorhandler(Exception)1016 def handle_exception(e):1017 return "Exception"10181019 @app.route("/E1")1020 def raise_e1():1021 raise E110221023 @app.route("/E3")1024 def raise_e3():1025 raise E310261027 rv = client.get("/E1")1028 assert rv.data == b"Exception"10291030 rv = client.get("/E3")1031 assert rv.data == b"E2"103210331034def test_trapping_of_bad_request_key_errors(app, client):1035 @app.route("/key")1036 def fail():1037 flask.request.form["missing_key"]10381039 @app.route("/abort")1040 def allow_abort():1041 flask.abort(400)10421043 rv = client.get("/key")1044 assert rv.status_code == 4001045 assert b"missing_key" not in rv.data1046 rv = client.get("/abort")1047 assert rv.status_code == 40010481049 app.debug = True1050 with pytest.raises(KeyError) as e:1051 client.get("/key")1052 assert e.errisinstance(BadRequest)1053 assert "missing_key" in e.value.get_description()1054 rv = client.get("/abort")1055 assert rv.status_code == 40010561057 app.debug = False1058 app.config["TRAP_BAD_REQUEST_ERRORS"] = True1059 with pytest.raises(KeyError):1060 client.get("/key")1061 with pytest.raises(BadRequest):1062 client.get("/abort")106310641065def test_trapping_of_all_http_exceptions(app, client):1066 app.config["TRAP_HTTP_EXCEPTIONS"] = True10671068 @app.route("/fail")1069 def fail():1070 flask.abort(404)10711072 with pytest.raises(NotFound):1073 client.get("/fail")107410751076def test_error_handler_after_processor_error(app, client):1077 app.testing = False10781079 @app.before_request1080 def before_request():1081 if _trigger == "before":1082 1 // 010831084 @app.after_request1085 def after_request(response):1086 if _trigger == "after":1087 1 // 01088 return response10891090 @app.route("/")1091 def index():1092 return "Foo"10931094 @app.errorhandler(500)1095 def internal_server_error(e):1096 return "Hello Server Error", 50010971098 for _trigger in "before", "after":1099 rv = client.get("/")1100 assert rv.status_code == 5001101 assert rv.data == b"Hello Server Error"110211031104def test_enctype_debug_helper(app, client):1105 from flask.debughelpers import DebugFilesKeyError11061107 app.debug = True11081109 @app.route("/fail", methods=["POST"])1110 def index():1111 return flask.request.files["foo"].filename11121113 # with statement is important because we leave an exception on the1114 # stack otherwise and we want to ensure that this is not the case1115 # to not negatively affect other tests.1116 with client:1117 with pytest.raises(DebugFilesKeyError) as e:1118 client.post("/fail", data={"foo": "index.txt"})1119 assert "no file contents were transmitted" in str(e.value)1120 assert "This was submitted: 'index.txt'" in str(e.value)112111221123def test_response_types(app, client):1124 @app.route("/text")1125 def from_text():1126 return "Hällo Wörld"11271128 @app.route("/bytes")1129 def from_bytes():1130 return "Hällo Wörld".encode()11311132 @app.route("/full_tuple")1133 def from_full_tuple():1134 return (1135 "Meh",1136 400,1137 {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1138 )11391140 @app.route("/text_headers")1141 def from_text_headers():1142 return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}11431144 @app.route("/text_status")1145 def from_text_status():1146 return "Hi, status!", 40011471148 @app.route("/response_headers")1149 def from_response_headers():1150 return (1151 flask.Response(1152 "Hello world", 404, {"Content-Type": "text/html", "X-Foo": "Baz"}1153 ),1154 {"Content-Type": "text/plain", "X-Foo": "Bar", "X-Bar": "Foo"},1155 )11561157 @app.route("/response_status")1158 def from_response_status():1159 return app.response_class("Hello world", 400), 50011601161 @app.route("/wsgi")1162 def from_wsgi():1163 return NotFound()11641165 @app.route("/dict")1166 def from_dict():1167 return {"foo": "bar"}, 20111681169 assert client.get("/text").data == "Hällo Wörld".encode()1170 assert client.get("/bytes").data == "Hällo Wörld".encode()11711172 rv = client.get("/full_tuple")1173 assert rv.data == b"Meh"1174 assert rv.headers["X-Foo"] == "Testing"1175 assert rv.status_code == 4001176 assert rv.mimetype == "text/plain"11771178 rv = client.get("/text_headers")1179 assert rv.data == b"Hello"1180 assert rv.headers["X-Foo"] == "Test"1181 assert rv.status_code == 2001182 assert rv.mimetype == "text/plain"11831184 rv = client.get("/text_status")1185 assert rv.data == b"Hi, status!"1186 assert rv.status_code == 4001187 assert rv.mimetype == "text/html"11881189 rv = client.get("/response_headers")1190 assert rv.data == b"Hello world"1191 assert rv.content_type == "text/plain"1192 assert rv.headers.getlist("X-Foo") == ["Bar"]1193 assert rv.headers["X-Bar"] == "Foo"1194 assert rv.status_code == 40411951196 rv = client.get("/response_status")1197 assert rv.data == b"Hello world"1198 assert rv.status_code == 50011991200 rv = client.get("/wsgi")1201 assert b"Not Found" in rv.data1202 assert rv.status_code == 40412031204 rv = client.get("/dict")1205 assert rv.json == {"foo": "bar"}1206 assert rv.status_code == 201120712081209def test_response_type_errors():1210 app = flask.Flask(__name__)1211 app.testing = True12121213 @app.route("/none")1214 def from_none():1215 pass12161217 @app.route("/small_tuple")1218 def from_small_tuple():1219 return ("Hello",)12201221 @app.route("/large_tuple")1222 def from_large_tuple():1223 return "Hello", 234, {"X-Foo": "Bar"}, "???"12241225 @app.route("/bad_type")1226 def from_bad_type():1227 return True12281229 @app.route("/bad_wsgi")1230 def from_bad_wsgi():1231 return lambda: None12321233 c = app.test_client()12341235 with pytest.raises(TypeError) as e:1236 c.get("/none")1237

Merge branch '2.1.x'David Lordbefore adoptionf976d5b

lines 1238–1240why, one step back
1238 assert "returned None" in str(e.value)
1239 assert "from_none" in str(e.value)1240

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

lines 1241–1243why, one step back
1241 with pytest.raises(TypeError) as e:
1242 c.get("/small_tuple")1243

Merge branch '2.1.x'David Lordbefore adoptionf976d5b

line 1244why, one step back
1244 assert "tuple must have the form" in str(e.value)

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

line 1245why, one step back
1245

Merge branch '2.1.x'David Lordbefore adoptionf976d5b

lines 1246–1248why, one step back
1246 with pytest.raises(TypeError):
1247 c.get("/large_tuple")1248

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

lines 1249–1251why, one step back
1249 with pytest.raises(TypeError) as e:
1250 c.get("/bad_type")1251

Merge branch '2.1.x'David Lordbefore adoptionf976d5b

line 1252why, one step back
1252 assert "it was a bool" in str(e.value)

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

line 1253why, one step back
1253

Merge branch '2.1.x'David Lordbefore adoptionf976d5b

lines 1254–1255why, one step back
1254 with pytest.raises(TypeError):
1255 c.get("/bad_wsgi")

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

line 1256why, one step back
1256

Merge branch '2.1.x'David Lordbefore adoptionf976d5b

line 1257why, one step back
1257

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

lines 1258–1525why, one step back
1258def test_make_response(app, req_ctx):
1259 rv = flask.make_response()1260 assert rv.status_code == 2001261 assert rv.data == b""1262 assert rv.mimetype == "text/html"12631264 rv = flask.make_response("Awesome")1265 assert rv.status_code == 2001266 assert rv.data == b"Awesome"1267 assert rv.mimetype == "text/html"12681269 rv = flask.make_response("W00t", 404)1270 assert rv.status_code == 4041271 assert rv.data == b"W00t"1272 assert rv.mimetype == "text/html"127312741275def test_make_response_with_response_instance(app, req_ctx):1276 rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1277 assert rv.status_code == 4001278 assert rv.data == b'{"msg":"W00t"}\n'1279 assert rv.mimetype == "application/json"12801281 rv = flask.make_response(flask.Response(""), 400)1282 assert rv.status_code == 4001283 assert rv.data == b""1284 assert rv.mimetype == "text/html"12851286 rv = flask.make_response(1287 flask.Response("", headers={"Content-Type": "text/html"}),1288 400,1289 [("X-Foo", "bar")],1290 )1291 assert rv.status_code == 4001292 assert rv.headers["Content-Type"] == "text/html"1293 assert rv.headers["X-Foo"] == "bar"129412951296def test_jsonify_no_prettyprint(app, req_ctx):1297 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1298 compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1299 uncompressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}13001301 rv = flask.make_response(flask.jsonify(uncompressed_msg), 200)1302 assert rv.data == compressed_msg130313041305def test_jsonify_prettyprint(app, req_ctx):1306 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1307 compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1308 pretty_response = (1309 b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'1310 )13111312 rv = flask.make_response(flask.jsonify(compressed_msg), 200)1313 assert rv.data == pretty_response131413151316def test_jsonify_mimetype(app, req_ctx):1317 app.config.update({"JSONIFY_MIMETYPE": "application/vnd.api+json"})1318 msg = {"msg": {"submsg": "W00t"}}1319 rv = flask.make_response(flask.jsonify(msg), 200)1320 assert rv.mimetype == "application/vnd.api+json"132113221323def test_json_dump_dataclass(app, req_ctx):1324 from dataclasses import make_dataclass13251326 Data = make_dataclass("Data", [("name", str)])1327 value = flask.json.dumps(Data("Flask"), app=app)1328 value = flask.json.loads(value, app=app)1329 assert value == {"name": "Flask"}133013311332def test_jsonify_args_and_kwargs_check(app, req_ctx):1333 with pytest.raises(TypeError) as e:1334 flask.jsonify("fake args", kwargs="fake")1335 assert "behavior undefined" in str(e.value)133613371338def test_url_generation(app, req_ctx):1339 @app.route("/hello/<name>", methods=["POST"])1340 def hello():1341 pass13421343 assert flask.url_for("hello", name="test x") == "/hello/test%20x"1344 assert (1345 flask.url_for("hello", name="test x", _external=True)1346 == "http://localhost/hello/test%20x"1347 )134813491350def test_build_error_handler(app):1351 # Test base case, a URL which results in a BuildError.1352 with app.test_request_context():1353 pytest.raises(BuildError, flask.url_for, "spam")13541355 # Verify the error is re-raised if not the current exception.1356 try:1357 with app.test_request_context():1358 flask.url_for("spam")1359 except BuildError as err:1360 error = err1361 try:1362 raise RuntimeError("Test case where BuildError is not current.")1363 except RuntimeError:1364 pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})13651366 # Test a custom handler.1367 def handler(error, endpoint, values):1368 # Just a test.1369 return "/test_handler/"13701371 app.url_build_error_handlers.append(handler)1372 with app.test_request_context():1373 assert flask.url_for("spam") == "/test_handler/"137413751376def test_build_error_handler_reraise(app):1377 # Test a custom handler which reraises the BuildError1378 def handler_raises_build_error(error, endpoint, values):1379 raise error13801381 app.url_build_error_handlers.append(handler_raises_build_error)13821383 with app.test_request_context():1384 pytest.raises(BuildError, flask.url_for, "not.existing")138513861387def test_url_for_passes_special_values_to_build_error_handler(app):1388 @app.url_build_error_handlers.append1389 def handler(error, endpoint, values):1390 assert values == {1391 "_external": False,1392 "_anchor": None,1393 "_method": None,1394 "_scheme": None,1395 }1396 return "handled"13971398 with app.test_request_context():1399 flask.url_for("/")140014011402def test_static_files(app, client):1403 rv = client.get("/static/index.html")1404 assert rv.status_code == 2001405 assert rv.data.strip() == b"<h1>Hello World!</h1>"1406 with app.test_request_context():1407 assert flask.url_for("static", filename="index.html") == "/static/index.html"1408 rv.close()140914101411def test_static_url_path():1412 app = flask.Flask(__name__, static_url_path="/foo")1413 app.testing = True1414 rv = app.test_client().get("/foo/index.html")1415 assert rv.status_code == 2001416 rv.close()14171418 with app.test_request_context():1419 assert flask.url_for("static", filename="index.html") == "/foo/index.html"142014211422def test_static_url_path_with_ending_slash():1423 app = flask.Flask(__name__, static_url_path="/foo/")1424 app.testing = True1425 rv = app.test_client().get("/foo/index.html")1426 assert rv.status_code == 2001427 rv.close()14281429 with app.test_request_context():1430 assert flask.url_for("static", filename="index.html") == "/foo/index.html"143114321433def test_static_url_empty_path(app):1434 app = flask.Flask(__name__, static_folder="", static_url_path="")1435 rv = app.test_client().open("/static/index.html", method="GET")1436 assert rv.status_code == 2001437 rv.close()143814391440def test_static_url_empty_path_default(app):1441 app = flask.Flask(__name__, static_folder="")1442 rv = app.test_client().open("/static/index.html", method="GET")1443 assert rv.status_code == 2001444 rv.close()144514461447def test_static_folder_with_pathlib_path(app):1448 from pathlib import Path14491450 app = flask.Flask(__name__, static_folder=Path("static"))1451 rv = app.test_client().open("/static/index.html", method="GET")1452 assert rv.status_code == 2001453 rv.close()145414551456def test_static_folder_with_ending_slash():1457 app = flask.Flask(__name__, static_folder="static/")14581459 @app.route("/<path:path>")1460 def catch_all(path):1461 return path14621463 rv = app.test_client().get("/catch/all")1464 assert rv.data == b"catch/all"146514661467def test_static_route_with_host_matching():1468 app = flask.Flask(__name__, host_matching=True, static_host="example.com")1469 c = app.test_client()1470 rv = c.get("http://example.com/static/index.html")1471 assert rv.status_code == 2001472 rv.close()1473 with app.test_request_context():1474 rv = flask.url_for("static", filename="index.html", _external=True)1475 assert rv == "http://example.com/static/index.html"1476 # Providing static_host without host_matching=True should error.1477 with pytest.raises(Exception):1478 flask.Flask(__name__, static_host="example.com")1479 # Providing host_matching=True with static_folder1480 # but without static_host should error.1481 with pytest.raises(Exception):1482 flask.Flask(__name__, host_matching=True)1483 # Providing host_matching=True without static_host1484 # but with static_folder=None should not error.1485 flask.Flask(__name__, host_matching=True, static_folder=None)148614871488def test_request_locals():1489 assert repr(flask.g) == "<LocalProxy unbound>"1490 assert not flask.g149114921493def test_server_name_subdomain():1494 app = flask.Flask(__name__, subdomain_matching=True)1495 client = app.test_client()14961497 @app.route("/")1498 def index():1499 return "default"15001501 @app.route("/", subdomain="foo")1502 def subdomain():1503 return "subdomain"15041505 app.config["SERVER_NAME"] = "dev.local:5000"1506 rv = client.get("/")1507 assert rv.data == b"default"15081509 rv = client.get("/", "http://dev.local:5000")1510 assert rv.data == b"default"15111512 rv = client.get("/", "https://dev.local:5000")1513 assert rv.data == b"default"15141515 app.config["SERVER_NAME"] = "dev.local:443"1516 rv = client.get("/", "https://dev.local")15171518 # Werkzeug 1.0 fixes matching https scheme with 443 port1519 if rv.status_code != 404:1520 assert rv.data == b"default"15211522 app.config["SERVER_NAME"] = "dev.local"1523 rv = client.get("/", "https://dev.local")1524 assert rv.data == b"default"1525

Merge branch '2.0.x'David Lordbefore adoptione37e871

lines 1526–1530why, one step back
1526 # suppress Werkzeug 0.15 warning about name mismatch
1527 with warnings.catch_warnings():1528 warnings.filterwarnings(1529 "ignore", "Current server name", UserWarning, "flask.app"1530 )

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

lines 1531–1537why, one step back
1531 rv = client.get("/", "http://foo.localhost")
1532 assert rv.status_code == 40415331534 rv = client.get("/", "http://foo.dev.local")1535 assert rv.data == b"subdomain"15361537

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

lines 1538–1539why, one step back
1538@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning")
1539@pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning")

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

lines 1540–1631why, one step back
1540def test_exception_propagation(app, client):
1541 def apprunner(config_key):1542 @app.route("/")1543 def index():1544 1 // 015451546 if config_key is not None:1547 app.config[config_key] = True1548 with pytest.raises(Exception):1549 client.get("/")1550 else:1551 assert client.get("/").status_code == 50015521553 # we have to run this test in an isolated thread because if the1554 # debug flag is set to true and an exception happens the context is1555 # not torn down. This causes other tests that run after this fail1556 # when they expect no exception on the stack.1557 for config_key in "TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None:1558 t = Thread(target=apprunner, args=(config_key,))1559 t.start()1560 t.join()156115621563@pytest.mark.parametrize("debug", [True, False])1564@pytest.mark.parametrize("use_debugger", [True, False])1565@pytest.mark.parametrize("use_reloader", [True, False])1566@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1567def test_werkzeug_passthrough_errors(1568 monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1569):1570 rv = {}15711572 # Mocks werkzeug.serving.run_simple method1573 def run_simple_mock(*args, **kwargs):1574 rv["passthrough_errors"] = kwargs.get("passthrough_errors")15751576 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1577 app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1578 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)157915801581def test_max_content_length(app, client):1582 app.config["MAX_CONTENT_LENGTH"] = 6415831584 @app.before_request1585 def always_first():1586 flask.request.form["myfile"]1587 AssertionError()15881589 @app.route("/accept", methods=["POST"])1590 def accept_file():1591 flask.request.form["myfile"]1592 AssertionError()15931594 @app.errorhandler(413)1595 def catcher(error):1596 return "42"15971598 rv = client.post("/accept", data={"myfile": "foo" * 100})1599 assert rv.data == b"42"160016011602def test_url_processors(app, client):1603 @app.url_defaults1604 def add_language_code(endpoint, values):1605 if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1606 endpoint, "lang_code"1607 ):1608 values.setdefault("lang_code", flask.g.lang_code)16091610 @app.url_value_preprocessor1611 def pull_lang_code(endpoint, values):1612 flask.g.lang_code = values.pop("lang_code", None)16131614 @app.route("/<lang_code>/")1615 def index():1616 return flask.url_for("about")16171618 @app.route("/<lang_code>/about")1619 def about():1620 return flask.url_for("something_else")16211622 @app.route("/foo")1623 def something_else():1624 return flask.url_for("about", lang_code="en")16251626 assert client.get("/de/").data == b"/de/about"1627 assert client.get("/de/about").data == b"/foo"1628 assert client.get("/foo").data == b"/en/about"162916301631def test_inject_blueprint_url_defaults(app):

Merge remote-tracking branch 'origin/2.0.x'David Lordbefore adoption4240ace

line 1632why, one step back
1632 bp = flask.Blueprint("foo", __name__, template_folder="template")

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

lines 1633–1644why, one step back
1633
1634 @bp.url_defaults1635 def bp_defaults(endpoint, values):1636 values["page"] = "login"16371638 @bp.route("/<page>")1639 def view(page):1640 pass16411642 app.register_blueprint(bp)16431644 values = dict()

Merge remote-tracking branch 'origin/2.0.x'David Lordbefore adoption4240ace

line 1645why, one step back
1645 app.inject_url_defaults("foo.view", values)

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

lines 1646–1649why, one step back
1646 expected = dict(page="login")
1647 assert values == expected16481649 with app.test_request_context("/somepage"):

Merge remote-tracking branch 'origin/2.0.x'David Lordbefore adoption4240ace

line 1650why, one step back
1650 url = flask.url_for("foo.view")

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

lines 1651–1673why, one step back
1651 expected = "/login"
1652 assert url == expected165316541655def test_nonascii_pathinfo(app, client):1656 @app.route("/киртест")1657 def index():1658 return "Hello World!"16591660 rv = client.get("/киртест")1661 assert rv.data == b"Hello World!"166216631664def test_debug_mode_complains_after_first_request(app, client):1665 app.debug = True16661667 @app.route("/")1668 def index():1669 return "Awesome"16701671 assert not app.got_first_request1672 assert client.get("/").data == b"Awesome"1673

Merge branch '2.1.x'David Lordbefore adoptionf976d5b

lines 1674–1675why, one step back
1674 with pytest.raises(AssertionError) as e:
1675 app.add_url_rule("/foo", endpoint="late")

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

lines 1676–1721why, one step back
1676
1677 assert "A setup function was called" in str(e.value)16781679 app.debug = False16801681 @app.route("/foo")1682 def working():1683 return "Meh"16841685 assert client.get("/foo").data == b"Meh"1686 assert app.got_first_request168716881689def test_before_first_request_functions(app, client):1690 got = []16911692 @app.before_first_request1693 def foo():1694 got.append(42)16951696 client.get("/")1697 assert got == [42]1698 client.get("/")1699 assert got == [42]1700 assert app.got_first_request170117021703def test_before_first_request_functions_concurrent(app, client):1704 got = []17051706 @app.before_first_request1707 def foo():1708 time.sleep(0.2)1709 got.append(42)17101711 def get_and_assert():1712 client.get("/")1713 assert got == [42]17141715 t = Thread(target=get_and_assert)1716 t.start()1717 get_and_assert()1718 t.join()1719 assert app.got_first_request17201721

Merge pull request #4492 from pallets/debug-messagesDavid Lordbefore adoptionce7b884

line 1722why, one step back
1722def test_routing_redirect_debugging(monkeypatch, app, client):

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

lines 1723–1726why, one step back
1723 @app.route("/foo/", methods=["GET", "POST"])
1724 def foo():1725 return "success"1726

Merge pull request #4492 from pallets/debug-messagesDavid Lordbefore adoptionce7b884

lines 1727–1729why, one step back
1727 app.debug = False
1728 rv = client.post("/foo", data={}, follow_redirects=True)1729 assert rv.data == b"success"

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

line 1730why, one step back
1730

Merge pull request #4492 from pallets/debug-messagesDavid Lordbefore adoptionce7b884

line 1731why, one step back
1731 app.debug = True

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

lines 1732–1735why, one step back
1732
1733 with client:1734 rv = client.post("/foo", data={}, follow_redirects=True)1735 assert rv.data == b"success"

Merge pull request #4492 from pallets/debug-messagesDavid Lordbefore adoptionce7b884

lines 1736–1744why, one step back
1736 rv = client.get("/foo", data={}, follow_redirects=True)
1737 assert rv.data == b"success"17381739 monkeypatch.setattr(RequestRedirect, "code", 301)17401741 with client, pytest.raises(AssertionError) as e:1742 client.post("/foo", data={})17431744 assert "canonical URL 'http://localhost/foo/'" in str(e.value)

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

lines 1745–1895why, one step back
1745
17461747def test_route_decorator_custom_endpoint(app, client):1748 app.debug = True17491750 @app.route("/foo/")1751 def foo():1752 return flask.request.endpoint17531754 @app.route("/bar/", endpoint="bar")1755 def for_bar():1756 return flask.request.endpoint17571758 @app.route("/bar/123", endpoint="123")1759 def for_bar_foo():1760 return flask.request.endpoint17611762 with app.test_request_context():1763 assert flask.url_for("foo") == "/foo/"1764 assert flask.url_for("bar") == "/bar/"1765 assert flask.url_for("123") == "/bar/123"17661767 assert client.get("/foo/").data == b"foo"1768 assert client.get("/bar/").data == b"bar"1769 assert client.get("/bar/123").data == b"123"177017711772def test_preserve_only_once(app, client):1773 app.debug = True17741775 @app.route("/fail")1776 def fail_func():1777 1 // 017781779 for _x in range(3):1780 with pytest.raises(ZeroDivisionError):1781 client.get("/fail")17821783 assert flask._request_ctx_stack.top is not None1784 assert flask._app_ctx_stack.top is not None1785 # implicit appctx disappears too1786 flask._request_ctx_stack.top.pop()1787 assert flask._request_ctx_stack.top is None1788 assert flask._app_ctx_stack.top is None178917901791def test_preserve_remembers_exception(app, client):1792 app.debug = True1793 errors = []17941795 @app.route("/fail")1796 def fail_func():1797 1 // 017981799 @app.route("/success")1800 def success_func():1801 return "Okay"18021803 @app.teardown_request1804 def teardown_handler(exc):1805 errors.append(exc)18061807 # After this failure we did not yet call the teardown handler1808 with pytest.raises(ZeroDivisionError):1809 client.get("/fail")1810 assert errors == []18111812 # But this request triggers it, and it's an error1813 client.get("/success")1814 assert len(errors) == 21815 assert isinstance(errors[0], ZeroDivisionError)18161817 # At this point another request does nothing.1818 client.get("/success")1819 assert len(errors) == 31820 assert errors[1] is None182118221823def test_get_method_on_g(app_ctx):1824 assert flask.g.get("x") is None1825 assert flask.g.get("x", 11) == 111826 flask.g.x = 421827 assert flask.g.get("x") == 421828 assert flask.g.x == 42182918301831def test_g_iteration_protocol(app_ctx):1832 flask.g.foo = 231833 flask.g.bar = 421834 assert "foo" in flask.g1835 assert "foos" not in flask.g1836 assert sorted(flask.g) == ["bar", "foo"]183718381839def test_subdomain_basic_support():1840 app = flask.Flask(__name__, subdomain_matching=True)1841 app.config["SERVER_NAME"] = "localhost.localdomain"1842 client = app.test_client()18431844 @app.route("/")1845 def normal_index():1846 return "normal index"18471848 @app.route("/", subdomain="test")1849 def test_index():1850 return "test index"18511852 rv = client.get("/", "http://localhost.localdomain/")1853 assert rv.data == b"normal index"18541855 rv = client.get("/", "http://test.localhost.localdomain/")1856 assert rv.data == b"test index"185718581859def test_subdomain_matching():1860 app = flask.Flask(__name__, subdomain_matching=True)1861 client = app.test_client()1862 app.config["SERVER_NAME"] = "localhost.localdomain"18631864 @app.route("/", subdomain="<user>")1865 def index(user):1866 return f"index for {user}"18671868 rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1869 assert rv.data == b"index for mitsuhiko"187018711872def test_subdomain_matching_with_ports():1873 app = flask.Flask(__name__, subdomain_matching=True)1874 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1875 client = app.test_client()18761877 @app.route("/", subdomain="<user>")1878 def index(user):1879 return f"index for {user}"18801881 rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1882 assert rv.data == b"index for mitsuhiko"188318841885@pytest.mark.parametrize("matching", (False, True))1886def test_subdomain_matching_other_name(matching):1887 app = flask.Flask(__name__, subdomain_matching=matching)1888 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1889 client = app.test_client()18901891 @app.route("/")1892 def index():1893 return "", 20418941895 # suppress Werkzeug 0.15 warning about name mismatch

Merge branch '2.0.x'David Lordbefore adoptione37e871

lines 1896–1899why, one step back
1896 with warnings.catch_warnings():
1897 warnings.filterwarnings(1898 "ignore", "Current server name", UserWarning, "flask.app"1899 )

update cache action to v2 (#3749)Ryuichi Watanabebefore adoptiona1fb8f1

lines 1900–2013why, one step back
1900 # ip address can't match name
1901 rv = client.get("/", "http://127.0.0.1:3000/")1902 assert rv.status_code == 404 if matching else 20419031904 # allow all subdomains if matching is disabled1905 rv = client.get("/", "http://www.localhost.localdomain:3000/")1906 assert rv.status_code == 404 if matching else 204190719081909def test_multi_route_rules(app, client):1910 @app.route("/")1911 @app.route("/<test>/")1912 def index(test="a"):1913 return test19141915 rv = client.open("/")1916 assert rv.data == b"a"1917 rv = client.open("/b/")1918 assert rv.data == b"b"191919201921def test_multi_route_class_views(app, client):1922 class View:1923 def __init__(self, app):1924 app.add_url_rule("/", "index", self.index)1925 app.add_url_rule("/<test>/", "index", self.index)19261927 def index(self, test="a"):1928 return test19291930 _ = View(app)1931 rv = client.open("/")1932 assert rv.data == b"a"1933 rv = client.open("/b/")1934 assert rv.data == b"b"193519361937def test_run_defaults(monkeypatch, app):1938 rv = {}19391940 # Mocks werkzeug.serving.run_simple method1941 def run_simple_mock(*args, **kwargs):1942 rv["result"] = "running..."19431944 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1945 app.run()1946 assert rv["result"] == "running..."194719481949def test_run_server_port(monkeypatch, app):1950 rv = {}19511952 # Mocks werkzeug.serving.run_simple method1953 def run_simple_mock(hostname, port, application, *args, **kwargs):1954 rv["result"] = f"running on {hostname}:{port} ..."19551956 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1957 hostname, port = "localhost", 80001958 app.run(hostname, port, debug=True)1959 assert rv["result"] == f"running on {hostname}:{port} ..."196019611962@pytest.mark.parametrize(1963 "host,port,server_name,expect_host,expect_port",1964 (1965 (None, None, "pocoo.org:8080", "pocoo.org", 8080),1966 ("localhost", None, "pocoo.org:8080", "localhost", 8080),1967 (None, 80, "pocoo.org:8080", "pocoo.org", 80),1968 ("localhost", 80, "pocoo.org:8080", "localhost", 80),1969 ("localhost", 0, "localhost:8080", "localhost", 0),1970 (None, None, "localhost:8080", "localhost", 8080),1971 (None, None, "localhost:0", "localhost", 0),1972 ),1973)1974def test_run_from_config(1975 monkeypatch, host, port, server_name, expect_host, expect_port, app1976):1977 def run_simple_mock(hostname, port, *args, **kwargs):1978 assert hostname == expect_host1979 assert port == expect_port19801981 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1982 app.config["SERVER_NAME"] = server_name1983 app.run(host, port)198419851986def test_max_cookie_size(app, client, recwarn):1987 app.config["MAX_COOKIE_SIZE"] = 10019881989 # outside app context, default to Werkzeug static value,1990 # which is also the default config1991 response = flask.Response()1992 default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1993 assert response.max_cookie_size == default19941995 # inside app context, use app config1996 with app.app_context():1997 assert flask.Response().max_cookie_size == 10019981999 @app.route("/")2000 def index():

The first 2,000 of 2,029 lines.