Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

1,958 lines · 52.4 KiB · Python

Last changed by

add json provider interfaceDavid Lordbefore adoption69f9845

History of this file

Take it

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

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1–4why, one step back
1import gc
2import re3import time4import uuid

Merge branch '2.0.x'David Lordbefore adoptione37e871

line 5why, one step back
5import warnings

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 6–7why, one step back
6import weakref
7from datetime import datetime

Merge pull request #4645 from kkirsche/patch-2David Lordbefore adoption7f2a0f4

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

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 9–18why, one step back
9from platform import python_implementation
10from threading import Thread1112import pytest13import werkzeug.serving14from werkzeug.exceptions import BadRequest15from werkzeug.exceptions import Forbidden16from werkzeug.exceptions import NotFound17from werkzeug.http import parse_date18from werkzeug.routing import BuildError

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

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

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 20–52why, one step back
20
21import flask222324require_cpython_gc = pytest.mark.skipif(25 python_implementation() != "CPython",26 reason="Requires CPython GC behavior",27)282930def test_options_work(app, client):31 @app.route("/", methods=["GET", "POST"])32 def index():33 return "Hello World"3435 rv = client.open("/", method="OPTIONS")36 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]37 assert rv.data == b""383940def test_options_on_multiple_rules(app, client):41 @app.route("/", methods=["GET", "POST"])42 def index():43 return "Hello World"4445 @app.route("/", methods=["PUT"])46 def index_put():47 return "Aha!"4849 rv = client.open("/", method="OPTIONS")50 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST", "PUT"]5152

Merge pull request #3907 from pgjones/sugarDavid Lordbefore adoption5fea7ca

lines 53–69why, one step back
53@pytest.mark.parametrize("method", ["get", "post", "put", "delete", "patch"])
54def test_method_route(app, client, method):55 method_route = getattr(app, method)56 client_method = getattr(client, method)5758 @method_route("/")59 def hello():60 return "Hello"6162 assert client_method("/").data == b"Hello"636465def test_method_route_no_methods(app):66 with pytest.raises(TypeError):67 app.get("/", methods=["GET", "POST"])6869

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 70–153why, one step back
70def test_provide_automatic_options_attr():
71 app = flask.Flask(__name__)7273 def index():74 return "Hello World!"7576 index.provide_automatic_options = False77 app.route("/")(index)78 rv = app.test_client().open("/", method="OPTIONS")79 assert rv.status_code == 4058081 app = flask.Flask(__name__)8283 def index2():84 return "Hello World!"8586 index2.provide_automatic_options = True87 app.route("/", methods=["OPTIONS"])(index2)88 rv = app.test_client().open("/", method="OPTIONS")89 assert sorted(rv.allow) == ["OPTIONS"]909192def test_provide_automatic_options_kwarg(app, client):93 def index():94 return flask.request.method9596 def more():97 return flask.request.method9899 app.add_url_rule("/", view_func=index, provide_automatic_options=False)100 app.add_url_rule(101 "/more",102 view_func=more,103 methods=["GET", "POST"],104 provide_automatic_options=False,105 )106 assert client.get("/").data == b"GET"107108 rv = client.post("/")109 assert rv.status_code == 405110 assert sorted(rv.allow) == ["GET", "HEAD"]111112 rv = client.open("/", method="OPTIONS")113 assert rv.status_code == 405114115 rv = client.head("/")116 assert rv.status_code == 200117 assert not rv.data # head truncates118 assert client.post("/more").data == b"POST"119 assert client.get("/more").data == b"GET"120121 rv = client.delete("/more")122 assert rv.status_code == 405123 assert sorted(rv.allow) == ["GET", "HEAD", "POST"]124125 rv = client.open("/more", method="OPTIONS")126 assert rv.status_code == 405127128129def test_request_dispatching(app, client):130 @app.route("/")131 def index():132 return flask.request.method133134 @app.route("/more", methods=["GET", "POST"])135 def more():136 return flask.request.method137138 assert client.get("/").data == b"GET"139 rv = client.post("/")140 assert rv.status_code == 405141 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]142 rv = client.head("/")143 assert rv.status_code == 200144 assert not rv.data # head truncates145 assert client.post("/more").data == b"POST"146 assert client.get("/more").data == b"GET"147 rv = client.delete("/more")148 assert rv.status_code == 405149 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]150151152def test_disallow_string_for_allowed_methods(app):153 with pytest.raises(TypeError):

Merge branch '2.1.x'David Lordbefore adoptionf976d5b

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

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 155–332why, one step back
155
156157def 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):194 from werkzeug.routing import Submount, Rule195196 app.url_map.add(197 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])198 )199200 def bar():201 return "bar"202203 def index():204 return "index"205206 app.view_functions["bar"] = bar207 app.view_functions["index"] = index208209 assert client.get("/foo/").data == b"index"210 assert client.get("/foo/bar").data == b"bar"211212213def test_endpoint_decorator(app, client):214 from werkzeug.routing import Submount, Rule215216 app.url_map.add(217 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])218 )219220 @app.endpoint("bar")221 def bar():222 return "bar"223224 @app.endpoint("index")225 def index():226 return "index"227228 assert client.get("/foo/").data == b"index"229 assert client.get("/foo/bar").data == b"bar"230231232def test_session(app, client):233 @app.route("/set", methods=["POST"])234 def set():235 assert not flask.session.accessed236 assert not flask.session.modified237 flask.session["value"] = flask.request.form["value"]238 assert flask.session.accessed239 assert flask.session.modified240 return "value set"241242 @app.route("/get")243 def get():244 assert not flask.session.accessed245 assert not flask.session.modified246 v = flask.session.get("value", "None")247 assert flask.session.accessed248 assert not flask.session.modified249 return v250251 assert client.post("/set", data={"value": "42"}).data == b"value set"252 assert client.get("/get").data == b"42"253254255def test_session_using_server_name(app, client):256 app.config.update(SERVER_NAME="example.com")257258 @app.route("/")259 def index():260 flask.session["testing"] = 42261 return "Hello World"262263 rv = client.get("/", "http://example.com/")264 assert "domain=.example.com" in rv.headers["set-cookie"].lower()265 assert "httponly" in rv.headers["set-cookie"].lower()266267268def test_session_using_server_name_and_port(app, client):269 app.config.update(SERVER_NAME="example.com:8080")270271 @app.route("/")272 def index():273 flask.session["testing"] = 42274 return "Hello World"275276 rv = client.get("/", "http://example.com:8080/")277 assert "domain=.example.com" in rv.headers["set-cookie"].lower()278 assert "httponly" in rv.headers["set-cookie"].lower()279280281def test_session_using_server_name_port_and_path(app, client):282 app.config.update(SERVER_NAME="example.com:8080", APPLICATION_ROOT="/foo")283284 @app.route("/")285 def index():286 flask.session["testing"] = 42287 return "Hello World"288289 rv = client.get("/", "http://example.com:8080/foo")290 assert "domain=example.com" in rv.headers["set-cookie"].lower()291 assert "path=/foo" in rv.headers["set-cookie"].lower()292 assert "httponly" in rv.headers["set-cookie"].lower()293294295def test_session_using_application_root(app, client):296 class PrefixPathMiddleware:297 def __init__(self, app, prefix):298 self.app = app299 self.prefix = prefix300301 def __call__(self, environ, start_response):302 environ["SCRIPT_NAME"] = self.prefix303 return self.app(environ, start_response)304305 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, "/bar")306 app.config.update(APPLICATION_ROOT="/bar")307308 @app.route("/")309 def index():310 flask.session["testing"] = 42311 return "Hello World"312313 rv = client.get("/", "http://example.com:8080/")314 assert "path=/bar" in rv.headers["set-cookie"].lower()315316317def test_session_using_session_settings(app, client):318 app.config.update(319 SERVER_NAME="www.example.com:8080",320 APPLICATION_ROOT="/test",321 SESSION_COOKIE_DOMAIN=".example.com",322 SESSION_COOKIE_HTTPONLY=False,323 SESSION_COOKIE_SECURE=True,324 SESSION_COOKIE_SAMESITE="Lax",325 SESSION_COOKIE_PATH="/",326 )327328 @app.route("/")329 def index():330 flask.session["testing"] = 42331 return "Hello World"332

Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db

