test_basic.py
This file
Path
tests/test_basic.py
1,919 lines · 51.6 KiB · Python
Last changed by
Merge pull request #4995 from pallets/remove-deprecatedDavid Lordbefore adoption1ee22e1
History of this fileTake it
The walk stopped after 200 commits: lines older than 16f51ef point at it.
Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1–3why, one step back1import gc2import re3import uuidMerge branch '2.0.x'David Lordbefore adoptione37e871
line 4why, one step back4import warningsMerge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 5–6why, one step back5import weakref6from datetime import datetimeMerge pull request #4645 from kkirsche/patch-2David Lordbefore adoption7f2a0f4
line 7why, one step back7from datetime import timezoneMerge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 8–16why, one step back8from platform import python_implementation910import pytest11import werkzeug.serving12from werkzeug.exceptions import BadRequest13from werkzeug.exceptions import Forbidden14from werkzeug.exceptions import NotFound15from werkzeug.http import parse_date16from werkzeug.routing import BuildErrorMerge pull request #4492 from pallets/debug-messagesDavid Lordbefore adoptionce7b884
line 17why, one step back17from werkzeug.routing import RequestRedirectMerge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 18–151why, one step back1819import flask202122require_cpython_gc = pytest.mark.skipif(23 python_implementation() != "CPython",24 reason="Requires CPython GC behavior",25)262728def test_options_work(app, client):29 @app.route("/", methods=["GET", "POST"])30 def index():31 return "Hello World"3233 rv = client.open("/", method="OPTIONS")34 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]35 assert rv.data == b""363738def test_options_on_multiple_rules(app, client):39 @app.route("/", methods=["GET", "POST"])40 def index():41 return "Hello World"4243 @app.route("/", methods=["PUT"])44 def index_put():45 return "Aha!"4647 rv = client.open("/", method="OPTIONS")48 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST", "PUT"]495051@pytest.mark.parametrize("method", ["get", "post", "put", "delete", "patch"])52def test_method_route(app, client, method):53 method_route = getattr(app, method)54 client_method = getattr(client, method)5556 @method_route("/")57 def hello():58 return "Hello"5960 assert client_method("/").data == b"Hello"616263def test_method_route_no_methods(app):64 with pytest.raises(TypeError):65 app.get("/", methods=["GET", "POST"])666768def test_provide_automatic_options_attr():69 app = flask.Flask(__name__)7071 def index():72 return "Hello World!"7374 index.provide_automatic_options = False75 app.route("/")(index)76 rv = app.test_client().open("/", method="OPTIONS")77 assert rv.status_code == 4057879 app = flask.Flask(__name__)8081 def index2():82 return "Hello World!"8384 index2.provide_automatic_options = True85 app.route("/", methods=["OPTIONS"])(index2)86 rv = app.test_client().open("/", method="OPTIONS")87 assert sorted(rv.allow) == ["OPTIONS"]888990def test_provide_automatic_options_kwarg(app, client):91 def index():92 return flask.request.method9394 def more():95 return flask.request.method9697 app.add_url_rule("/", view_func=index, provide_automatic_options=False)98 app.add_url_rule(99 "/more",100 view_func=more,101 methods=["GET", "POST"],102 provide_automatic_options=False,103 )104 assert client.get("/").data == b"GET"105106 rv = client.post("/")107 assert rv.status_code == 405108 assert sorted(rv.allow) == ["GET", "HEAD"]109110 rv = client.open("/", method="OPTIONS")111 assert rv.status_code == 405112113 rv = client.head("/")114 assert rv.status_code == 200115 assert not rv.data # head truncates116 assert client.post("/more").data == b"POST"117 assert client.get("/more").data == b"GET"118119 rv = client.delete("/more")120 assert rv.status_code == 405121 assert sorted(rv.allow) == ["GET", "HEAD", "POST"]122123 rv = client.open("/more", method="OPTIONS")124 assert rv.status_code == 405125126127def test_request_dispatching(app, client):128 @app.route("/")129 def index():130 return flask.request.method131132 @app.route("/more", methods=["GET", "POST"])133 def more():134 return flask.request.method135136 assert client.get("/").data == b"GET"137 rv = client.post("/")138 assert rv.status_code == 405139 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]140 rv = client.head("/")141 assert rv.status_code == 200142 assert not rv.data # head truncates143 assert client.post("/more").data == b"POST"144 assert client.get("/more").data == b"GET"145 rv = client.delete("/more")146 assert rv.status_code == 405147 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]148149150def test_disallow_string_for_allowed_methods(app):151 with pytest.raises(TypeError):Merge branch '2.1.x'David Lordbefore adoptionf976d5b
line 152why, one step back152 app.add_url_rule("/", methods="GET POST", endpoint="test")Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 153–330why, one step back153154155def test_url_mapping(app, client):156 random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"157158 def index():159 return flask.request.method160161 def more():162 return flask.request.method163164 def options():165 return random_uuid4166167 app.add_url_rule("/", "index", index)168 app.add_url_rule("/more", "more", more, methods=["GET", "POST"])169170 # Issue 1288: Test that automatic options are not added171 # when non-uppercase 'options' in methods172 app.add_url_rule("/options", "options", options, methods=["options"])173174 assert client.get("/").data == b"GET"175 rv = client.post("/")176 assert rv.status_code == 405177 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]178 rv = client.head("/")179 assert rv.status_code == 200180 assert not rv.data # head truncates181 assert client.post("/more").data == b"POST"182 assert client.get("/more").data == b"GET"183 rv = client.delete("/more")184 assert rv.status_code == 405185 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]186 rv = client.open("/options", method="OPTIONS")187 assert rv.status_code == 200188 assert random_uuid4 in rv.data.decode("utf-8")189190191def test_werkzeug_routing(app, client):192 from werkzeug.routing import Submount, Rule193194 app.url_map.add(195 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])196 )197198 def bar():199 return "bar"200201 def index():202 return "index"203204 app.view_functions["bar"] = bar205 app.view_functions["index"] = index206207 assert client.get("/foo/").data == b"index"208 assert client.get("/foo/bar").data == b"bar"209210211def test_endpoint_decorator(app, client):212 from werkzeug.routing import Submount, Rule213214 app.url_map.add(215 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])216 )217218 @app.endpoint("bar")219 def bar():220 return "bar"221222 @app.endpoint("index")223 def index():224 return "index"225226 assert client.get("/foo/").data == b"index"227 assert client.get("/foo/bar").data == b"bar"228229230def test_session(app, client):231 @app.route("/set", methods=["POST"])232 def set():233 assert not flask.session.accessed234 assert not flask.session.modified235 flask.session["value"] = flask.request.form["value"]236 assert flask.session.accessed237 assert flask.session.modified238 return "value set"239240 @app.route("/get")241 def get():242 assert not flask.session.accessed243 assert not flask.session.modified244 v = flask.session.get("value", "None")245 assert flask.session.accessed246 assert not flask.session.modified247 return v248249 assert client.post("/set", data={"value": "42"}).data == b"value set"250 assert client.get("/get").data == b"42"251252253def test_session_using_server_name(app, client):254 app.config.update(SERVER_NAME="example.com")255256 @app.route("/")257 def index():258 flask.session["testing"] = 42259 return "Hello World"260261 rv = client.get("/", "http://example.com/")262 assert "domain=.example.com" in rv.headers["set-cookie"].lower()263 assert "httponly" in rv.headers["set-cookie"].lower()264265266def test_session_using_server_name_and_port(app, client):267 app.config.update(SERVER_NAME="example.com:8080")268269 @app.route("/")270 def index():271 flask.session["testing"] = 42272 return "Hello World"273274 rv = client.get("/", "http://example.com:8080/")275 assert "domain=.example.com" in rv.headers["set-cookie"].lower()276 assert "httponly" in rv.headers["set-cookie"].lower()277278279def test_session_using_server_name_port_and_path(app, client):280 app.config.update(SERVER_NAME="example.com:8080", APPLICATION_ROOT="/foo")281282 @app.route("/")283 def index():284 flask.session["testing"] = 42285 return "Hello World"286287 rv = client.get("/", "http://example.com:8080/foo")288 assert "domain=example.com" in rv.headers["set-cookie"].lower()289 assert "path=/foo" in rv.headers["set-cookie"].lower()290 assert "httponly" in rv.headers["set-cookie"].lower()291292293def test_session_using_application_root(app, client):294 class PrefixPathMiddleware:295 def __init__(self, app, prefix):296 self.app = app297 self.prefix = prefix298299 def __call__(self, environ, start_response):300 environ["SCRIPT_NAME"] = self.prefix301 return self.app(environ, start_response)302303 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, "/bar")304 app.config.update(APPLICATION_ROOT="/bar")305306 @app.route("/")307 def index():308 flask.session["testing"] = 42309 return "Hello World"310311 rv = client.get("/", "http://example.com:8080/")312 assert "path=/bar" in rv.headers["set-cookie"].lower()313314315def test_session_using_session_settings(app, client):316 app.config.update(317 SERVER_NAME="www.example.com:8080",318 APPLICATION_ROOT="/test",319 SESSION_COOKIE_DOMAIN=".example.com",320 SESSION_COOKIE_HTTPONLY=False,321 SESSION_COOKIE_SECURE=True,322 SESSION_COOKIE_SAMESITE="Lax",323 SESSION_COOKIE_PATH="/",324 )325326 @app.route("/")327 def index():328 flask.session["testing"] = 42329 return "Hello World"330Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db
lines 331–335why, one step back331 @app.route("/clear")332 def clear():333 flask.session.pop("testing", None)334 return "Goodbye World"335Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 336–437why, one step back336 rv = client.get("/", "http://www.example.com:8080/test/")337 cookie = rv.headers["set-cookie"].lower()338 assert "domain=.example.com" in cookie339 assert "path=/" in cookie340 assert "secure" in cookie341 assert "httponly" not in cookie342 assert "samesite" in cookie343344 rv = client.get("/clear", "http://www.example.com:8080/test/")345 cookie = rv.headers["set-cookie"].lower()346 assert "session=;" in cookie347 assert "domain=.example.com" in cookie348 assert "path=/" in cookie349 assert "secure" in cookie350 assert "samesite" in cookie351352353def test_session_using_samesite_attribute(app, client):354 @app.route("/")355 def index():356 flask.session["testing"] = 42357 return "Hello World"358359 app.config.update(SESSION_COOKIE_SAMESITE="invalid")360361 with pytest.raises(ValueError):362 client.get("/")363364 app.config.update(SESSION_COOKIE_SAMESITE=None)365 rv = client.get("/")366 cookie = rv.headers["set-cookie"].lower()367 assert "samesite" not in cookie368369 app.config.update(SESSION_COOKIE_SAMESITE="Strict")370 rv = client.get("/")371 cookie = rv.headers["set-cookie"].lower()372 assert "samesite=strict" in cookie373374 app.config.update(SESSION_COOKIE_SAMESITE="Lax")375 rv = client.get("/")376 cookie = rv.headers["set-cookie"].lower()377 assert "samesite=lax" in cookie378379380def test_session_localhost_warning(recwarn, app, client):381 app.config.update(SERVER_NAME="localhost:5000")382383 @app.route("/")384 def index():385 flask.session["testing"] = 42386 return "testing"387388 rv = client.get("/", "http://localhost:5000/")389 assert "domain" not in rv.headers["set-cookie"].lower()390 w = recwarn.pop(UserWarning)391 assert "'localhost' is not a valid cookie domain" in str(w.message)392393394def test_session_ip_warning(recwarn, app, client):395 app.config.update(SERVER_NAME="127.0.0.1:5000")396397 @app.route("/")398 def index():399 flask.session["testing"] = 42400 return "testing"401402 rv = client.get("/", "http://127.0.0.1:5000/")403 assert "domain=127.0.0.1" in rv.headers["set-cookie"].lower()404 w = recwarn.pop(UserWarning)405 assert "cookie domain is an IP" in str(w.message)406407408def test_missing_session(app):409 app.secret_key = None410411 def expect_exception(f, *args, **kwargs):412 e = pytest.raises(RuntimeError, f, *args, **kwargs)413 assert e.value.args and "session is unavailable" in e.value.args[0]414415 with app.test_request_context():416 assert flask.session.get("missing_key") is None417 expect_exception(flask.session.__setitem__, "foo", 42)418 expect_exception(flask.session.pop, "foo")419420421def test_session_expiration(app, client):422 permanent = True423424 @app.route("/")425 def index():426 flask.session["test"] = 42427 flask.session.permanent = permanent428 return ""429430 @app.route("/test")431 def test():432 return str(flask.session.permanent)433434 rv = client.get("/")435 assert "set-cookie" in rv.headers436 match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])437 expires = parse_date(match.group())Merge pull request #4645 from kkirsche/patch-2David Lordbefore adoption7f2a0f4
line 438why, one step back438 expected = datetime.now(timezone.utc) + app.permanent_session_lifetimeMerge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 439–467why, one step back439 assert expires.year == expected.year440 assert expires.month == expected.month441 assert expires.day == expected.day442443 rv = client.get("/test")444 assert rv.data == b"True"445446 permanent = False447 rv = client.get("/")448 assert "set-cookie" in rv.headers449 match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])450 assert match is None451452453def test_session_stored_last(app, client):454 @app.after_request455 def modify_session(response):456 flask.session["foo"] = 42457 return response458459 @app.route("/")460 def dump_session_contents():461 return repr(flask.session.get("foo"))462463 assert client.get("/").data == b"None"464 assert client.get("/").data == b"42"465466467def test_session_special_types(app, client):Merge pull request #4645 from kkirsche/patch-2David Lordbefore adoption7f2a0f4
line 468why, one step back468 now = datetime.now(timezone.utc).replace(microsecond=0)Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 469–928why, one step back469 the_uuid = uuid.uuid4()470471 @app.route("/")472 def dump_session_contents():473 flask.session["t"] = (1, 2, 3)474 flask.session["b"] = b"\xff"475 flask.session["m"] = flask.Markup("<html>")476 flask.session["u"] = the_uuid477 flask.session["d"] = now478 flask.session["t_tag"] = {" t": "not-a-tuple"}479 flask.session["di_t_tag"] = {" t__": "not-a-tuple"}480 flask.session["di_tag"] = {" di": "not-a-dict"}481 return "", 204482483 with client:484 client.get("/")485 s = flask.session486 assert s["t"] == (1, 2, 3)487 assert type(s["b"]) == bytes488 assert s["b"] == b"\xff"489 assert type(s["m"]) == flask.Markup490 assert s["m"] == flask.Markup("<html>")491 assert s["u"] == the_uuid492 assert s["d"] == now493 assert s["t_tag"] == {" t": "not-a-tuple"}494 assert s["di_t_tag"] == {" t__": "not-a-tuple"}495 assert s["di_tag"] == {" di": "not-a-dict"}496497498def test_session_cookie_setting(app):499 is_permanent = True500501 @app.route("/bump")502 def bump():503 rv = flask.session["foo"] = flask.session.get("foo", 0) + 1504 flask.session.permanent = is_permanent505 return str(rv)506507 @app.route("/read")508 def read():509 return str(flask.session.get("foo", 0))510511 def run_test(expect_header):512 with app.test_client() as c:513 assert c.get("/bump").data == b"1"514 assert c.get("/bump").data == b"2"515 assert c.get("/bump").data == b"3"516517 rv = c.get("/read")518 set_cookie = rv.headers.get("set-cookie")519 assert (set_cookie is not None) == expect_header520 assert rv.data == b"3"521522 is_permanent = True523 app.config["SESSION_REFRESH_EACH_REQUEST"] = True524 run_test(expect_header=True)525526 is_permanent = True527 app.config["SESSION_REFRESH_EACH_REQUEST"] = False528 run_test(expect_header=False)529530 is_permanent = False531 app.config["SESSION_REFRESH_EACH_REQUEST"] = True532 run_test(expect_header=False)533534 is_permanent = False535 app.config["SESSION_REFRESH_EACH_REQUEST"] = False536 run_test(expect_header=False)537538539def test_session_vary_cookie(app, client):540 @app.route("/set")541 def set_session():542 flask.session["test"] = "test"543 return ""544545 @app.route("/get")546 def get():547 return flask.session.get("test")548549 @app.route("/getitem")550 def getitem():551 return flask.session["test"]552553 @app.route("/setdefault")554 def setdefault():555 return flask.session.setdefault("test", "default")556557 @app.route("/vary-cookie-header-set")558 def vary_cookie_header_set():559 response = flask.Response()560 response.vary.add("Cookie")561 flask.session["test"] = "test"562 return response563564 @app.route("/vary-header-set")565 def vary_header_set():566 response = flask.Response()567 response.vary.update(("Accept-Encoding", "Accept-Language"))568 flask.session["test"] = "test"569 return response570571 @app.route("/no-vary-header")572 def no_vary_header():573 return ""574575 def expect(path, header_value="Cookie"):576 rv = client.get(path)577578 if header_value:579 # The 'Vary' key should exist in the headers only once.580 assert len(rv.headers.get_all("Vary")) == 1581 assert rv.headers["Vary"] == header_value582 else:583 assert "Vary" not in rv.headers584585 expect("/set")586 expect("/get")587 expect("/getitem")588 expect("/setdefault")589 expect("/vary-cookie-header-set")590 expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")591 expect("/no-vary-header", None)592593594def test_flashes(app, req_ctx):595 assert not flask.session.modified596 flask.flash("Zap")597 flask.session.modified = False598 flask.flash("Zip")599 assert flask.session.modified600 assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]601602603def test_extended_flashing(app):604 # Be sure app.testing=True below, else tests can fail silently.605 #606 # Specifically, if app.testing is not set to True, the AssertionErrors607 # in the view functions will cause a 500 response to the test client608 # instead of propagating exceptions.609610 @app.route("/")611 def index():612 flask.flash("Hello World")613 flask.flash("Hello World", "error")614 flask.flash(flask.Markup("<em>Testing</em>"), "warning")615 return ""616617 @app.route("/test/")618 def test():619 messages = flask.get_flashed_messages()620 assert list(messages) == [621 "Hello World",622 "Hello World",623 flask.Markup("<em>Testing</em>"),624 ]625 return ""626627 @app.route("/test_with_categories/")628 def test_with_categories():629 messages = flask.get_flashed_messages(with_categories=True)630 assert len(messages) == 3631 assert list(messages) == [632 ("message", "Hello World"),633 ("error", "Hello World"),634 ("warning", flask.Markup("<em>Testing</em>")),635 ]636 return ""637638 @app.route("/test_filter/")639 def test_filter():640 messages = flask.get_flashed_messages(641 category_filter=["message"], with_categories=True642 )643 assert list(messages) == [("message", "Hello World")]644 return ""645646 @app.route("/test_filters/")647 def test_filters():648 messages = flask.get_flashed_messages(649 category_filter=["message", "warning"], with_categories=True650 )651 assert list(messages) == [652 ("message", "Hello World"),653 ("warning", flask.Markup("<em>Testing</em>")),654 ]655 return ""656657 @app.route("/test_filters_without_returning_categories/")658 def test_filters2():659 messages = flask.get_flashed_messages(category_filter=["message", "warning"])660 assert len(messages) == 2661 assert messages[0] == "Hello World"662 assert messages[1] == flask.Markup("<em>Testing</em>")663 return ""664665 # Create new test client on each test to clean flashed messages.666667 client = app.test_client()668 client.get("/")669 client.get("/test_with_categories/")670671 client = app.test_client()672 client.get("/")673 client.get("/test_filter/")674675 client = app.test_client()676 client.get("/")677 client.get("/test_filters/")678679 client = app.test_client()680 client.get("/")681 client.get("/test_filters_without_returning_categories/")682683684def test_request_processing(app, client):685 evts = []686687 @app.before_request688 def before_request():689 evts.append("before")690691 @app.after_request692 def after_request(response):693 response.data += b"|after"694 evts.append("after")695 return response696697 @app.route("/")698 def index():699 assert "before" in evts700 assert "after" not in evts701 return "request"702703 assert "after" not in evts704 rv = client.get("/").data705 assert "after" in evts706 assert rv == b"request|after"707708709def test_request_preprocessing_early_return(app, client):710 evts = []711712 @app.before_request713 def before_request1():714 evts.append(1)715716 @app.before_request717 def before_request2():718 evts.append(2)719 return "hello"720721 @app.before_request722 def before_request3():723 evts.append(3)724 return "bye"725726 @app.route("/")727 def index():728 evts.append("index")729 return "damnit"730731 rv = client.get("/").data.strip()732 assert rv == b"hello"733 assert evts == [1, 2]734735736def test_after_request_processing(app, client):737 @app.route("/")738 def index():739 @flask.after_this_request740 def foo(response):741 response.headers["X-Foo"] = "a header"742 return response743744 return "Test"745746 resp = client.get("/")747 assert resp.status_code == 200748 assert resp.headers["X-Foo"] == "a header"749750751def test_teardown_request_handler(app, client):752 called = []753754 @app.teardown_request755 def teardown_request(exc):756 called.append(True)757 return "Ignored"758759 @app.route("/")760 def root():761 return "Response"762763 rv = client.get("/")764 assert rv.status_code == 200765 assert b"Response" in rv.data766 assert len(called) == 1767768769def test_teardown_request_handler_debug_mode(app, client):770 called = []771772 @app.teardown_request773 def teardown_request(exc):774 called.append(True)775 return "Ignored"776777 @app.route("/")778 def root():779 return "Response"780781 rv = client.get("/")782 assert rv.status_code == 200783 assert b"Response" in rv.data784 assert len(called) == 1785786787def test_teardown_request_handler_error(app, client):788 called = []789 app.testing = False790791 @app.teardown_request792 def teardown_request1(exc):793 assert type(exc) == ZeroDivisionError794 called.append(True)795 # This raises a new error and blows away sys.exc_info(), so we can796 # test that all teardown_requests get passed the same original797 # exception.798 try:799 raise TypeError()800 except Exception:801 pass802803 @app.teardown_request804 def teardown_request2(exc):805 assert type(exc) == ZeroDivisionError806 called.append(True)807 # This raises a new error and blows away sys.exc_info(), so we can808 # test that all teardown_requests get passed the same original809 # exception.810 try:811 raise TypeError()812 except Exception:813 pass814815 @app.route("/")816 def fails():817 1 // 0818819 rv = client.get("/")820 assert rv.status_code == 500821 assert b"Internal Server Error" in rv.data822 assert len(called) == 2823824825def test_before_after_request_order(app, client):826 called = []827828 @app.before_request829 def before1():830 called.append(1)831832 @app.before_request833 def before2():834 called.append(2)835836 @app.after_request837 def after1(response):838 called.append(4)839 return response840841 @app.after_request842 def after2(response):843 called.append(3)844 return response845846 @app.teardown_request847 def finish1(exc):848 called.append(6)849850 @app.teardown_request851 def finish2(exc):852 called.append(5)853854 @app.route("/")855 def index():856 return "42"857858 rv = client.get("/")859 assert rv.data == b"42"860 assert called == [1, 2, 3, 4, 5, 6]861862863def test_error_handling(app, client):864 app.testing = False865866 @app.errorhandler(404)867 def not_found(e):868 return "not found", 404869870 @app.errorhandler(500)871 def internal_server_error(e):872 return "internal server error", 500873874 @app.errorhandler(Forbidden)875 def forbidden(e):876 return "forbidden", 403877878 @app.route("/")879 def index():880 flask.abort(404)881882 @app.route("/error")883 def error():884 1 // 0885886 @app.route("/forbidden")887 def error2():888 flask.abort(403)889890 rv = client.get("/")891 assert rv.status_code == 404892 assert rv.data == b"not found"893 rv = client.get("/error")894 assert rv.status_code == 500895 assert b"internal server error" == rv.data896 rv = client.get("/forbidden")897 assert rv.status_code == 403898 assert b"forbidden" == rv.data899900901def test_error_handling_processing(app, client):902 app.testing = False903904 @app.errorhandler(500)905 def internal_server_error(e):906 return "internal server error", 500907908 @app.route("/")909 def broken_func():910 1 // 0911912 @app.after_request913 def after_request(resp):914 resp.mimetype = "text/x-special"915 return resp916917 resp = client.get("/")918 assert resp.mimetype == "text/x-special"919 assert resp.data == b"internal server error"920921922def test_baseexception_error_handling(app, client):923 app.testing = False924925 @app.route("/")926 def broken_func():927 raise KeyboardInterrupt()928Merge pull request #4666 from pallets/debug-contextDavid Lordbefore adoption6916697
lines 929–930why, one step back929 with pytest.raises(KeyboardInterrupt):930 client.get("/")Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 931–1027why, one step back931932933def test_before_request_and_routing_errors(app, client):934 @app.before_request935 def attach_something():936 flask.g.something = "value"937938 @app.errorhandler(404)939 def return_something(error):940 return flask.g.something, 404941942 rv = client.get("/")943 assert rv.status_code == 404944 assert rv.data == b"value"945946947def test_user_error_handling(app, client):948 class MyException(Exception):949 pass950951 @app.errorhandler(MyException)952 def handle_my_exception(e):953 assert isinstance(e, MyException)954 return "42"955956 @app.route("/")957 def index():958 raise MyException()959960 assert client.get("/").data == b"42"961962963def test_http_error_subclass_handling(app, client):964 class ForbiddenSubclass(Forbidden):965 pass966967 @app.errorhandler(ForbiddenSubclass)968 def handle_forbidden_subclass(e):969 assert isinstance(e, ForbiddenSubclass)970 return "banana"971972 @app.errorhandler(403)973 def handle_403(e):974 assert not isinstance(e, ForbiddenSubclass)975 assert isinstance(e, Forbidden)976 return "apple"977978 @app.route("/1")979 def index1():980 raise ForbiddenSubclass()981982 @app.route("/2")983 def index2():984 flask.abort(403)985986 @app.route("/3")987 def index3():988 raise Forbidden()989990 assert client.get("/1").data == b"banana"991 assert client.get("/2").data == b"apple"992 assert client.get("/3").data == b"apple"993994995def test_errorhandler_precedence(app, client):996 class E1(Exception):997 pass998999 class E2(Exception):1000 pass10011002 class E3(E1, E2):1003 pass10041005 @app.errorhandler(E2)1006 def handle_e2(e):1007 return "E2"10081009 @app.errorhandler(Exception)1010 def handle_exception(e):1011 return "Exception"10121013 @app.route("/E1")1014 def raise_e1():1015 raise E110161017 @app.route("/E3")1018 def raise_e3():1019 raise E310201021 rv = client.get("/E1")1022 assert rv.data == b"Exception"10231024 rv = client.get("/E3")1025 assert rv.data == b"E2"10261027Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db
lines 1028–1035why, one step back1028@pytest.mark.parametrize(1029 ("debug", "trap", "expect_key", "expect_abort"),1030 [(False, None, True, True), (True, None, False, True), (False, True, False, False)],1031)1032def test_trap_bad_request_key_error(app, client, debug, trap, expect_key, expect_abort):1033 app.config["DEBUG"] = debug1034 app.config["TRAP_BAD_REQUEST_ERRORS"] = trap1035Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1036–1043why, one step back1036 @app.route("/key")1037 def fail():1038 flask.request.form["missing_key"]10391040 @app.route("/abort")1041 def allow_abort():1042 flask.abort(400)1043Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db
lines 1044–1050why, one step back1044 if expect_key:1045 rv = client.get("/key")1046 assert rv.status_code == 4001047 assert b"missing_key" not in rv.data1048 else:1049 with pytest.raises(KeyError) as exc_info:1050 client.get("/key")Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
line 1051why, one step back1051Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db
lines 1052–1053why, one step back1052 assert exc_info.errisinstance(BadRequest)1053 assert "missing_key" in exc_info.value.get_description()Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
line 1054why, one step back1054Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db
lines 1055–1060why, one step back1055 if expect_abort:1056 rv = client.get("/abort")1057 assert rv.status_code == 4001058 else:1059 with pytest.raises(BadRequest):1060 client.get("/abort")Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1061–1110why, one step back106110621063def test_trapping_of_all_http_exceptions(app, client):1064 app.config["TRAP_HTTP_EXCEPTIONS"] = True10651066 @app.route("/fail")1067 def fail():1068 flask.abort(404)10691070 with pytest.raises(NotFound):1071 client.get("/fail")107210731074def test_error_handler_after_processor_error(app, client):1075 app.testing = False10761077 @app.before_request1078 def before_request():1079 if _trigger == "before":1080 1 // 010811082 @app.after_request1083 def after_request(response):1084 if _trigger == "after":1085 1 // 01086 return response10871088 @app.route("/")1089 def index():1090 return "Foo"10911092 @app.errorhandler(500)1093 def internal_server_error(e):1094 return "Hello Server Error", 50010951096 for _trigger in "before", "after":1097 rv = client.get("/")1098 assert rv.status_code == 5001099 assert rv.data == b"Hello Server Error"110011011102def test_enctype_debug_helper(app, client):1103 from flask.debughelpers import DebugFilesKeyError11041105 app.debug = True11061107 @app.route("/fail", methods=["POST"])1108 def index():1109 return flask.request.files["foo"].filename1110Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae
lines 1111–1114why, one step back1111 with pytest.raises(DebugFilesKeyError) as e:1112 client.post("/fail", data={"foo": "index.txt"})1113 assert "no file contents were transmitted" in str(e.value)1114 assert "This was submitted: 'index.txt'" in str(e.value)Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1115–1162why, one step back111511161117def test_response_types(app, client):1118 @app.route("/text")1119 def from_text():1120 return "Hällo Wörld"11211122 @app.route("/bytes")1123 def from_bytes():1124 return "Hällo Wörld".encode()11251126 @app.route("/full_tuple")1127 def from_full_tuple():1128 return (1129 "Meh",1130 400,1131 {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1132 )11331134 @app.route("/text_headers")1135 def from_text_headers():1136 return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}11371138 @app.route("/text_status")1139 def from_text_status():1140 return "Hi, status!", 40011411142 @app.route("/response_headers")1143 def from_response_headers():1144 return (1145 flask.Response(1146 "Hello world", 404, {"Content-Type": "text/html", "X-Foo": "Baz"}1147 ),1148 {"Content-Type": "text/plain", "X-Foo": "Bar", "X-Bar": "Foo"},1149 )11501151 @app.route("/response_status")1152 def from_response_status():1153 return app.response_class("Hello world", 400), 50011541155 @app.route("/wsgi")1156 def from_wsgi():1157 return NotFound()11581159 @app.route("/dict")1160 def from_dict():1161 return {"foo": "bar"}, 2011162Merge pull request #4672 from greyli/return-listDavid Lordbefore adoption559a845
lines 1163–1166why, one step back1163 @app.route("/list")1164 def from_list():1165 return ["foo", "bar"], 2011166Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1167–1203why, one step back1167 assert client.get("/text").data == "Hällo Wörld".encode()1168 assert client.get("/bytes").data == "Hällo Wörld".encode()11691170 rv = client.get("/full_tuple")1171 assert rv.data == b"Meh"1172 assert rv.headers["X-Foo"] == "Testing"1173 assert rv.status_code == 4001174 assert rv.mimetype == "text/plain"11751176 rv = client.get("/text_headers")1177 assert rv.data == b"Hello"1178 assert rv.headers["X-Foo"] == "Test"1179 assert rv.status_code == 2001180 assert rv.mimetype == "text/plain"11811182 rv = client.get("/text_status")1183 assert rv.data == b"Hi, status!"1184 assert rv.status_code == 4001185 assert rv.mimetype == "text/html"11861187 rv = client.get("/response_headers")1188 assert rv.data == b"Hello world"1189 assert rv.content_type == "text/plain"1190 assert rv.headers.getlist("X-Foo") == ["Bar"]1191 assert rv.headers["X-Bar"] == "Foo"1192 assert rv.status_code == 40411931194 rv = client.get("/response_status")1195 assert rv.data == b"Hello world"1196 assert rv.status_code == 50011971198 rv = client.get("/wsgi")1199 assert b"Not Found" in rv.data1200 assert rv.status_code == 40412011202 rv = client.get("/dict")1203 assert rv.json == {"foo": "bar"}Merge pull request #4672 from greyli/return-listDavid Lordbefore adoption559a845
lines 1204–1207why, one step back1204 assert rv.status_code == 20112051206 rv = client.get("/list")1207 assert rv.json == ["foo", "bar"]Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1208–1239why, one step back1208 assert rv.status_code == 201120912101211def test_response_type_errors():1212 app = flask.Flask(__name__)1213 app.testing = True12141215 @app.route("/none")1216 def from_none():1217 pass12181219 @app.route("/small_tuple")1220 def from_small_tuple():1221 return ("Hello",)12221223 @app.route("/large_tuple")1224 def from_large_tuple():1225 return "Hello", 234, {"X-Foo": "Bar"}, "???"12261227 @app.route("/bad_type")1228 def from_bad_type():1229 return True12301231 @app.route("/bad_wsgi")1232 def from_bad_wsgi():1233 return lambda: None12341235 c = app.test_client()12361237 with pytest.raises(TypeError) as e:1238 c.get("/none")1239Merge branch '2.1.x'David Lordbefore adoptionf976d5b
lines 1240–1242why, one step back1240 assert "returned None" in str(e.value)1241 assert "from_none" in str(e.value)1242Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1243–1245why, one step back1243 with pytest.raises(TypeError) as e:1244 c.get("/small_tuple")1245Merge branch '2.1.x'David Lordbefore adoptionf976d5b
line 1246why, one step back1246 assert "tuple must have the form" in str(e.value)Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
line 1247why, one step back1247Merge branch '2.1.x'David Lordbefore adoptionf976d5b
lines 1248–1250why, one step back1248 with pytest.raises(TypeError):1249 c.get("/large_tuple")1250Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1251–1253why, one step back1251 with pytest.raises(TypeError) as e:1252 c.get("/bad_type")1253Merge branch '2.1.x'David Lordbefore adoptionf976d5b
line 1254why, one step back1254 assert "it was a bool" in str(e.value)Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
line 1255why, one step back1255Merge branch '2.1.x'David Lordbefore adoptionf976d5b
lines 1256–1257why, one step back1256 with pytest.raises(TypeError):1257 c.get("/bad_wsgi")Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
line 1258why, one step back1258Merge branch '2.1.x'David Lordbefore adoptionf976d5b
line 1259why, one step back1259Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1260–1275why, one step back1260def test_make_response(app, req_ctx):1261 rv = flask.make_response()1262 assert rv.status_code == 2001263 assert rv.data == b""1264 assert rv.mimetype == "text/html"12651266 rv = flask.make_response("Awesome")1267 assert rv.status_code == 2001268 assert rv.data == b"Awesome"1269 assert rv.mimetype == "text/html"12701271 rv = flask.make_response("W00t", 404)1272 assert rv.status_code == 4041273 assert rv.data == b"W00t"1274 assert rv.mimetype == "text/html"1275Merge pull request #4629 from pgjones/generateDavid Lordbefore adoptionab36542
lines 1276–1280why, one step back1276 rv = flask.make_response(c for c in "Hello")1277 assert rv.status_code == 2001278 assert rv.data == b"Hello"1279 assert rv.mimetype == "text/html"1280Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1281–1302why, one step back12811282def test_make_response_with_response_instance(app, req_ctx):1283 rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1284 assert rv.status_code == 4001285 assert rv.data == b'{"msg":"W00t"}\n'1286 assert rv.mimetype == "application/json"12871288 rv = flask.make_response(flask.Response(""), 400)1289 assert rv.status_code == 4001290 assert rv.data == b""1291 assert rv.mimetype == "text/html"12921293 rv = flask.make_response(1294 flask.Response("", headers={"Content-Type": "text/html"}),1295 400,1296 [("X-Foo", "bar")],1297 )1298 assert rv.status_code == 4001299 assert rv.headers["Content-Type"] == "text/html"1300 assert rv.headers["X-Foo"] == "bar"13011302Merge pull request #4692 from pallets/json-providerDavid Lordbefore adoption67310ab
lines 1303–1309why, one step back1303@pytest.mark.parametrize("compact", [True, False])1304def test_jsonify_no_prettyprint(app, compact):1305 app.json.compact = compact1306 rv = app.json.response({"msg": {"submsg": "W00t"}, "msg2": "foobar"})1307 data = rv.data.strip()1308 assert (b" " not in data) is compact1309 assert (b"\n" not in data) is compactMerge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1310–1312why, one step back131013111312def test_jsonify_mimetype(app, req_ctx):Merge pull request #4692 from pallets/json-providerDavid Lordbefore adoption67310ab
line 1313why, one step back1313 app.json.mimetype = "application/vnd.api+json"Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1314–1322why, one step back1314 msg = {"msg": {"submsg": "W00t"}}1315 rv = flask.make_response(flask.jsonify(msg), 200)1316 assert rv.mimetype == "application/vnd.api+json"131713181319def test_json_dump_dataclass(app, req_ctx):1320 from dataclasses import make_dataclass13211322 Data = make_dataclass("Data", [("name", str)])Merge pull request #4692 from pallets/json-providerDavid Lordbefore adoption67310ab
lines 1323–1324why, one step back1323 value = app.json.dumps(Data("Flask"))1324 value = app.json.loads(value)Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1325–1330why, one step back1325 assert value == {"name": "Flask"}132613271328def test_jsonify_args_and_kwargs_check(app, req_ctx):1329 with pytest.raises(TypeError) as e:1330 flask.jsonify("fake args", kwargs="fake")Merge pull request #4692 from pallets/json-providerDavid Lordbefore adoption67310ab
line 1331why, one step back1331 assert "args or kwargs" in str(e.value)Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1332–1472why, one step back133213331334def test_url_generation(app, req_ctx):1335 @app.route("/hello/<name>", methods=["POST"])1336 def hello():1337 pass13381339 assert flask.url_for("hello", name="test x") == "/hello/test%20x"1340 assert (1341 flask.url_for("hello", name="test x", _external=True)1342 == "http://localhost/hello/test%20x"1343 )134413451346def test_build_error_handler(app):1347 # Test base case, a URL which results in a BuildError.1348 with app.test_request_context():1349 pytest.raises(BuildError, flask.url_for, "spam")13501351 # Verify the error is re-raised if not the current exception.1352 try:1353 with app.test_request_context():1354 flask.url_for("spam")1355 except BuildError as err:1356 error = err1357 try:1358 raise RuntimeError("Test case where BuildError is not current.")1359 except RuntimeError:1360 pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})13611362 # Test a custom handler.1363 def handler(error, endpoint, values):1364 # Just a test.1365 return "/test_handler/"13661367 app.url_build_error_handlers.append(handler)1368 with app.test_request_context():1369 assert flask.url_for("spam") == "/test_handler/"137013711372def test_build_error_handler_reraise(app):1373 # Test a custom handler which reraises the BuildError1374 def handler_raises_build_error(error, endpoint, values):1375 raise error13761377 app.url_build_error_handlers.append(handler_raises_build_error)13781379 with app.test_request_context():1380 pytest.raises(BuildError, flask.url_for, "not.existing")138113821383def test_url_for_passes_special_values_to_build_error_handler(app):1384 @app.url_build_error_handlers.append1385 def handler(error, endpoint, values):1386 assert values == {1387 "_external": False,1388 "_anchor": None,1389 "_method": None,1390 "_scheme": None,1391 }1392 return "handled"13931394 with app.test_request_context():1395 flask.url_for("/")139613971398def test_static_files(app, client):1399 rv = client.get("/static/index.html")1400 assert rv.status_code == 2001401 assert rv.data.strip() == b"<h1>Hello World!</h1>"1402 with app.test_request_context():1403 assert flask.url_for("static", filename="index.html") == "/static/index.html"1404 rv.close()140514061407def test_static_url_path():1408 app = flask.Flask(__name__, static_url_path="/foo")1409 app.testing = True1410 rv = app.test_client().get("/foo/index.html")1411 assert rv.status_code == 2001412 rv.close()14131414 with app.test_request_context():1415 assert flask.url_for("static", filename="index.html") == "/foo/index.html"141614171418def test_static_url_path_with_ending_slash():1419 app = flask.Flask(__name__, static_url_path="/foo/")1420 app.testing = True1421 rv = app.test_client().get("/foo/index.html")1422 assert rv.status_code == 2001423 rv.close()14241425 with app.test_request_context():1426 assert flask.url_for("static", filename="index.html") == "/foo/index.html"142714281429def test_static_url_empty_path(app):1430 app = flask.Flask(__name__, static_folder="", static_url_path="")1431 rv = app.test_client().open("/static/index.html", method="GET")1432 assert rv.status_code == 2001433 rv.close()143414351436def test_static_url_empty_path_default(app):1437 app = flask.Flask(__name__, static_folder="")1438 rv = app.test_client().open("/static/index.html", method="GET")1439 assert rv.status_code == 2001440 rv.close()144114421443def test_static_folder_with_pathlib_path(app):1444 from pathlib import Path14451446 app = flask.Flask(__name__, static_folder=Path("static"))1447 rv = app.test_client().open("/static/index.html", method="GET")1448 assert rv.status_code == 2001449 rv.close()145014511452def test_static_folder_with_ending_slash():1453 app = flask.Flask(__name__, static_folder="static/")14541455 @app.route("/<path:path>")1456 def catch_all(path):1457 return path14581459 rv = app.test_client().get("/catch/all")1460 assert rv.data == b"catch/all"146114621463def test_static_route_with_host_matching():1464 app = flask.Flask(__name__, host_matching=True, static_host="example.com")1465 c = app.test_client()1466 rv = c.get("http://example.com/static/index.html")1467 assert rv.status_code == 2001468 rv.close()1469 with app.test_request_context():1470 rv = flask.url_for("static", filename="index.html", _external=True)1471 assert rv == "http://example.com/static/index.html"1472 # Providing static_host without host_matching=True should error.Merge pull request #4947 from pallets/pyprojectDavid Lordbefore adoption78b42b9
line 1473why, one step back1473 with pytest.raises(AssertionError):Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1474–1476why, one step back1474 flask.Flask(__name__, static_host="example.com")1475 # Providing host_matching=True with static_folder1476 # but without static_host should error.Merge pull request #4947 from pallets/pyprojectDavid Lordbefore adoption78b42b9
line 1477why, one step back1477 with pytest.raises(AssertionError):Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1478–1521why, one step back1478 flask.Flask(__name__, host_matching=True)1479 # Providing host_matching=True without static_host1480 # but with static_folder=None should not error.1481 flask.Flask(__name__, host_matching=True, static_folder=None)148214831484def test_request_locals():1485 assert repr(flask.g) == "<LocalProxy unbound>"1486 assert not flask.g148714881489def test_server_name_subdomain():1490 app = flask.Flask(__name__, subdomain_matching=True)1491 client = app.test_client()14921493 @app.route("/")1494 def index():1495 return "default"14961497 @app.route("/", subdomain="foo")1498 def subdomain():1499 return "subdomain"15001501 app.config["SERVER_NAME"] = "dev.local:5000"1502 rv = client.get("/")1503 assert rv.data == b"default"15041505 rv = client.get("/", "http://dev.local:5000")1506 assert rv.data == b"default"15071508 rv = client.get("/", "https://dev.local:5000")1509 assert rv.data == b"default"15101511 app.config["SERVER_NAME"] = "dev.local:443"1512 rv = client.get("/", "https://dev.local")15131514 # Werkzeug 1.0 fixes matching https scheme with 443 port1515 if rv.status_code != 404:1516 assert rv.data == b"default"15171518 app.config["SERVER_NAME"] = "dev.local"1519 rv = client.get("/", "https://dev.local")1520 assert rv.data == b"default"1521Merge branch '2.0.x'David Lordbefore adoptione37e871
lines 1522–1526why, one step back1522 # suppress Werkzeug 0.15 warning about name mismatch1523 with warnings.catch_warnings():1524 warnings.filterwarnings(1525 "ignore", "Current server name", UserWarning, "flask.app"1526 )Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1527–1533why, one step back1527 rv = client.get("/", "http://foo.localhost")1528 assert rv.status_code == 40415291530 rv = client.get("/", "http://foo.dev.local")1531 assert rv.data == b"subdomain"15321533Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae
lines 1534–1536why, one step back1534@pytest.mark.parametrize("key", ["TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None])1535def test_exception_propagation(app, client, key):1536 app.testing = FalseMerge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
line 1537why, one step back1537Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae
lines 1538–1540why, one step back1538 @app.route("/")1539 def index():1540 1 // 0Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
line 1541why, one step back1541Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae
lines 1542–1548why, one step back1542 if key is not None:1543 app.config[key] = True15441545 with pytest.raises(ZeroDivisionError):1546 client.get("/")1547 else:1548 assert client.get("/").status_code == 500Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1549–1619why, one step back154915501551@pytest.mark.parametrize("debug", [True, False])1552@pytest.mark.parametrize("use_debugger", [True, False])1553@pytest.mark.parametrize("use_reloader", [True, False])1554@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1555def test_werkzeug_passthrough_errors(1556 monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1557):1558 rv = {}15591560 # Mocks werkzeug.serving.run_simple method1561 def run_simple_mock(*args, **kwargs):1562 rv["passthrough_errors"] = kwargs.get("passthrough_errors")15631564 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1565 app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1566 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)156715681569def test_max_content_length(app, client):1570 app.config["MAX_CONTENT_LENGTH"] = 6415711572 @app.before_request1573 def always_first():1574 flask.request.form["myfile"]1575 AssertionError()15761577 @app.route("/accept", methods=["POST"])1578 def accept_file():1579 flask.request.form["myfile"]1580 AssertionError()15811582 @app.errorhandler(413)1583 def catcher(error):1584 return "42"15851586 rv = client.post("/accept", data={"myfile": "foo" * 100})1587 assert rv.data == b"42"158815891590def test_url_processors(app, client):1591 @app.url_defaults1592 def add_language_code(endpoint, values):1593 if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1594 endpoint, "lang_code"1595 ):1596 values.setdefault("lang_code", flask.g.lang_code)15971598 @app.url_value_preprocessor1599 def pull_lang_code(endpoint, values):1600 flask.g.lang_code = values.pop("lang_code", None)16011602 @app.route("/<lang_code>/")1603 def index():1604 return flask.url_for("about")16051606 @app.route("/<lang_code>/about")1607 def about():1608 return flask.url_for("something_else")16091610 @app.route("/foo")1611 def something_else():1612 return flask.url_for("about", lang_code="en")16131614 assert client.get("/de/").data == b"/de/about"1615 assert client.get("/de/about").data == b"/foo"1616 assert client.get("/foo").data == b"/en/about"161716181619def test_inject_blueprint_url_defaults(app):Merge remote-tracking branch 'origin/2.0.x'David Lordbefore adoption4240ace
line 1620why, one step back1620 bp = flask.Blueprint("foo", __name__, template_folder="template")Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1621–1632why, one step back16211622 @bp.url_defaults1623 def bp_defaults(endpoint, values):1624 values["page"] = "login"16251626 @bp.route("/<page>")1627 def view(page):1628 pass16291630 app.register_blueprint(bp)16311632 values = dict()Merge remote-tracking branch 'origin/2.0.x'David Lordbefore adoption4240ace
line 1633why, one step back1633 app.inject_url_defaults("foo.view", values)Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1634–1637why, one step back1634 expected = dict(page="login")1635 assert values == expected16361637 with app.test_request_context("/somepage"):Merge remote-tracking branch 'origin/2.0.x'David Lordbefore adoption4240ace
line 1638why, one step back1638 url = flask.url_for("foo.view")Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1639–1651why, one step back1639 expected = "/login"1640 assert url == expected164116421643def test_nonascii_pathinfo(app, client):1644 @app.route("/киртест")1645 def index():1646 return "Hello World!"16471648 rv = client.get("/киртест")1649 assert rv.data == b"Hello World!"16501651Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db
line 1652why, one step back1652def test_no_setup_after_first_request(app, client):Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1653–1661why, one step back1653 app.debug = True16541655 @app.route("/")1656 def index():1657 return "Awesome"16581659 assert not app.got_first_request1660 assert client.get("/").data == b"Awesome"1661Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db
line 1662why, one step back1662 with pytest.raises(AssertionError) as exc_info:Merge branch '2.1.x'David Lordbefore adoptionf976d5b
line 1663why, one step back1663 app.add_url_rule("/foo", endpoint="late")Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
line 1664why, one step back1664Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db
line 1665why, one step back1665 assert "setup method 'add_url_rule'" in str(exc_info.value)Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1666–1667why, one step back16661667Merge pull request #4492 from pallets/debug-messagesDavid Lordbefore adoptionce7b884
line 1668why, one step back1668def test_routing_redirect_debugging(monkeypatch, app, client):Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db
line 1669why, one step back1669 app.config["DEBUG"] = TrueMerge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
line 1670why, one step back1670Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db
lines 1671–1676why, one step back1671 @app.route("/user/", methods=["GET", "POST"])1672 def user():1673 return flask.request.form["status"]16741675 # default redirect code preserves form data1676 rv = client.post("/user", data={"status": "success"}, follow_redirects=True)Merge pull request #4492 from pallets/debug-messagesDavid Lordbefore adoptionce7b884
line 1677why, one step back1677 assert rv.data == b"success"Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
line 1678why, one step back1678Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db
line 1679why, one step back1679 # 301 and 302 raise errorMerge pull request #4492 from pallets/debug-messagesDavid Lordbefore adoptionce7b884
lines 1680–1681why, one step back1680 monkeypatch.setattr(RequestRedirect, "code", 301)1681Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db
lines 1682–1683why, one step back1682 with client, pytest.raises(AssertionError) as exc_info:1683 client.post("/user", data={"status": "error"}, follow_redirects=True)Merge pull request #4492 from pallets/debug-messagesDavid Lordbefore adoptionce7b884
line 1684why, one step back1684Merge pull request #4577 from hallacy/hallacy/fix_4571David Lordbefore adoptiona52a7db
line 1685why, one step back1685 assert "canonical URL 'http://localhost/user/'" in str(exc_info.value)Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1686–1785why, one step back168616871688def test_route_decorator_custom_endpoint(app, client):1689 app.debug = True16901691 @app.route("/foo/")1692 def foo():1693 return flask.request.endpoint16941695 @app.route("/bar/", endpoint="bar")1696 def for_bar():1697 return flask.request.endpoint16981699 @app.route("/bar/123", endpoint="123")1700 def for_bar_foo():1701 return flask.request.endpoint17021703 with app.test_request_context():1704 assert flask.url_for("foo") == "/foo/"1705 assert flask.url_for("bar") == "/bar/"1706 assert flask.url_for("123") == "/bar/123"17071708 assert client.get("/foo/").data == b"foo"1709 assert client.get("/bar/").data == b"bar"1710 assert client.get("/bar/123").data == b"123"171117121713def test_get_method_on_g(app_ctx):1714 assert flask.g.get("x") is None1715 assert flask.g.get("x", 11) == 111716 flask.g.x = 421717 assert flask.g.get("x") == 421718 assert flask.g.x == 42171917201721def test_g_iteration_protocol(app_ctx):1722 flask.g.foo = 231723 flask.g.bar = 421724 assert "foo" in flask.g1725 assert "foos" not in flask.g1726 assert sorted(flask.g) == ["bar", "foo"]172717281729def test_subdomain_basic_support():1730 app = flask.Flask(__name__, subdomain_matching=True)1731 app.config["SERVER_NAME"] = "localhost.localdomain"1732 client = app.test_client()17331734 @app.route("/")1735 def normal_index():1736 return "normal index"17371738 @app.route("/", subdomain="test")1739 def test_index():1740 return "test index"17411742 rv = client.get("/", "http://localhost.localdomain/")1743 assert rv.data == b"normal index"17441745 rv = client.get("/", "http://test.localhost.localdomain/")1746 assert rv.data == b"test index"174717481749def test_subdomain_matching():1750 app = flask.Flask(__name__, subdomain_matching=True)1751 client = app.test_client()1752 app.config["SERVER_NAME"] = "localhost.localdomain"17531754 @app.route("/", subdomain="<user>")1755 def index(user):1756 return f"index for {user}"17571758 rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1759 assert rv.data == b"index for mitsuhiko"176017611762def test_subdomain_matching_with_ports():1763 app = flask.Flask(__name__, subdomain_matching=True)1764 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1765 client = app.test_client()17661767 @app.route("/", subdomain="<user>")1768 def index(user):1769 return f"index for {user}"17701771 rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1772 assert rv.data == b"index for mitsuhiko"177317741775@pytest.mark.parametrize("matching", (False, True))1776def test_subdomain_matching_other_name(matching):1777 app = flask.Flask(__name__, subdomain_matching=matching)1778 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1779 client = app.test_client()17801781 @app.route("/")1782 def index():1783 return "", 20417841785 # suppress Werkzeug 0.15 warning about name mismatchMerge branch '2.0.x'David Lordbefore adoptione37e871
lines 1786–1789why, one step back1786 with warnings.catch_warnings():1787 warnings.filterwarnings(1788 "ignore", "Current server name", UserWarning, "flask.app"1789 )Merge pull request #3960 from pallets/shell-interactive-hookDavid Lordbefore adoption16f51ef
lines 1790–1919why, one step back1790 # ip address can't match name1791 rv = client.get("/", "http://127.0.0.1:3000/")1792 assert rv.status_code == 404 if matching else 20417931794 # allow all subdomains if matching is disabled1795 rv = client.get("/", "http://www.localhost.localdomain:3000/")1796 assert rv.status_code == 404 if matching else 204179717981799def test_multi_route_rules(app, client):1800 @app.route("/")1801 @app.route("/<test>/")1802 def index(test="a"):1803 return test18041805 rv = client.open("/")1806 assert rv.data == b"a"1807 rv = client.open("/b/")1808 assert rv.data == b"b"180918101811def test_multi_route_class_views(app, client):1812 class View:1813 def __init__(self, app):1814 app.add_url_rule("/", "index", self.index)1815 app.add_url_rule("/<test>/", "index", self.index)18161817 def index(self, test="a"):1818 return test18191820 _ = View(app)1821 rv = client.open("/")1822 assert rv.data == b"a"1823 rv = client.open("/b/")1824 assert rv.data == b"b"182518261827def test_run_defaults(monkeypatch, app):1828 rv = {}18291830 # Mocks werkzeug.serving.run_simple method1831 def run_simple_mock(*args, **kwargs):1832 rv["result"] = "running..."18331834 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1835 app.run()1836 assert rv["result"] == "running..."183718381839def test_run_server_port(monkeypatch, app):1840 rv = {}18411842 # Mocks werkzeug.serving.run_simple method1843 def run_simple_mock(hostname, port, application, *args, **kwargs):1844 rv["result"] = f"running on {hostname}:{port} ..."18451846 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1847 hostname, port = "localhost", 80001848 app.run(hostname, port, debug=True)1849 assert rv["result"] == f"running on {hostname}:{port} ..."185018511852@pytest.mark.parametrize(1853 "host,port,server_name,expect_host,expect_port",1854 (1855 (None, None, "pocoo.org:8080", "pocoo.org", 8080),1856 ("localhost", None, "pocoo.org:8080", "localhost", 8080),1857 (None, 80, "pocoo.org:8080", "pocoo.org", 80),1858 ("localhost", 80, "pocoo.org:8080", "localhost", 80),1859 ("localhost", 0, "localhost:8080", "localhost", 0),1860 (None, None, "localhost:8080", "localhost", 8080),1861 (None, None, "localhost:0", "localhost", 0),1862 ),1863)1864def test_run_from_config(1865 monkeypatch, host, port, server_name, expect_host, expect_port, app1866):1867 def run_simple_mock(hostname, port, *args, **kwargs):1868 assert hostname == expect_host1869 assert port == expect_port18701871 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1872 app.config["SERVER_NAME"] = server_name1873 app.run(host, port)187418751876def test_max_cookie_size(app, client, recwarn):1877 app.config["MAX_COOKIE_SIZE"] = 10018781879 # outside app context, default to Werkzeug static value,1880 # which is also the default config1881 response = flask.Response()1882 default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1883 assert response.max_cookie_size == default18841885 # inside app context, use app config1886 with app.app_context():1887 assert flask.Response().max_cookie_size == 10018881889 @app.route("/")1890 def index():1891 r = flask.Response("", status=204)1892 r.set_cookie("foo", "bar" * 100)1893 return r18941895 client.get("/")1896 assert len(recwarn) == 11897 w = recwarn.pop()1898 assert "cookie is too large" in str(w.message)18991900 app.config["MAX_COOKIE_SIZE"] = 019011902 client.get("/")1903 assert len(recwarn) == 0190419051906@require_cpython_gc1907def test_app_freed_on_zero_refcount():1908 # A Flask instance should not create a reference cycle that prevents CPython1909 # from freeing it when all external references to it are released (see #3761).1910 gc.disable()1911 try:1912 app = flask.Flask(__name__)1913 assert app.view_functions["static"]1914 weak = weakref.ref(app)1915 assert weak() is not None1916 del app1917 assert weak() is None1918 finally:1919 gc.enable()