lines 333–337why, one step back
333 @app.route("/clear")
334 def clear():335 flask.session.pop("testing", None)336 return "Goodbye World"337

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 338–439why, one step back
338 rv = client.get("/", "http://www.example.com:8080/test/")
339 cookie = rv.headers["set-cookie"].lower()340 assert "domain=.example.com" in cookie341 assert "path=/" in cookie342 assert "secure" in cookie343 assert "httponly" not in cookie344 assert "samesite" in cookie345346 rv = client.get("/clear", "http://www.example.com:8080/test/")347 cookie = rv.headers["set-cookie"].lower()348 assert "session=;" in cookie349 assert "domain=.example.com" in cookie350 assert "path=/" in cookie351 assert "secure" in cookie352 assert "samesite" in cookie353354355def test_session_using_samesite_attribute(app, client):356 @app.route("/")357 def index():358 flask.session["testing"] = 42359 return "Hello World"360361 app.config.update(SESSION_COOKIE_SAMESITE="invalid")362363 with pytest.raises(ValueError):364 client.get("/")365366 app.config.update(SESSION_COOKIE_SAMESITE=None)367 rv = client.get("/")368 cookie = rv.headers["set-cookie"].lower()369 assert "samesite" not in cookie370371 app.config.update(SESSION_COOKIE_SAMESITE="Strict")372 rv = client.get("/")373 cookie = rv.headers["set-cookie"].lower()374 assert "samesite=strict" in cookie375376 app.config.update(SESSION_COOKIE_SAMESITE="Lax")377 rv = client.get("/")378 cookie = rv.headers["set-cookie"].lower()379 assert "samesite=lax" in cookie380381382def test_session_localhost_warning(recwarn, app, client):383 app.config.update(SERVER_NAME="localhost:5000")384385 @app.route("/")386 def index():387 flask.session["testing"] = 42388 return "testing"389390 rv = client.get("/", "http://localhost:5000/")391 assert "domain" not in rv.headers["set-cookie"].lower()392 w = recwarn.pop(UserWarning)393 assert "'localhost' is not a valid cookie domain" in str(w.message)394395396def test_session_ip_warning(recwarn, app, client):397 app.config.update(SERVER_NAME="127.0.0.1:5000")398399 @app.route("/")400 def index():401 flask.session["testing"] = 42402 return "testing"403404 rv = client.get("/", "http://127.0.0.1:5000/")405 assert "domain=127.0.0.1" in rv.headers["set-cookie"].lower()406 w = recwarn.pop(UserWarning)407 assert "cookie domain is an IP" in str(w.message)408409410def test_missing_session(app):411 app.secret_key = None412413 def expect_exception(f, *args, **kwargs):414 e = pytest.raises(RuntimeError, f, *args, **kwargs)415 assert e.value.args and "session is unavailable" in e.value.args[0]416417 with app.test_request_context():418 assert flask.session.get("missing_key") is None419 expect_exception(flask.session.__setitem__, "foo", 42)420 expect_exception(flask.session.pop, "foo")421422423def test_session_expiration(app, client):424 permanent = True425426 @app.route("/")427 def index():428 flask.session["test"] = 42429 flask.session.permanent = permanent430 return ""431432 @app.route("/test")433 def test():434 return str(flask.session.permanent)435436 rv = client.get("/")437 assert "set-cookie" in rv.headers438 match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])439 expires = parse_date(match.group())

Merge pull request #4645 from kkirsche/patch-2David Lordbefore adoption7f2a0f4

line 440why, one step back
440 expected = datetime.now(timezone.utc) + app.permanent_session_lifetime

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 441–469why, one step back
441 assert expires.year == expected.year
442 assert expires.month == expected.month443 assert expires.day == expected.day444445 rv = client.get("/test")446 assert rv.data == b"True"447448 permanent = False449 rv = client.get("/")450 assert "set-cookie" in rv.headers451 match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])452 assert match is None453454455def test_session_stored_last(app, client):456 @app.after_request457 def modify_session(response):458 flask.session["foo"] = 42459 return response460461 @app.route("/")462 def dump_session_contents():463 return repr(flask.session.get("foo"))464465 assert client.get("/").data == b"None"466 assert client.get("/").data == b"42"467468469def test_session_special_types(app, client):

Merge pull request #4645 from kkirsche/patch-2David Lordbefore adoption7f2a0f4

line 470why, one step back
470 now = datetime.now(timezone.utc).replace(microsecond=0)

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 471–930why, one step back
471 the_uuid = uuid.uuid4()
472473 @app.route("/")474 def dump_session_contents():475 flask.session["t"] = (1, 2, 3)476 flask.session["b"] = b"\xff"477 flask.session["m"] = flask.Markup("<html>")478 flask.session["u"] = the_uuid479 flask.session["d"] = now480 flask.session["t_tag"] = {" t": "not-a-tuple"}481 flask.session["di_t_tag"] = {" t__": "not-a-tuple"}482 flask.session["di_tag"] = {" di": "not-a-dict"}483 return "", 204484485 with client:486 client.get("/")487 s = flask.session488 assert s["t"] == (1, 2, 3)489 assert type(s["b"]) == bytes490 assert s["b"] == b"\xff"491 assert type(s["m"]) == flask.Markup492 assert s["m"] == flask.Markup("<html>")493 assert s["u"] == the_uuid494 assert s["d"] == now495 assert s["t_tag"] == {" t": "not-a-tuple"}496 assert s["di_t_tag"] == {" t__": "not-a-tuple"}497 assert s["di_tag"] == {" di": "not-a-dict"}498499500def test_session_cookie_setting(app):501 is_permanent = True502503 @app.route("/bump")504 def bump():505 rv = flask.session["foo"] = flask.session.get("foo", 0) + 1506 flask.session.permanent = is_permanent507 return str(rv)508509 @app.route("/read")510 def read():511 return str(flask.session.get("foo", 0))512513 def run_test(expect_header):514 with app.test_client() as c:515 assert c.get("/bump").data == b"1"516 assert c.get("/bump").data == b"2"517 assert c.get("/bump").data == b"3"518519 rv = c.get("/read")520 set_cookie = rv.headers.get("set-cookie")521 assert (set_cookie is not None) == expect_header522 assert rv.data == b"3"523524 is_permanent = True525 app.config["SESSION_REFRESH_EACH_REQUEST"] = True526 run_test(expect_header=True)527528 is_permanent = True529 app.config["SESSION_REFRESH_EACH_REQUEST"] = False530 run_test(expect_header=False)531532 is_permanent = False533 app.config["SESSION_REFRESH_EACH_REQUEST"] = True534 run_test(expect_header=False)535536 is_permanent = False537 app.config["SESSION_REFRESH_EACH_REQUEST"] = False538 run_test(expect_header=False)539540541def test_session_vary_cookie(app, client):542 @app.route("/set")543 def set_session():544 flask.session["test"] = "test"545 return ""546547 @app.route("/get")548 def get():549 return flask.session.get("test")550551 @app.route("/getitem")552 def getitem():553 return flask.session["test"]554555 @app.route("/setdefault")556 def setdefault():557 return flask.session.setdefault("test", "default")558559 @app.route("/vary-cookie-header-set")560 def vary_cookie_header_set():561 response = flask.Response()562 response.vary.add("Cookie")563 flask.session["test"] = "test"564 return response565566 @app.route("/vary-header-set")567 def vary_header_set():568 response = flask.Response()569 response.vary.update(("Accept-Encoding", "Accept-Language"))570 flask.session["test"] = "test"571 return response572573 @app.route("/no-vary-header")574 def no_vary_header():575 return ""576577 def expect(path, header_value="Cookie"):578 rv = client.get(path)579580 if header_value:581 # The 'Vary' key should exist in the headers only once.582 assert len(rv.headers.get_all("Vary")) == 1583 assert rv.headers["Vary"] == header_value584 else:585 assert "Vary" not in rv.headers586587 expect("/set")588 expect("/get")589 expect("/getitem")590 expect("/setdefault")591 expect("/vary-cookie-header-set")592 expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")593 expect("/no-vary-header", None)594595596def test_flashes(app, req_ctx):597 assert not flask.session.modified598 flask.flash("Zap")599 flask.session.modified = False600 flask.flash("Zip")601 assert flask.session.modified602 assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]603604605def test_extended_flashing(app):606 # Be sure app.testing=True below, else tests can fail silently.607 #608 # Specifically, if app.testing is not set to True, the AssertionErrors609 # in the view functions will cause a 500 response to the test client610 # instead of propagating exceptions.611612 @app.route("/")613 def index():614 flask.flash("Hello World")615 flask.flash("Hello World", "error")616 flask.flash(flask.Markup("<em>Testing</em>"), "warning")617 return ""618619 @app.route("/test/")620 def test():621 messages = flask.get_flashed_messages()622 assert list(messages) == [623 "Hello World",624 "Hello World",625 flask.Markup("<em>Testing</em>"),626 ]627 return ""628629 @app.route("/test_with_categories/")630 def test_with_categories():631 messages = flask.get_flashed_messages(with_categories=True)632 assert len(messages) == 3633 assert list(messages) == [634 ("message", "Hello World"),635 ("error", "Hello World"),636 ("warning", flask.Markup("<em>Testing</em>")),637 ]638 return ""639640 @app.route("/test_filter/")641 def test_filter():642 messages = flask.get_flashed_messages(643 category_filter=["message"], with_categories=True644 )645 assert list(messages) == [("message", "Hello World")]646 return ""647648 @app.route("/test_filters/")649 def test_filters():650 messages = flask.get_flashed_messages(651 category_filter=["message", "warning"], with_categories=True652 )653 assert list(messages) == [654 ("message", "Hello World"),655 ("warning", flask.Markup("<em>Testing</em>")),656 ]657 return ""658659 @app.route("/test_filters_without_returning_categories/")660 def test_filters2():661 messages = flask.get_flashed_messages(category_filter=["message", "warning"])662 assert len(messages) == 2663 assert messages[0] == "Hello World"664 assert messages[1] == flask.Markup("<em>Testing</em>")665 return ""666667 # Create new test client on each test to clean flashed messages.668669 client = app.test_client()670 client.get("/")671 client.get("/test_with_categories/")672673 client = app.test_client()674 client.get("/")675 client.get("/test_filter/")676677 client = app.test_client()678 client.get("/")679 client.get("/test_filters/")680681 client = app.test_client()682 client.get("/")683 client.get("/test_filters_without_returning_categories/")684685686def test_request_processing(app, client):687 evts = []688689 @app.before_request690 def before_request():691 evts.append("before")692693 @app.after_request694 def after_request(response):695 response.data += b"|after"696 evts.append("after")697 return response698699 @app.route("/")700 def index():701 assert "before" in evts702 assert "after" not in evts703 return "request"704705 assert "after" not in evts706 rv = client.get("/").data707 assert "after" in evts708 assert rv == b"request|after"709710711def test_request_preprocessing_early_return(app, client):712 evts = []713714 @app.before_request715 def before_request1():716 evts.append(1)717718 @app.before_request719 def before_request2():720 evts.append(2)721 return "hello"722723 @app.before_request724 def before_request3():725 evts.append(3)726 return "bye"727728 @app.route("/")729 def index():730 evts.append("index")731 return "damnit"732733 rv = client.get("/").data.strip()734 assert rv == b"hello"735 assert evts == [1, 2]736737738def test_after_request_processing(app, client):739 @app.route("/")740 def index():741 @flask.after_this_request742 def foo(response):743 response.headers["X-Foo"] = "a header"744 return response745746 return "Test"747748 resp = client.get("/")749 assert resp.status_code == 200750 assert resp.headers["X-Foo"] == "a header"751752753def test_teardown_request_handler(app, client):754 called = []755756 @app.teardown_request757 def teardown_request(exc):758 called.append(True)759 return "Ignored"760761 @app.route("/")762 def root():763 return "Response"764765 rv = client.get("/")766 assert rv.status_code == 200767 assert b"Response" in rv.data768 assert len(called) == 1769770771def test_teardown_request_handler_debug_mode(app, client):772 called = []773774 @app.teardown_request775 def teardown_request(exc):776 called.append(True)777 return "Ignored"778779 @app.route("/")780 def root():781 return "Response"782783 rv = client.get("/")784 assert rv.status_code == 200785 assert b"Response" in rv.data786 assert len(called) == 1787788789def test_teardown_request_handler_error(app, client):790 called = []791 app.testing = False792793 @app.teardown_request794 def teardown_request1(exc):795 assert type(exc) == ZeroDivisionError796 called.append(True)797 # This raises a new error and blows away sys.exc_info(), so we can798 # test that all teardown_requests get passed the same original799 # exception.800 try:801 raise TypeError()802 except Exception:803 pass804805 @app.teardown_request806 def teardown_request2(exc):807 assert type(exc) == ZeroDivisionError808 called.append(True)809 # This raises a new error and blows away sys.exc_info(), so we can810 # test that all teardown_requests get passed the same original811 # exception.812 try:813 raise TypeError()814 except Exception:815 pass816817 @app.route("/")818 def fails():819 1 // 0820821 rv = client.get("/")822 assert rv.status_code == 500823 assert b"Internal Server Error" in rv.data824 assert len(called) == 2825826827def test_before_after_request_order(app, client):828 called = []829830 @app.before_request831 def before1():832 called.append(1)833834 @app.before_request835 def before2():836 called.append(2)837838 @app.after_request839 def after1(response):840 called.append(4)841 return response842843 @app.after_request844 def after2(response):845 called.append(3)846 return response847848 @app.teardown_request849 def finish1(exc):850 called.append(6)851852 @app.teardown_request853 def finish2(exc):854 called.append(5)855856 @app.route("/")857 def index():858 return "42"859860 rv = client.get("/")861 assert rv.data == b"42"862 assert called == [1, 2, 3, 4, 5, 6]863864865def test_error_handling(app, client):866 app.testing = False867868 @app.errorhandler(404)869 def not_found(e):870 return "not found", 404871872 @app.errorhandler(500)873 def internal_server_error(e):874 return "internal server error", 500875876 @app.errorhandler(Forbidden)877 def forbidden(e):878 return "forbidden", 403879880 @app.route("/")881 def index():882 flask.abort(404)883884 @app.route("/error")885 def error():886 1 // 0887888 @app.route("/forbidden")889 def error2():890 flask.abort(403)891892 rv = client.get("/")893 assert rv.status_code == 404894 assert rv.data == b"not found"895 rv = client.get("/error")896 assert rv.status_code == 500897 assert b"internal server error" == rv.data898 rv = client.get("/forbidden")899 assert rv.status_code == 403900 assert b"forbidden" == rv.data901902903def test_error_handling_processing(app, client):904 app.testing = False905906 @app.errorhandler(500)907 def internal_server_error(e):908 return "internal server error", 500909910 @app.route("/")911 def broken_func():912 1 // 0913914 @app.after_request915 def after_request(resp):916 resp.mimetype = "text/x-special"917 return resp918919 resp = client.get("/")920 assert resp.mimetype == "text/x-special"921 assert resp.data == b"internal server error"922923924def test_baseexception_error_handling(app, client):925 app.testing = False926927 @app.route("/")928 def broken_func():929 raise KeyboardInterrupt()930

Merge pull request #4666 from pallets/debug-contextDavid Lordbefore adoption6916697

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

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 933–1029why, one step back
933
934935def test_before_request_and_routing_errors(app, client):936 @app.before_request937 def attach_something():938 flask.g.something = "value"939940 @app.errorhandler(404)941 def return_something(error):942 return flask.g.something, 404943944 rv = client.get("/")945 assert rv.status_code == 404946 assert rv.data == b"value"947948949def test_user_error_handling(app, client):950 class MyException(Exception):951 pass952953 @app.errorhandler(MyException)954 def handle_my_exception(e):955 assert isinstance(e, MyException)956 return "42"957958 @app.route("/")959 def index():960 raise MyException()961962 assert client.get("/").data == b"42"963964965def test_http_error_subclass_handling(app, client):966 class ForbiddenSubclass(Forbidden):967 pass968969 @app.errorhandler(ForbiddenSubclass)970 def handle_forbidden_subclass(e):971 assert isinstance(e, ForbiddenSubclass)972 return "banana"973974 @app.errorhandler(403)975 def handle_403(e):976 assert not isinstance(e, ForbiddenSubclass)977 assert isinstance(e, Forbidden)978 return "apple"979980 @app.route("/1")981 def index1():982 raise ForbiddenSubclass()983984 @app.route("/2")985 def index2():986 flask.abort(403)987988 @app.route("/3")989 def index3():990 raise Forbidden()991992 assert client.get("/1").data == b"banana"993 assert client.get("/2").data == b"apple"994 assert client.get("/3").data == b"apple"995996997def test_errorhandler_precedence(app, client):998 class E1(Exception):999 pass10001001 class E2(Exception):1002 pass10031004 class E3(E1, E2):1005 pass10061007 @app.errorhandler(E2)1008 def handle_e2(e):1009 return "E2"10101011 @app.errorhandler(Exception)1012 def handle_exception(e):1013 return "Exception"10141015 @app.route("/E1")1016 def raise_e1():1017 raise E110181019 @app.route("/E3")1020 def raise_e3():1021 raise E310221023 rv = client.get("/E1")1024 assert rv.data == b"Exception"10251026 rv = client.get("/E3")1027 assert rv.data == b"E2"10281029

Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db

lines 1030–1037why, one step back
1030@pytest.mark.parametrize(
1031 ("debug", "trap", "expect_key", "expect_abort"),1032 [(False, None, True, True), (True, None, False, True), (False, True, False, False)],1033)1034def test_trap_bad_request_key_error(app, client, debug, trap, expect_key, expect_abort):1035 app.config["DEBUG"] = debug1036 app.config["TRAP_BAD_REQUEST_ERRORS"] = trap1037

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1038–1045why, one step back
1038 @app.route("/key")
1039 def fail():1040 flask.request.form["missing_key"]10411042 @app.route("/abort")1043 def allow_abort():1044 flask.abort(400)1045

Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db

lines 1046–1052why, one step back
1046 if expect_key:
1047 rv = client.get("/key")1048 assert rv.status_code == 4001049 assert b"missing_key" not in rv.data1050 else:1051 with pytest.raises(KeyError) as exc_info:1052 client.get("/key")

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

line 1053why, one step back
1053

Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db

lines 1054–1055why, one step back
1054 assert exc_info.errisinstance(BadRequest)
1055 assert "missing_key" in exc_info.value.get_description()

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

line 1056why, one step back
1056

Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db

lines 1057–1062why, one step back
1057 if expect_abort:
1058 rv = client.get("/abort")1059 assert rv.status_code == 4001060 else:1061 with pytest.raises(BadRequest):1062 client.get("/abort")

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1063–1112why, one step back
1063
10641065def 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"].filename1112

Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae

lines 1113–1116why, one step back
1113 with pytest.raises(DebugFilesKeyError) as e:
1114 client.post("/fail", data={"foo": "index.txt"})1115 assert "no file contents were transmitted" in str(e.value)1116 assert "This was submitted: 'index.txt'" in str(e.value)

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1117–1164why, one step back
1117
11181119def test_response_types(app, client):1120 @app.route("/text")1121 def from_text():1122 return "Hällo Wörld"11231124 @app.route("/bytes")1125 def from_bytes():1126 return "Hällo Wörld".encode()11271128 @app.route("/full_tuple")1129 def from_full_tuple():1130 return (1131 "Meh",1132 400,1133 {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1134 )11351136 @app.route("/text_headers")1137 def from_text_headers():1138 return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}11391140 @app.route("/text_status")1141 def from_text_status():1142 return "Hi, status!", 40011431144 @app.route("/response_headers")1145 def from_response_headers():1146 return (1147 flask.Response(1148 "Hello world", 404, {"Content-Type": "text/html", "X-Foo": "Baz"}1149 ),1150 {"Content-Type": "text/plain", "X-Foo": "Bar", "X-Bar": "Foo"},1151 )11521153 @app.route("/response_status")1154 def from_response_status():1155 return app.response_class("Hello world", 400), 50011561157 @app.route("/wsgi")1158 def from_wsgi():1159 return NotFound()11601161 @app.route("/dict")1162 def from_dict():1163 return {"foo": "bar"}, 2011164

Merge pull request #4672 from greyli/return-listDavid Lordbefore adoption559a845

lines 1165–1168why, one step back
1165 @app.route("/list")
1166 def from_list():1167 return ["foo", "bar"], 2011168

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1169–1205why, one step back
1169 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"}

Merge pull request #4672 from greyli/return-listDavid Lordbefore adoption559a845

lines 1206–1209why, one step back
1206 assert rv.status_code == 201
12071208 rv = client.get("/list")1209 assert rv.json == ["foo", "bar"]

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1210–1241why, one step back
1210 assert rv.status_code == 201
121112121213def test_response_type_errors():1214 app = flask.Flask(__name__)1215 app.testing = True12161217 @app.route("/none")1218 def from_none():1219 pass12201221 @app.route("/small_tuple")1222 def from_small_tuple():1223 return ("Hello",)12241225 @app.route("/large_tuple")1226 def from_large_tuple():1227 return "Hello", 234, {"X-Foo": "Bar"}, "???"12281229 @app.route("/bad_type")1230 def from_bad_type():1231 return True12321233 @app.route("/bad_wsgi")1234 def from_bad_wsgi():1235 return lambda: None12361237 c = app.test_client()12381239 with pytest.raises(TypeError) as e:1240 c.get("/none")1241

Merge branch '2.1.x'David Lordbefore adoptionf976d5b

lines 1242–1244why, one step back
1242 assert "returned None" in str(e.value)
1243 assert "from_none" in str(e.value)1244

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1245–1247why, one step back
1245 with pytest.raises(TypeError) as e:
1246 c.get("/small_tuple")1247

Merge branch '2.1.x'David Lordbefore adoptionf976d5b

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

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

line 1249why, one step back
1249

Merge branch '2.1.x'David Lordbefore adoptionf976d5b

lines 1250–1252why, one step back
1250 with pytest.raises(TypeError):
1251 c.get("/large_tuple")1252

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

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

Merge branch '2.1.x'David Lordbefore adoptionf976d5b

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

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

line 1257why, one step back
1257

Merge branch '2.1.x'David Lordbefore adoptionf976d5b

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

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

line 1260why, one step back
1260

Merge branch '2.1.x'David Lordbefore adoptionf976d5b

line 1261why, one step back
1261

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1262–1277why, one step back
1262def test_make_response(app, req_ctx):
1263 rv = flask.make_response()1264 assert rv.status_code == 2001265 assert rv.data == b""1266 assert rv.mimetype == "text/html"12671268 rv = flask.make_response("Awesome")1269 assert rv.status_code == 2001270 assert rv.data == b"Awesome"1271 assert rv.mimetype == "text/html"12721273 rv = flask.make_response("W00t", 404)1274 assert rv.status_code == 4041275 assert rv.data == b"W00t"1276 assert rv.mimetype == "text/html"1277

Merge pull request #4629 from pgjones/generateDavid Lordbefore adoptionab36542

lines 1278–1282why, one step back
1278 rv = flask.make_response(c for c in "Hello")
1279 assert rv.status_code == 2001280 assert rv.data == b"Hello"1281 assert rv.mimetype == "text/html"1282

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1283–1304why, one step back
1283
1284def test_make_response_with_response_instance(app, req_ctx):1285 rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1286 assert rv.status_code == 4001287 assert rv.data == b'{"msg":"W00t"}\n'1288 assert rv.mimetype == "application/json"12891290 rv = flask.make_response(flask.Response(""), 400)1291 assert rv.status_code == 4001292 assert rv.data == b""1293 assert rv.mimetype == "text/html"12941295 rv = flask.make_response(1296 flask.Response("", headers={"Content-Type": "text/html"}),1297 400,1298 [("X-Foo", "bar")],1299 )1300 assert rv.status_code == 4001301 assert rv.headers["Content-Type"] == "text/html"1302 assert rv.headers["X-Foo"] == "bar"13031304

add json provider interfaceDavid Lordbefore adoption69f9845

lines 1305–1311why, one step back
1305@pytest.mark.parametrize("compact", [True, False])
1306def test_jsonify_no_prettyprint(app, compact):1307 app.json.compact = compact1308 rv = app.json.response({"msg": {"submsg": "W00t"}, "msg2": "foobar"})1309 data = rv.data.strip()1310 assert (b" " not in data) is compact1311 assert (b"\n" not in data) is compact

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1312–1314why, one step back
1312
13131314def test_jsonify_mimetype(app, req_ctx):

add json provider interfaceDavid Lordbefore adoption69f9845

line 1315why, one step back
1315 app.json.mimetype = "application/vnd.api+json"

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1316–1324why, one step back
1316 msg = {"msg": {"submsg": "W00t"}}
1317 rv = flask.make_response(flask.jsonify(msg), 200)1318 assert rv.mimetype == "application/vnd.api+json"131913201321def test_json_dump_dataclass(app, req_ctx):1322 from dataclasses import make_dataclass13231324 Data = make_dataclass("Data", [("name", str)])

add json provider interfaceDavid Lordbefore adoption69f9845

lines 1325–1326why, one step back
1325 value = app.json.dumps(Data("Flask"))
1326 value = app.json.loads(value)

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1327–1332why, one step back
1327 assert value == {"name": "Flask"}
132813291330def test_jsonify_args_and_kwargs_check(app, req_ctx):1331 with pytest.raises(TypeError) as e:1332 flask.jsonify("fake args", kwargs="fake")

add json provider interfaceDavid Lordbefore adoption69f9845

line 1333why, one step back
1333 assert "args or kwargs" in str(e.value)

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1334–1523why, one step back
1334
13351336def test_url_generation(app, req_ctx):1337 @app.route("/hello/<name>", methods=["POST"])1338 def hello():1339 pass13401341 assert flask.url_for("hello", name="test x") == "/hello/test%20x"1342 assert (1343 flask.url_for("hello", name="test x", _external=True)1344 == "http://localhost/hello/test%20x"1345 )134613471348def test_build_error_handler(app):1349 # Test base case, a URL which results in a BuildError.1350 with app.test_request_context():1351 pytest.raises(BuildError, flask.url_for, "spam")13521353 # Verify the error is re-raised if not the current exception.1354 try:1355 with app.test_request_context():1356 flask.url_for("spam")1357 except BuildError as err:1358 error = err1359 try:1360 raise RuntimeError("Test case where BuildError is not current.")1361 except RuntimeError:1362 pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})13631364 # Test a custom handler.1365 def handler(error, endpoint, values):1366 # Just a test.1367 return "/test_handler/"13681369 app.url_build_error_handlers.append(handler)1370 with app.test_request_context():1371 assert flask.url_for("spam") == "/test_handler/"137213731374def test_build_error_handler_reraise(app):1375 # Test a custom handler which reraises the BuildError1376 def handler_raises_build_error(error, endpoint, values):1377 raise error13781379 app.url_build_error_handlers.append(handler_raises_build_error)13801381 with app.test_request_context():1382 pytest.raises(BuildError, flask.url_for, "not.existing")138313841385def test_url_for_passes_special_values_to_build_error_handler(app):1386 @app.url_build_error_handlers.append1387 def handler(error, endpoint, values):1388 assert values == {1389 "_external": False,1390 "_anchor": None,1391 "_method": None,1392 "_scheme": None,1393 }1394 return "handled"13951396 with app.test_request_context():1397 flask.url_for("/")139813991400def test_static_files(app, client):1401 rv = client.get("/static/index.html")1402 assert rv.status_code == 2001403 assert rv.data.strip() == b"<h1>Hello World!</h1>"1404 with app.test_request_context():1405 assert flask.url_for("static", filename="index.html") == "/static/index.html"1406 rv.close()140714081409def test_static_url_path():1410 app = flask.Flask(__name__, static_url_path="/foo")1411 app.testing = True1412 rv = app.test_client().get("/foo/index.html")1413 assert rv.status_code == 2001414 rv.close()14151416 with app.test_request_context():1417 assert flask.url_for("static", filename="index.html") == "/foo/index.html"141814191420def test_static_url_path_with_ending_slash():1421 app = flask.Flask(__name__, static_url_path="/foo/")1422 app.testing = True1423 rv = app.test_client().get("/foo/index.html")1424 assert rv.status_code == 2001425 rv.close()14261427 with app.test_request_context():1428 assert flask.url_for("static", filename="index.html") == "/foo/index.html"142914301431def test_static_url_empty_path(app):1432 app = flask.Flask(__name__, static_folder="", static_url_path="")1433 rv = app.test_client().open("/static/index.html", method="GET")1434 assert rv.status_code == 2001435 rv.close()143614371438def test_static_url_empty_path_default(app):1439 app = flask.Flask(__name__, static_folder="")1440 rv = app.test_client().open("/static/index.html", method="GET")1441 assert rv.status_code == 2001442 rv.close()144314441445def test_static_folder_with_pathlib_path(app):1446 from pathlib import Path14471448 app = flask.Flask(__name__, static_folder=Path("static"))1449 rv = app.test_client().open("/static/index.html", method="GET")1450 assert rv.status_code == 2001451 rv.close()145214531454def test_static_folder_with_ending_slash():1455 app = flask.Flask(__name__, static_folder="static/")14561457 @app.route("/<path:path>")1458 def catch_all(path):1459 return path14601461 rv = app.test_client().get("/catch/all")1462 assert rv.data == b"catch/all"146314641465def test_static_route_with_host_matching():1466 app = flask.Flask(__name__, host_matching=True, static_host="example.com")1467 c = app.test_client()1468 rv = c.get("http://example.com/static/index.html")1469 assert rv.status_code == 2001470 rv.close()1471 with app.test_request_context():1472 rv = flask.url_for("static", filename="index.html", _external=True)1473 assert rv == "http://example.com/static/index.html"1474 # Providing static_host without host_matching=True should error.1475 with pytest.raises(Exception):1476 flask.Flask(__name__, static_host="example.com")1477 # Providing host_matching=True with static_folder1478 # but without static_host should error.1479 with pytest.raises(Exception):1480 flask.Flask(__name__, host_matching=True)1481 # Providing host_matching=True without static_host1482 # but with static_folder=None should not error.1483 flask.Flask(__name__, host_matching=True, static_folder=None)148414851486def test_request_locals():1487 assert repr(flask.g) == "<LocalProxy unbound>"1488 assert not flask.g148914901491def test_server_name_subdomain():1492 app = flask.Flask(__name__, subdomain_matching=True)1493 client = app.test_client()14941495 @app.route("/")1496 def index():1497 return "default"14981499 @app.route("/", subdomain="foo")1500 def subdomain():1501 return "subdomain"15021503 app.config["SERVER_NAME"] = "dev.local:5000"1504 rv = client.get("/")1505 assert rv.data == b"default"15061507 rv = client.get("/", "http://dev.local:5000")1508 assert rv.data == b"default"15091510 rv = client.get("/", "https://dev.local:5000")1511 assert rv.data == b"default"15121513 app.config["SERVER_NAME"] = "dev.local:443"1514 rv = client.get("/", "https://dev.local")15151516 # Werkzeug 1.0 fixes matching https scheme with 443 port1517 if rv.status_code != 404:1518 assert rv.data == b"default"15191520 app.config["SERVER_NAME"] = "dev.local"1521 rv = client.get("/", "https://dev.local")1522 assert rv.data == b"default"1523

Merge branch '2.0.x'David Lordbefore adoptione37e871

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

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1529–1535why, one step back
1529 rv = client.get("/", "http://foo.localhost")
1530 assert rv.status_code == 40415311532 rv = client.get("/", "http://foo.dev.local")1533 assert rv.data == b"subdomain"15341535

Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae

lines 1536–1538why, one step back
1536@pytest.mark.parametrize("key", ["TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None])
1537def test_exception_propagation(app, client, key):1538 app.testing = False

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

line 1539why, one step back
1539

Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae

lines 1540–1542why, one step back
1540 @app.route("/")
1541 def index():1542 1 // 0

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

line 1543why, one step back
1543

Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae

lines 1544–1550why, one step back
1544 if key is not None:
1545 app.config[key] = True15461547 with pytest.raises(ZeroDivisionError):1548 client.get("/")1549 else:1550 assert client.get("/").status_code == 500

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1551–1621why, one step back
1551
15521553@pytest.mark.parametrize("debug", [True, False])1554@pytest.mark.parametrize("use_debugger", [True, False])1555@pytest.mark.parametrize("use_reloader", [True, False])1556@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1557def test_werkzeug_passthrough_errors(1558 monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1559):1560 rv = {}15611562 # Mocks werkzeug.serving.run_simple method1563 def run_simple_mock(*args, **kwargs):1564 rv["passthrough_errors"] = kwargs.get("passthrough_errors")15651566 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1567 app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1568 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)156915701571def test_max_content_length(app, client):1572 app.config["MAX_CONTENT_LENGTH"] = 6415731574 @app.before_request1575 def always_first():1576 flask.request.form["myfile"]1577 AssertionError()15781579 @app.route("/accept", methods=["POST"])1580 def accept_file():1581 flask.request.form["myfile"]1582 AssertionError()15831584 @app.errorhandler(413)1585 def catcher(error):1586 return "42"15871588 rv = client.post("/accept", data={"myfile": "foo" * 100})1589 assert rv.data == b"42"159015911592def test_url_processors(app, client):1593 @app.url_defaults1594 def add_language_code(endpoint, values):1595 if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1596 endpoint, "lang_code"1597 ):1598 values.setdefault("lang_code", flask.g.lang_code)15991600 @app.url_value_preprocessor1601 def pull_lang_code(endpoint, values):1602 flask.g.lang_code = values.pop("lang_code", None)16031604 @app.route("/<lang_code>/")1605 def index():1606 return flask.url_for("about")16071608 @app.route("/<lang_code>/about")1609 def about():1610 return flask.url_for("something_else")16111612 @app.route("/foo")1613 def something_else():1614 return flask.url_for("about", lang_code="en")16151616 assert client.get("/de/").data == b"/de/about"1617 assert client.get("/de/about").data == b"/foo"1618 assert client.get("/foo").data == b"/en/about"161916201621def test_inject_blueprint_url_defaults(app):

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

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

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1623–1634why, one step back
1623
1624 @bp.url_defaults1625 def bp_defaults(endpoint, values):1626 values["page"] = "login"16271628 @bp.route("/<page>")1629 def view(page):1630 pass16311632 app.register_blueprint(bp)16331634 values = dict()

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

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

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1636–1639why, one step back
1636 expected = dict(page="login")
1637 assert values == expected16381639 with app.test_request_context("/somepage"):

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

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

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1641–1653why, one step back
1641 expected = "/login"
1642 assert url == expected164316441645def test_nonascii_pathinfo(app, client):1646 @app.route("/киртест")1647 def index():1648 return "Hello World!"16491650 rv = client.get("/киртест")1651 assert rv.data == b"Hello World!"16521653

Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db

line 1654why, one step back
1654def test_no_setup_after_first_request(app, client):

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1655–1663why, one step back
1655 app.debug = True
16561657 @app.route("/")1658 def index():1659 return "Awesome"16601661 assert not app.got_first_request1662 assert client.get("/").data == b"Awesome"1663

Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db

line 1664why, one step back
1664 with pytest.raises(AssertionError) as exc_info:

Merge branch '2.1.x'David Lordbefore adoptionf976d5b

line 1665why, one step back
1665 app.add_url_rule("/foo", endpoint="late")

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

line 1666why, one step back
1666

Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db

line 1667why, one step back
1667 assert "setup method 'add_url_rule'" in str(exc_info.value)

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1668–1672why, one step back
1668
16691670def test_before_first_request_functions(app, client):1671 got = []1672

Merge pull request #4621 from pallets/deprecate-before_first_requestDavid Lordbefore adoptionaab1d99

line 1673why, one step back
1673 with pytest.deprecated_call():

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

line 1674why, one step back
1674

Merge pull request #4621 from pallets/deprecate-before_first_requestDavid Lordbefore adoptionaab1d99

lines 1675–1678why, one step back
1675 @app.before_first_request
1676 def foo():1677 got.append(42)1678

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1679–1688why, one step back
1679 client.get("/")
1680 assert got == [42]1681 client.get("/")1682 assert got == [42]1683 assert app.got_first_request168416851686def test_before_first_request_functions_concurrent(app, client):1687 got = []1688

Merge pull request #4621 from pallets/deprecate-before_first_requestDavid Lordbefore adoptionaab1d99

lines 1689–1694why, one step back
1689 with pytest.deprecated_call():
16901691 @app.before_first_request1692 def foo():1693 time.sleep(0.2)1694 got.append(42)

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1695–1706why, one step back
1695
1696 def get_and_assert():1697 client.get("/")1698 assert got == [42]16991700 t = Thread(target=get_and_assert)1701 t.start()1702 get_and_assert()1703 t.join()1704 assert app.got_first_request17051706

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

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

Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db

line 1708why, one step back
1708 app.config["DEBUG"] = True

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

line 1709why, one step back
1709

Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db

lines 1710–1715why, one step back
1710 @app.route("/user/", methods=["GET", "POST"])
1711 def user():1712 return flask.request.form["status"]17131714 # default redirect code preserves form data1715 rv = client.post("/user", data={"status": "success"}, follow_redirects=True)

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

line 1716why, one step back
1716 assert rv.data == b"success"

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

line 1717why, one step back
1717

Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db

line 1718why, one step back
1718 # 301 and 302 raise error

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

lines 1719–1720why, one step back
1719 monkeypatch.setattr(RequestRedirect, "code", 301)
1720

Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db

lines 1721–1722why, one step back
1721 with client, pytest.raises(AssertionError) as exc_info:
1722 client.post("/user", data={"status": "error"}, follow_redirects=True)

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

line 1723why, one step back
1723

Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db

line 1724why, one step back
1724 assert "canonical URL 'http://localhost/user/'" in str(exc_info.value)

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1725–1824why, one step back
1725
17261727def test_route_decorator_custom_endpoint(app, client):1728 app.debug = True17291730 @app.route("/foo/")1731 def foo():1732 return flask.request.endpoint17331734 @app.route("/bar/", endpoint="bar")1735 def for_bar():1736 return flask.request.endpoint17371738 @app.route("/bar/123", endpoint="123")1739 def for_bar_foo():1740 return flask.request.endpoint17411742 with app.test_request_context():1743 assert flask.url_for("foo") == "/foo/"1744 assert flask.url_for("bar") == "/bar/"1745 assert flask.url_for("123") == "/bar/123"17461747 assert client.get("/foo/").data == b"foo"1748 assert client.get("/bar/").data == b"bar"1749 assert client.get("/bar/123").data == b"123"175017511752def test_get_method_on_g(app_ctx):1753 assert flask.g.get("x") is None1754 assert flask.g.get("x", 11) == 111755 flask.g.x = 421756 assert flask.g.get("x") == 421757 assert flask.g.x == 42175817591760def test_g_iteration_protocol(app_ctx):1761 flask.g.foo = 231762 flask.g.bar = 421763 assert "foo" in flask.g1764 assert "foos" not in flask.g1765 assert sorted(flask.g) == ["bar", "foo"]176617671768def test_subdomain_basic_support():1769 app = flask.Flask(__name__, subdomain_matching=True)1770 app.config["SERVER_NAME"] = "localhost.localdomain"1771 client = app.test_client()17721773 @app.route("/")1774 def normal_index():1775 return "normal index"17761777 @app.route("/", subdomain="test")1778 def test_index():1779 return "test index"17801781 rv = client.get("/", "http://localhost.localdomain/")1782 assert rv.data == b"normal index"17831784 rv = client.get("/", "http://test.localhost.localdomain/")1785 assert rv.data == b"test index"178617871788def test_subdomain_matching():1789 app = flask.Flask(__name__, subdomain_matching=True)1790 client = app.test_client()1791 app.config["SERVER_NAME"] = "localhost.localdomain"17921793 @app.route("/", subdomain="<user>")1794 def index(user):1795 return f"index for {user}"17961797 rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1798 assert rv.data == b"index for mitsuhiko"179918001801def test_subdomain_matching_with_ports():1802 app = flask.Flask(__name__, subdomain_matching=True)1803 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1804 client = app.test_client()18051806 @app.route("/", subdomain="<user>")1807 def index(user):1808 return f"index for {user}"18091810 rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1811 assert rv.data == b"index for mitsuhiko"181218131814@pytest.mark.parametrize("matching", (False, True))1815def test_subdomain_matching_other_name(matching):1816 app = flask.Flask(__name__, subdomain_matching=matching)1817 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1818 client = app.test_client()18191820 @app.route("/")1821 def index():1822 return "", 20418231824 # suppress Werkzeug 0.15 warning about name mismatch

Merge branch '2.0.x'David Lordbefore adoptione37e871

lines 1825–1828why, one step back
1825 with warnings.catch_warnings():
1826 warnings.filterwarnings(1827 "ignore", "Current server name", UserWarning, "flask.app"1828 )

Fix broken func directives in docstringsGrey Libefore adoption2fab8a3

lines 1829–1958why, one step back
1829 # ip address can't match name
1830 rv = client.get("/", "http://127.0.0.1:3000/")1831 assert rv.status_code == 404 if matching else 20418321833 # allow all subdomains if matching is disabled1834 rv = client.get("/", "http://www.localhost.localdomain:3000/")1835 assert rv.status_code == 404 if matching else 204183618371838def test_multi_route_rules(app, client):1839 @app.route("/")1840 @app.route("/<test>/")1841 def index(test="a"):1842 return test18431844 rv = client.open("/")1845 assert rv.data == b"a"1846 rv = client.open("/b/")1847 assert rv.data == b"b"184818491850def test_multi_route_class_views(app, client):1851 class View:1852 def __init__(self, app):1853 app.add_url_rule("/", "index", self.index)1854 app.add_url_rule("/<test>/", "index", self.index)18551856 def index(self, test="a"):1857 return test18581859 _ = View(app)1860 rv = client.open("/")1861 assert rv.data == b"a"1862 rv = client.open("/b/")1863 assert rv.data == b"b"186418651866def test_run_defaults(monkeypatch, app):1867 rv = {}18681869 # Mocks werkzeug.serving.run_simple method1870 def run_simple_mock(*args, **kwargs):1871 rv["result"] = "running..."18721873 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1874 app.run()1875 assert rv["result"] == "running..."187618771878def test_run_server_port(monkeypatch, app):1879 rv = {}18801881 # Mocks werkzeug.serving.run_simple method1882 def run_simple_mock(hostname, port, application, *args, **kwargs):1883 rv["result"] = f"running on {hostname}:{port} ..."18841885 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1886 hostname, port = "localhost", 80001887 app.run(hostname, port, debug=True)1888 assert rv["result"] == f"running on {hostname}:{port} ..."188918901891@pytest.mark.parametrize(1892 "host,port,server_name,expect_host,expect_port",1893 (1894 (None, None, "pocoo.org:8080", "pocoo.org", 8080),1895 ("localhost", None, "pocoo.org:8080", "localhost", 8080),1896 (None, 80, "pocoo.org:8080", "pocoo.org", 80),1897 ("localhost", 80, "pocoo.org:8080", "localhost", 80),1898 ("localhost", 0, "localhost:8080", "localhost", 0),1899 (None, None, "localhost:8080", "localhost", 8080),1900 (None, None, "localhost:0", "localhost", 0),1901 ),1902)1903def test_run_from_config(1904 monkeypatch, host, port, server_name, expect_host, expect_port, app1905):1906 def run_simple_mock(hostname, port, *args, **kwargs):1907 assert hostname == expect_host1908 assert port == expect_port19091910 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1911 app.config["SERVER_NAME"] = server_name1912 app.run(host, port)191319141915def test_max_cookie_size(app, client, recwarn):1916 app.config["MAX_COOKIE_SIZE"] = 10019171918 # outside app context, default to Werkzeug static value,1919 # which is also the default config1920 response = flask.Response()1921 default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1922 assert response.max_cookie_size == default19231924 # inside app context, use app config1925 with app.app_context():1926 assert flask.Response().max_cookie_size == 10019271928 @app.route("/")1929 def index():1930 r = flask.Response("", status=204)1931 r.set_cookie("foo", "bar" * 100)1932 return r19331934 client.get("/")1935 assert len(recwarn) == 11936 w = recwarn.pop()1937 assert "cookie is too large" in str(w.message)19381939 app.config["MAX_COOKIE_SIZE"] = 019401941 client.get("/")1942 assert len(recwarn) == 0194319441945@require_cpython_gc1946def test_app_freed_on_zero_refcount():1947 # A Flask instance should not create a reference cycle that prevents CPython1948 # from freeing it when all external references to it are released (see #3761).1949 gc.disable()1950 try:1951 app = flask.Flask(__name__)1952 assert app.view_functions["static"]1953 weak = weakref.ref(app)1954 assert weak() is not None1955 del app1956 assert weak() is None1957 finally:1958 gc.enable()