test_basic.py
This file
Path
tests/test_basic.py
2,010 lines · 54.0 KiB · Python
Last changed by
include samesite and secure when removing session cookie (#3726)Mathurshan Vimalesvaranbefore adoption22987b6
History of this fileTake it
1import gc2import re3import sys4import time5import uuid6import weakref7from datetime import datetime8from platform import python_implementation9from threading import Thread1011import pytest12import werkzeug.serving13from werkzeug.exceptions import BadRequest14from werkzeug.exceptions import Forbidden15from werkzeug.exceptions import NotFound16from werkzeug.http import parse_date17from werkzeug.routing import BuildError1819import 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"]495051def test_provide_automatic_options_attr():52 app = flask.Flask(__name__)5354 def index():55 return "Hello World!"5657 index.provide_automatic_options = False58 app.route("/")(index)59 rv = app.test_client().open("/", method="OPTIONS")60 assert rv.status_code == 4056162 app = flask.Flask(__name__)6364 def index2():65 return "Hello World!"6667 index2.provide_automatic_options = True68 app.route("/", methods=["OPTIONS"])(index2)69 rv = app.test_client().open("/", method="OPTIONS")70 assert sorted(rv.allow) == ["OPTIONS"]717273def test_provide_automatic_options_kwarg(app, client):74 def index():75 return flask.request.method7677 def more():78 return flask.request.method7980 app.add_url_rule("/", view_func=index, provide_automatic_options=False)81 app.add_url_rule(82 "/more",83 view_func=more,84 methods=["GET", "POST"],85 provide_automatic_options=False,86 )87 assert client.get("/").data == b"GET"8889 rv = client.post("/")90 assert rv.status_code == 40591 assert sorted(rv.allow) == ["GET", "HEAD"]9293 rv = client.open("/", method="OPTIONS")94 assert rv.status_code == 4059596 rv = client.head("/")97 assert rv.status_code == 20098 assert not rv.data # head truncates99 assert client.post("/more").data == b"POST"100 assert client.get("/more").data == b"GET"101102 rv = client.delete("/more")103 assert rv.status_code == 405104 assert sorted(rv.allow) == ["GET", "HEAD", "POST"]105106 rv = client.open("/more", method="OPTIONS")107 assert rv.status_code == 405108109110def test_request_dispatching(app, client):111 @app.route("/")112 def index():113 return flask.request.method114115 @app.route("/more", methods=["GET", "POST"])116 def more():117 return flask.request.method118119 assert client.get("/").data == b"GET"120 rv = client.post("/")121 assert rv.status_code == 405122 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]123 rv = client.head("/")124 assert rv.status_code == 200125 assert not rv.data # head truncates126 assert client.post("/more").data == b"POST"127 assert client.get("/more").data == b"GET"128 rv = client.delete("/more")129 assert rv.status_code == 405130 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]131132133def test_disallow_string_for_allowed_methods(app):134 with pytest.raises(TypeError):135136 @app.route("/", methods="GET POST")137 def index():138 return "Hey"139140141def test_url_mapping(app, client):142 random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"143144 def index():145 return flask.request.method146147 def more():148 return flask.request.method149150 def options():151 return random_uuid4152153 app.add_url_rule("/", "index", index)154 app.add_url_rule("/more", "more", more, methods=["GET", "POST"])155156 # Issue 1288: Test that automatic options are not added157 # when non-uppercase 'options' in methods158 app.add_url_rule("/options", "options", options, methods=["options"])159160 assert client.get("/").data == b"GET"161 rv = client.post("/")162 assert rv.status_code == 405163 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]164 rv = client.head("/")165 assert rv.status_code == 200166 assert not rv.data # head truncates167 assert client.post("/more").data == b"POST"168 assert client.get("/more").data == b"GET"169 rv = client.delete("/more")170 assert rv.status_code == 405171 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]172 rv = client.open("/options", method="OPTIONS")173 assert rv.status_code == 200174 assert random_uuid4 in rv.data.decode("utf-8")175176177def test_werkzeug_routing(app, client):178 from werkzeug.routing import Submount, Rule179180 app.url_map.add(181 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])182 )183184 def bar():185 return "bar"186187 def index():188 return "index"189190 app.view_functions["bar"] = bar191 app.view_functions["index"] = index192193 assert client.get("/foo/").data == b"index"194 assert client.get("/foo/bar").data == b"bar"195196197def test_endpoint_decorator(app, client):198 from werkzeug.routing import Submount, Rule199200 app.url_map.add(201 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])202 )203204 @app.endpoint("bar")205 def bar():206 return "bar"207208 @app.endpoint("index")209 def index():210 return "index"211212 assert client.get("/foo/").data == b"index"213 assert client.get("/foo/bar").data == b"bar"214215216def test_session(app, client):217 @app.route("/set", methods=["POST"])218 def set():219 assert not flask.session.accessed220 assert not flask.session.modified221 flask.session["value"] = flask.request.form["value"]222 assert flask.session.accessed223 assert flask.session.modified224 return "value set"225226 @app.route("/get")227 def get():228 assert not flask.session.accessed229 assert not flask.session.modified230 v = flask.session.get("value", "None")231 assert flask.session.accessed232 assert not flask.session.modified233 return v234235 assert client.post("/set", data={"value": "42"}).data == b"value set"236 assert client.get("/get").data == b"42"237238239def test_session_using_server_name(app, client):240 app.config.update(SERVER_NAME="example.com")241242 @app.route("/")243 def index():244 flask.session["testing"] = 42245 return "Hello World"246247 rv = client.get("/", "http://example.com/")248 assert "domain=.example.com" in rv.headers["set-cookie"].lower()249 assert "httponly" in rv.headers["set-cookie"].lower()250251252def test_session_using_server_name_and_port(app, client):253 app.config.update(SERVER_NAME="example.com:8080")254255 @app.route("/")256 def index():257 flask.session["testing"] = 42258 return "Hello World"259260 rv = client.get("/", "http://example.com:8080/")261 assert "domain=.example.com" in rv.headers["set-cookie"].lower()262 assert "httponly" in rv.headers["set-cookie"].lower()263264265def test_session_using_server_name_port_and_path(app, client):266 app.config.update(SERVER_NAME="example.com:8080", APPLICATION_ROOT="/foo")267268 @app.route("/")269 def index():270 flask.session["testing"] = 42271 return "Hello World"272273 rv = client.get("/", "http://example.com:8080/foo")274 assert "domain=example.com" in rv.headers["set-cookie"].lower()275 assert "path=/foo" in rv.headers["set-cookie"].lower()276 assert "httponly" in rv.headers["set-cookie"].lower()277278279def test_session_using_application_root(app, client):280 class PrefixPathMiddleware:281 def __init__(self, app, prefix):282 self.app = app283 self.prefix = prefix284285 def __call__(self, environ, start_response):286 environ["SCRIPT_NAME"] = self.prefix287 return self.app(environ, start_response)288289 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, "/bar")290 app.config.update(APPLICATION_ROOT="/bar")291292 @app.route("/")293 def index():294 flask.session["testing"] = 42295 return "Hello World"296297 rv = client.get("/", "http://example.com:8080/")298 assert "path=/bar" in rv.headers["set-cookie"].lower()299300301def test_session_using_session_settings(app, client):302 app.config.update(303 SERVER_NAME="www.example.com:8080",304 APPLICATION_ROOT="/test",305 SESSION_COOKIE_DOMAIN=".example.com",306 SESSION_COOKIE_HTTPONLY=False,307 SESSION_COOKIE_SECURE=True,308 SESSION_COOKIE_SAMESITE="Lax",309 SESSION_COOKIE_PATH="/",310 )311312 @app.route("/")313 def index():314 flask.session["testing"] = 42315 return "Hello World"316317 rv = client.get("/", "http://www.example.com:8080/test/")318 cookie = rv.headers["set-cookie"].lower()319 assert "domain=.example.com" in cookie320 assert "path=/" in cookie321 assert "secure" in cookie322 assert "httponly" not in cookie323 assert "samesite" in cookie324325 @app.route("/clear")326 def clear():327 flask.session.pop("testing", None)328 return "Goodbye World"329330 rv = client.get("/clear", "http://www.example.com:8080/test/")331 cookie = rv.headers["set-cookie"].lower()332 assert "session=;" in cookie333 assert "domain=.example.com" in cookie334 assert "path=/" in cookie335 assert "secure" in cookie336 assert "samesite" in cookie337338339def test_session_using_samesite_attribute(app, client):340 @app.route("/")341 def index():342 flask.session["testing"] = 42343 return "Hello World"344345 app.config.update(SESSION_COOKIE_SAMESITE="invalid")346347 with pytest.raises(ValueError):348 client.get("/")349350 app.config.update(SESSION_COOKIE_SAMESITE=None)351 rv = client.get("/")352 cookie = rv.headers["set-cookie"].lower()353 assert "samesite" not in cookie354355 app.config.update(SESSION_COOKIE_SAMESITE="Strict")356 rv = client.get("/")357 cookie = rv.headers["set-cookie"].lower()358 assert "samesite=strict" in cookie359360 app.config.update(SESSION_COOKIE_SAMESITE="Lax")361 rv = client.get("/")362 cookie = rv.headers["set-cookie"].lower()363 assert "samesite=lax" in cookie364365366def test_session_localhost_warning(recwarn, app, client):367 app.config.update(SERVER_NAME="localhost:5000")368369 @app.route("/")370 def index():371 flask.session["testing"] = 42372 return "testing"373374 rv = client.get("/", "http://localhost:5000/")375 assert "domain" not in rv.headers["set-cookie"].lower()376 w = recwarn.pop(UserWarning)377 assert "'localhost' is not a valid cookie domain" in str(w.message)378379380def test_session_ip_warning(recwarn, app, client):381 app.config.update(SERVER_NAME="127.0.0.1:5000")382383 @app.route("/")384 def index():385 flask.session["testing"] = 42386 return "testing"387388 rv = client.get("/", "http://127.0.0.1:5000/")389 assert "domain=127.0.0.1" in rv.headers["set-cookie"].lower()390 w = recwarn.pop(UserWarning)391 assert "cookie domain is an IP" in str(w.message)392393394def test_missing_session(app):395 app.secret_key = None396397 def expect_exception(f, *args, **kwargs):398 e = pytest.raises(RuntimeError, f, *args, **kwargs)399 assert e.value.args and "session is unavailable" in e.value.args[0]400401 with app.test_request_context():402 assert flask.session.get("missing_key") is None403 expect_exception(flask.session.__setitem__, "foo", 42)404 expect_exception(flask.session.pop, "foo")405406407def test_session_expiration(app, client):408 permanent = True409410 @app.route("/")411 def index():412 flask.session["test"] = 42413 flask.session.permanent = permanent414 return ""415416 @app.route("/test")417 def test():418 return str(flask.session.permanent)419420 rv = client.get("/")421 assert "set-cookie" in rv.headers422 match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])423 expires = parse_date(match.group())424 expected = datetime.utcnow() + app.permanent_session_lifetime425 assert expires.year == expected.year426 assert expires.month == expected.month427 assert expires.day == expected.day428429 rv = client.get("/test")430 assert rv.data == b"True"431432 permanent = False433 rv = client.get("/")434 assert "set-cookie" in rv.headers435 match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])436 assert match is None437438439def test_session_stored_last(app, client):440 @app.after_request441 def modify_session(response):442 flask.session["foo"] = 42443 return response444445 @app.route("/")446 def dump_session_contents():447 return repr(flask.session.get("foo"))448449 assert client.get("/").data == b"None"450 assert client.get("/").data == b"42"451452453def test_session_special_types(app, client):454 now = datetime.utcnow().replace(microsecond=0)455 the_uuid = uuid.uuid4()456457 @app.route("/")458 def dump_session_contents():459 flask.session["t"] = (1, 2, 3)460 flask.session["b"] = b"\xff"461 flask.session["m"] = flask.Markup("<html>")462 flask.session["u"] = the_uuid463 flask.session["d"] = now464 flask.session["t_tag"] = {" t": "not-a-tuple"}465 flask.session["di_t_tag"] = {" t__": "not-a-tuple"}466 flask.session["di_tag"] = {" di": "not-a-dict"}467 return "", 204468469 with client:470 client.get("/")471 s = flask.session472 assert s["t"] == (1, 2, 3)473 assert type(s["b"]) == bytes474 assert s["b"] == b"\xff"475 assert type(s["m"]) == flask.Markup476 assert s["m"] == flask.Markup("<html>")477 assert s["u"] == the_uuid478 assert s["d"] == now479 assert s["t_tag"] == {" t": "not-a-tuple"}480 assert s["di_t_tag"] == {" t__": "not-a-tuple"}481 assert s["di_tag"] == {" di": "not-a-dict"}482483484def test_session_cookie_setting(app):485 is_permanent = True486487 @app.route("/bump")488 def bump():489 rv = flask.session["foo"] = flask.session.get("foo", 0) + 1490 flask.session.permanent = is_permanent491 return str(rv)492493 @app.route("/read")494 def read():495 return str(flask.session.get("foo", 0))496497 def run_test(expect_header):498 with app.test_client() as c:499 assert c.get("/bump").data == b"1"500 assert c.get("/bump").data == b"2"501 assert c.get("/bump").data == b"3"502503 rv = c.get("/read")504 set_cookie = rv.headers.get("set-cookie")505 assert (set_cookie is not None) == expect_header506 assert rv.data == b"3"507508 is_permanent = True509 app.config["SESSION_REFRESH_EACH_REQUEST"] = True510 run_test(expect_header=True)511512 is_permanent = True513 app.config["SESSION_REFRESH_EACH_REQUEST"] = False514 run_test(expect_header=False)515516 is_permanent = False517 app.config["SESSION_REFRESH_EACH_REQUEST"] = True518 run_test(expect_header=False)519520 is_permanent = False521 app.config["SESSION_REFRESH_EACH_REQUEST"] = False522 run_test(expect_header=False)523524525def test_session_vary_cookie(app, client):526 @app.route("/set")527 def set_session():528 flask.session["test"] = "test"529 return ""530531 @app.route("/get")532 def get():533 return flask.session.get("test")534535 @app.route("/getitem")536 def getitem():537 return flask.session["test"]538539 @app.route("/setdefault")540 def setdefault():541 return flask.session.setdefault("test", "default")542543 @app.route("/vary-cookie-header-set")544 def vary_cookie_header_set():545 response = flask.Response()546 response.vary.add("Cookie")547 flask.session["test"] = "test"548 return response549550 @app.route("/vary-header-set")551 def vary_header_set():552 response = flask.Response()553 response.vary.update(("Accept-Encoding", "Accept-Language"))554 flask.session["test"] = "test"555 return response556557 @app.route("/no-vary-header")558 def no_vary_header():559 return ""560561 def expect(path, header_value="Cookie"):562 rv = client.get(path)563564 if header_value:565 # The 'Vary' key should exist in the headers only once.566 assert len(rv.headers.get_all("Vary")) == 1567 assert rv.headers["Vary"] == header_value568 else:569 assert "Vary" not in rv.headers570571 expect("/set")572 expect("/get")573 expect("/getitem")574 expect("/setdefault")575 expect("/vary-cookie-header-set")576 expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")577 expect("/no-vary-header", None)578579580def test_flashes(app, req_ctx):581 assert not flask.session.modified582 flask.flash("Zap")583 flask.session.modified = False584 flask.flash("Zip")585 assert flask.session.modified586 assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]587588589def test_extended_flashing(app):590 # Be sure app.testing=True below, else tests can fail silently.591 #592 # Specifically, if app.testing is not set to True, the AssertionErrors593 # in the view functions will cause a 500 response to the test client594 # instead of propagating exceptions.595596 @app.route("/")597 def index():598 flask.flash("Hello World")599 flask.flash("Hello World", "error")600 flask.flash(flask.Markup("<em>Testing</em>"), "warning")601 return ""602603 @app.route("/test/")604 def test():605 messages = flask.get_flashed_messages()606 assert list(messages) == [607 "Hello World",608 "Hello World",609 flask.Markup("<em>Testing</em>"),610 ]611 return ""612613 @app.route("/test_with_categories/")614 def test_with_categories():615 messages = flask.get_flashed_messages(with_categories=True)616 assert len(messages) == 3617 assert list(messages) == [618 ("message", "Hello World"),619 ("error", "Hello World"),620 ("warning", flask.Markup("<em>Testing</em>")),621 ]622 return ""623624 @app.route("/test_filter/")625 def test_filter():626 messages = flask.get_flashed_messages(627 category_filter=["message"], with_categories=True628 )629 assert list(messages) == [("message", "Hello World")]630 return ""631632 @app.route("/test_filters/")633 def test_filters():634 messages = flask.get_flashed_messages(635 category_filter=["message", "warning"], with_categories=True636 )637 assert list(messages) == [638 ("message", "Hello World"),639 ("warning", flask.Markup("<em>Testing</em>")),640 ]641 return ""642643 @app.route("/test_filters_without_returning_categories/")644 def test_filters2():645 messages = flask.get_flashed_messages(category_filter=["message", "warning"])646 assert len(messages) == 2647 assert messages[0] == "Hello World"648 assert messages[1] == flask.Markup("<em>Testing</em>")649 return ""650651 # Create new test client on each test to clean flashed messages.652653 client = app.test_client()654 client.get("/")655 client.get("/test_with_categories/")656657 client = app.test_client()658 client.get("/")659 client.get("/test_filter/")660661 client = app.test_client()662 client.get("/")663 client.get("/test_filters/")664665 client = app.test_client()666 client.get("/")667 client.get("/test_filters_without_returning_categories/")668669670def test_request_processing(app, client):671 evts = []672673 @app.before_request674 def before_request():675 evts.append("before")676677 @app.after_request678 def after_request(response):679 response.data += b"|after"680 evts.append("after")681 return response682683 @app.route("/")684 def index():685 assert "before" in evts686 assert "after" not in evts687 return "request"688689 assert "after" not in evts690 rv = client.get("/").data691 assert "after" in evts692 assert rv == b"request|after"693694695def test_request_preprocessing_early_return(app, client):696 evts = []697698 @app.before_request699 def before_request1():700 evts.append(1)701702 @app.before_request703 def before_request2():704 evts.append(2)705 return "hello"706707 @app.before_request708 def before_request3():709 evts.append(3)710 return "bye"711712 @app.route("/")713 def index():714 evts.append("index")715 return "damnit"716717 rv = client.get("/").data.strip()718 assert rv == b"hello"719 assert evts == [1, 2]720721722def test_after_request_processing(app, client):723 @app.route("/")724 def index():725 @flask.after_this_request726 def foo(response):727 response.headers["X-Foo"] = "a header"728 return response729730 return "Test"731732 resp = client.get("/")733 assert resp.status_code == 200734 assert resp.headers["X-Foo"] == "a header"735736737def test_teardown_request_handler(app, client):738 called = []739740 @app.teardown_request741 def teardown_request(exc):742 called.append(True)743 return "Ignored"744745 @app.route("/")746 def root():747 return "Response"748749 rv = client.get("/")750 assert rv.status_code == 200751 assert b"Response" in rv.data752 assert len(called) == 1753754755def test_teardown_request_handler_debug_mode(app, client):756 called = []757758 @app.teardown_request759 def teardown_request(exc):760 called.append(True)761 return "Ignored"762763 @app.route("/")764 def root():765 return "Response"766767 rv = client.get("/")768 assert rv.status_code == 200769 assert b"Response" in rv.data770 assert len(called) == 1771772773def test_teardown_request_handler_error(app, client):774 called = []775 app.testing = False776777 @app.teardown_request778 def teardown_request1(exc):779 assert type(exc) == ZeroDivisionError780 called.append(True)781 # This raises a new error and blows away sys.exc_info(), so we can782 # test that all teardown_requests get passed the same original783 # exception.784 try:785 raise TypeError()786 except Exception:787 pass788789 @app.teardown_request790 def teardown_request2(exc):791 assert type(exc) == ZeroDivisionError792 called.append(True)793 # This raises a new error and blows away sys.exc_info(), so we can794 # test that all teardown_requests get passed the same original795 # exception.796 try:797 raise TypeError()798 except Exception:799 pass800801 @app.route("/")802 def fails():803 1 // 0804805 rv = client.get("/")806 assert rv.status_code == 500807 assert b"Internal Server Error" in rv.data808 assert len(called) == 2809810811def test_before_after_request_order(app, client):812 called = []813814 @app.before_request815 def before1():816 called.append(1)817818 @app.before_request819 def before2():820 called.append(2)821822 @app.after_request823 def after1(response):824 called.append(4)825 return response826827 @app.after_request828 def after2(response):829 called.append(3)830 return response831832 @app.teardown_request833 def finish1(exc):834 called.append(6)835836 @app.teardown_request837 def finish2(exc):838 called.append(5)839840 @app.route("/")841 def index():842 return "42"843844 rv = client.get("/")845 assert rv.data == b"42"846 assert called == [1, 2, 3, 4, 5, 6]847848849def test_error_handling(app, client):850 app.testing = False851852 @app.errorhandler(404)853 def not_found(e):854 return "not found", 404855856 @app.errorhandler(500)857 def internal_server_error(e):858 return "internal server error", 500859860 @app.errorhandler(Forbidden)861 def forbidden(e):862 return "forbidden", 403863864 @app.route("/")865 def index():866 flask.abort(404)867868 @app.route("/error")869 def error():870 1 // 0871872 @app.route("/forbidden")873 def error2():874 flask.abort(403)875876 rv = client.get("/")877 assert rv.status_code == 404878 assert rv.data == b"not found"879 rv = client.get("/error")880 assert rv.status_code == 500881 assert b"internal server error" == rv.data882 rv = client.get("/forbidden")883 assert rv.status_code == 403884 assert b"forbidden" == rv.data885886887def test_error_handler_unknown_code(app):888 with pytest.raises(KeyError) as exc_info:889 app.register_error_handler(999, lambda e: ("999", 999))890891 assert "Use a subclass" in exc_info.value.args[0]892893894def test_error_handling_processing(app, client):895 app.testing = False896897 @app.errorhandler(500)898 def internal_server_error(e):899 return "internal server error", 500900901 @app.route("/")902 def broken_func():903 1 // 0904905 @app.after_request906 def after_request(resp):907 resp.mimetype = "text/x-special"908 return resp909910 resp = client.get("/")911 assert resp.mimetype == "text/x-special"912 assert resp.data == b"internal server error"913914915def test_baseexception_error_handling(app, client):916 app.testing = False917918 @app.route("/")919 def broken_func():920 raise KeyboardInterrupt()921922 with pytest.raises(KeyboardInterrupt):923 client.get("/")924925 ctx = flask._request_ctx_stack.top926 assert ctx.preserved927 assert type(ctx._preserved_exc) is KeyboardInterrupt928929930def test_before_request_and_routing_errors(app, client):931 @app.before_request932 def attach_something():933 flask.g.something = "value"934935 @app.errorhandler(404)936 def return_something(error):937 return flask.g.something, 404938939 rv = client.get("/")940 assert rv.status_code == 404941 assert rv.data == b"value"942943944def test_user_error_handling(app, client):945 class MyException(Exception):946 pass947948 @app.errorhandler(MyException)949 def handle_my_exception(e):950 assert isinstance(e, MyException)951 return "42"952953 @app.route("/")954 def index():955 raise MyException()956957 assert client.get("/").data == b"42"958959960def test_http_error_subclass_handling(app, client):961 class ForbiddenSubclass(Forbidden):962 pass963964 @app.errorhandler(ForbiddenSubclass)965 def handle_forbidden_subclass(e):966 assert isinstance(e, ForbiddenSubclass)967 return "banana"968969 @app.errorhandler(403)970 def handle_403(e):971 assert not isinstance(e, ForbiddenSubclass)972 assert isinstance(e, Forbidden)973 return "apple"974975 @app.route("/1")976 def index1():977 raise ForbiddenSubclass()978979 @app.route("/2")980 def index2():981 flask.abort(403)982983 @app.route("/3")984 def index3():985 raise Forbidden()986987 assert client.get("/1").data == b"banana"988 assert client.get("/2").data == b"apple"989 assert client.get("/3").data == b"apple"990991992def test_errorhandler_precedence(app, client):993 class E1(Exception):994 pass995996 class E2(Exception):997 pass998999 class E3(E1, E2):1000 pass10011002 @app.errorhandler(E2)1003 def handle_e2(e):1004 return "E2"10051006 @app.errorhandler(Exception)1007 def handle_exception(e):1008 return "Exception"10091010 @app.route("/E1")1011 def raise_e1():1012 raise E110131014 @app.route("/E3")1015 def raise_e3():1016 raise E310171018 rv = client.get("/E1")1019 assert rv.data == b"Exception"10201021 rv = client.get("/E3")1022 assert rv.data == b"E2"102310241025def test_trapping_of_bad_request_key_errors(app, client):1026 @app.route("/key")1027 def fail():1028 flask.request.form["missing_key"]10291030 @app.route("/abort")1031 def allow_abort():1032 flask.abort(400)10331034 rv = client.get("/key")1035 assert rv.status_code == 4001036 assert b"missing_key" not in rv.data1037 rv = client.get("/abort")1038 assert rv.status_code == 40010391040 app.debug = True1041 with pytest.raises(KeyError) as e:1042 client.get("/key")1043 assert e.errisinstance(BadRequest)1044 assert "missing_key" in e.value.get_description()1045 rv = client.get("/abort")1046 assert rv.status_code == 40010471048 app.debug = False1049 app.config["TRAP_BAD_REQUEST_ERRORS"] = True1050 with pytest.raises(KeyError):1051 client.get("/key")1052 with pytest.raises(BadRequest):1053 client.get("/abort")105410551056def test_trapping_of_all_http_exceptions(app, client):1057 app.config["TRAP_HTTP_EXCEPTIONS"] = True10581059 @app.route("/fail")1060 def fail():1061 flask.abort(404)10621063 with pytest.raises(NotFound):1064 client.get("/fail")106510661067def test_error_handler_after_processor_error(app, client):1068 app.testing = False10691070 @app.before_request1071 def before_request():1072 if _trigger == "before":1073 1 // 010741075 @app.after_request1076 def after_request(response):1077 if _trigger == "after":1078 1 // 01079 return response10801081 @app.route("/")1082 def index():1083 return "Foo"10841085 @app.errorhandler(500)1086 def internal_server_error(e):1087 return "Hello Server Error", 50010881089 for _trigger in "before", "after":1090 rv = client.get("/")1091 assert rv.status_code == 5001092 assert rv.data == b"Hello Server Error"109310941095def test_enctype_debug_helper(app, client):1096 from flask.debughelpers import DebugFilesKeyError10971098 app.debug = True10991100 @app.route("/fail", methods=["POST"])1101 def index():1102 return flask.request.files["foo"].filename11031104 # with statement is important because we leave an exception on the1105 # stack otherwise and we want to ensure that this is not the case1106 # to not negatively affect other tests.1107 with client:1108 with pytest.raises(DebugFilesKeyError) as e:1109 client.post("/fail", data={"foo": "index.txt"})1110 assert "no file contents were transmitted" in str(e.value)1111 assert "This was submitted: 'index.txt'" in str(e.value)111211131114def test_response_types(app, client):1115 @app.route("/text")1116 def from_text():1117 return "Hällo Wörld"11181119 @app.route("/bytes")1120 def from_bytes():1121 return "Hällo Wörld".encode()11221123 @app.route("/full_tuple")1124 def from_full_tuple():1125 return (1126 "Meh",1127 400,1128 {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1129 )11301131 @app.route("/text_headers")1132 def from_text_headers():1133 return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}11341135 @app.route("/text_status")1136 def from_text_status():1137 return "Hi, status!", 40011381139 @app.route("/response_headers")1140 def from_response_headers():1141 return (1142 flask.Response(1143 "Hello world", 404, {"Content-Type": "text/html", "X-Foo": "Baz"}1144 ),1145 {"Content-Type": "text/plain", "X-Foo": "Bar", "X-Bar": "Foo"},1146 )11471148 @app.route("/response_status")1149 def from_response_status():1150 return app.response_class("Hello world", 400), 50011511152 @app.route("/wsgi")1153 def from_wsgi():1154 return NotFound()11551156 @app.route("/dict")1157 def from_dict():1158 return {"foo": "bar"}, 20111591160 assert client.get("/text").data == "Hällo Wörld".encode()1161 assert client.get("/bytes").data == "Hällo Wörld".encode()11621163 rv = client.get("/full_tuple")1164 assert rv.data == b"Meh"1165 assert rv.headers["X-Foo"] == "Testing"1166 assert rv.status_code == 4001167 assert rv.mimetype == "text/plain"11681169 rv = client.get("/text_headers")1170 assert rv.data == b"Hello"1171 assert rv.headers["X-Foo"] == "Test"1172 assert rv.status_code == 2001173 assert rv.mimetype == "text/plain"11741175 rv = client.get("/text_status")1176 assert rv.data == b"Hi, status!"1177 assert rv.status_code == 4001178 assert rv.mimetype == "text/html"11791180 rv = client.get("/response_headers")1181 assert rv.data == b"Hello world"1182 assert rv.content_type == "text/plain"1183 assert rv.headers.getlist("X-Foo") == ["Bar"]1184 assert rv.headers["X-Bar"] == "Foo"1185 assert rv.status_code == 40411861187 rv = client.get("/response_status")1188 assert rv.data == b"Hello world"1189 assert rv.status_code == 50011901191 rv = client.get("/wsgi")1192 assert b"Not Found" in rv.data1193 assert rv.status_code == 40411941195 rv = client.get("/dict")1196 assert rv.json == {"foo": "bar"}1197 assert rv.status_code == 201119811991200def test_response_type_errors():1201 app = flask.Flask(__name__)1202 app.testing = True12031204 @app.route("/none")1205 def from_none():1206 pass12071208 @app.route("/small_tuple")1209 def from_small_tuple():1210 return ("Hello",)12111212 @app.route("/large_tuple")1213 def from_large_tuple():1214 return "Hello", 234, {"X-Foo": "Bar"}, "???"12151216 @app.route("/bad_type")1217 def from_bad_type():1218 return True12191220 @app.route("/bad_wsgi")1221 def from_bad_wsgi():1222 return lambda: None12231224 c = app.test_client()12251226 with pytest.raises(TypeError) as e:1227 c.get("/none")1228 assert "returned None" in str(e.value)1229 assert "from_none" in str(e.value)12301231 with pytest.raises(TypeError) as e:1232 c.get("/small_tuple")1233 assert "tuple must have the form" in str(e.value)12341235 pytest.raises(TypeError, c.get, "/large_tuple")12361237 with pytest.raises(TypeError) as e:1238 c.get("/bad_type")1239 assert "it was a bool" in str(e.value)12401241 pytest.raises(TypeError, c.get, "/bad_wsgi")124212431244def test_make_response(app, req_ctx):1245 rv = flask.make_response()1246 assert rv.status_code == 2001247 assert rv.data == b""1248 assert rv.mimetype == "text/html"12491250 rv = flask.make_response("Awesome")1251 assert rv.status_code == 2001252 assert rv.data == b"Awesome"1253 assert rv.mimetype == "text/html"12541255 rv = flask.make_response("W00t", 404)1256 assert rv.status_code == 4041257 assert rv.data == b"W00t"1258 assert rv.mimetype == "text/html"125912601261def test_make_response_with_response_instance(app, req_ctx):1262 rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1263 assert rv.status_code == 4001264 assert rv.data == b'{"msg":"W00t"}\n'1265 assert rv.mimetype == "application/json"12661267 rv = flask.make_response(flask.Response(""), 400)1268 assert rv.status_code == 4001269 assert rv.data == b""1270 assert rv.mimetype == "text/html"12711272 rv = flask.make_response(1273 flask.Response("", headers={"Content-Type": "text/html"}),1274 400,1275 [("X-Foo", "bar")],1276 )1277 assert rv.status_code == 4001278 assert rv.headers["Content-Type"] == "text/html"1279 assert rv.headers["X-Foo"] == "bar"128012811282def test_jsonify_no_prettyprint(app, req_ctx):1283 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1284 compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1285 uncompressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}12861287 rv = flask.make_response(flask.jsonify(uncompressed_msg), 200)1288 assert rv.data == compressed_msg128912901291def test_jsonify_prettyprint(app, req_ctx):1292 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1293 compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1294 pretty_response = (1295 b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'1296 )12971298 rv = flask.make_response(flask.jsonify(compressed_msg), 200)1299 assert rv.data == pretty_response130013011302def test_jsonify_mimetype(app, req_ctx):1303 app.config.update({"JSONIFY_MIMETYPE": "application/vnd.api+json"})1304 msg = {"msg": {"submsg": "W00t"}}1305 rv = flask.make_response(flask.jsonify(msg), 200)1306 assert rv.mimetype == "application/vnd.api+json"130713081309@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")1310def test_json_dump_dataclass(app, req_ctx):1311 from dataclasses import make_dataclass13121313 Data = make_dataclass("Data", [("name", str)])1314 value = flask.json.dumps(Data("Flask"), app=app)1315 value = flask.json.loads(value, app=app)1316 assert value == {"name": "Flask"}131713181319def test_jsonify_args_and_kwargs_check(app, req_ctx):1320 with pytest.raises(TypeError) as e:1321 flask.jsonify("fake args", kwargs="fake")1322 assert "behavior undefined" in str(e.value)132313241325def test_url_generation(app, req_ctx):1326 @app.route("/hello/<name>", methods=["POST"])1327 def hello():1328 pass13291330 assert flask.url_for("hello", name="test x") == "/hello/test%20x"1331 assert (1332 flask.url_for("hello", name="test x", _external=True)1333 == "http://localhost/hello/test%20x"1334 )133513361337def test_build_error_handler(app):1338 # Test base case, a URL which results in a BuildError.1339 with app.test_request_context():1340 pytest.raises(BuildError, flask.url_for, "spam")13411342 # Verify the error is re-raised if not the current exception.1343 try:1344 with app.test_request_context():1345 flask.url_for("spam")1346 except BuildError as err:1347 error = err1348 try:1349 raise RuntimeError("Test case where BuildError is not current.")1350 except RuntimeError:1351 pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})13521353 # Test a custom handler.1354 def handler(error, endpoint, values):1355 # Just a test.1356 return "/test_handler/"13571358 app.url_build_error_handlers.append(handler)1359 with app.test_request_context():1360 assert flask.url_for("spam") == "/test_handler/"136113621363def test_build_error_handler_reraise(app):1364 # Test a custom handler which reraises the BuildError1365 def handler_raises_build_error(error, endpoint, values):1366 raise error13671368 app.url_build_error_handlers.append(handler_raises_build_error)13691370 with app.test_request_context():1371 pytest.raises(BuildError, flask.url_for, "not.existing")137213731374def test_url_for_passes_special_values_to_build_error_handler(app):1375 @app.url_build_error_handlers.append1376 def handler(error, endpoint, values):1377 assert values == {1378 "_external": False,1379 "_anchor": None,1380 "_method": None,1381 "_scheme": None,1382 }1383 return "handled"13841385 with app.test_request_context():1386 flask.url_for("/")138713881389def test_static_files(app, client):1390 rv = client.get("/static/index.html")1391 assert rv.status_code == 2001392 assert rv.data.strip() == b"<h1>Hello World!</h1>"1393 with app.test_request_context():1394 assert flask.url_for("static", filename="index.html") == "/static/index.html"1395 rv.close()139613971398def test_static_url_path():1399 app = flask.Flask(__name__, static_url_path="/foo")1400 app.testing = True1401 rv = app.test_client().get("/foo/index.html")1402 assert rv.status_code == 2001403 rv.close()14041405 with app.test_request_context():1406 assert flask.url_for("static", filename="index.html") == "/foo/index.html"140714081409def test_static_url_path_with_ending_slash():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_empty_path(app):1421 app = flask.Flask(__name__, static_folder="", static_url_path="")1422 rv = app.test_client().open("/static/index.html", method="GET")1423 assert rv.status_code == 2001424 rv.close()142514261427def test_static_url_empty_path_default(app):1428 app = flask.Flask(__name__, static_folder="")1429 rv = app.test_client().open("/static/index.html", method="GET")1430 assert rv.status_code == 2001431 rv.close()143214331434@pytest.mark.skipif(sys.version_info < (3, 6), reason="requires Python >= 3.6")1435def test_static_folder_with_pathlib_path(app):1436 from pathlib import Path14371438 app = flask.Flask(__name__, static_folder=Path("static"))1439 rv = app.test_client().open("/static/index.html", method="GET")1440 assert rv.status_code == 2001441 rv.close()144214431444def test_static_folder_with_ending_slash():1445 app = flask.Flask(__name__, static_folder="static/")14461447 @app.route("/<path:path>")1448 def catch_all(path):1449 return path14501451 rv = app.test_client().get("/catch/all")1452 assert rv.data == b"catch/all"145314541455def test_static_route_with_host_matching():1456 app = flask.Flask(__name__, host_matching=True, static_host="example.com")1457 c = app.test_client()1458 rv = c.get("http://example.com/static/index.html")1459 assert rv.status_code == 2001460 rv.close()1461 with app.test_request_context():1462 rv = flask.url_for("static", filename="index.html", _external=True)1463 assert rv == "http://example.com/static/index.html"1464 # Providing static_host without host_matching=True should error.1465 with pytest.raises(Exception):1466 flask.Flask(__name__, static_host="example.com")1467 # Providing host_matching=True with static_folder1468 # but without static_host should error.1469 with pytest.raises(Exception):1470 flask.Flask(__name__, host_matching=True)1471 # Providing host_matching=True without static_host1472 # but with static_folder=None should not error.1473 flask.Flask(__name__, host_matching=True, static_folder=None)147414751476def test_request_locals():1477 assert repr(flask.g) == "<LocalProxy unbound>"1478 assert not flask.g147914801481def test_server_name_subdomain():1482 app = flask.Flask(__name__, subdomain_matching=True)1483 client = app.test_client()14841485 @app.route("/")1486 def index():1487 return "default"14881489 @app.route("/", subdomain="foo")1490 def subdomain():1491 return "subdomain"14921493 app.config["SERVER_NAME"] = "dev.local:5000"1494 rv = client.get("/")1495 assert rv.data == b"default"14961497 rv = client.get("/", "http://dev.local:5000")1498 assert rv.data == b"default"14991500 rv = client.get("/", "https://dev.local:5000")1501 assert rv.data == b"default"15021503 app.config["SERVER_NAME"] = "dev.local:443"1504 rv = client.get("/", "https://dev.local")15051506 # Werkzeug 1.0 fixes matching https scheme with 443 port1507 if rv.status_code != 404:1508 assert rv.data == b"default"15091510 app.config["SERVER_NAME"] = "dev.local"1511 rv = client.get("/", "https://dev.local")1512 assert rv.data == b"default"15131514 # suppress Werkzeug 1.0 warning about name mismatch1515 with pytest.warns(None):1516 rv = client.get("/", "http://foo.localhost")1517 assert rv.status_code == 40415181519 rv = client.get("/", "http://foo.dev.local")1520 assert rv.data == b"subdomain"152115221523def test_exception_propagation(app, client):1524 def apprunner(config_key):1525 @app.route("/")1526 def index():1527 1 // 015281529 if config_key is not None:1530 app.config[config_key] = True1531 with pytest.raises(Exception):1532 client.get("/")1533 else:1534 assert client.get("/").status_code == 50015351536 # we have to run this test in an isolated thread because if the1537 # debug flag is set to true and an exception happens the context is1538 # not torn down. This causes other tests that run after this fail1539 # when they expect no exception on the stack.1540 for config_key in "TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None:1541 t = Thread(target=apprunner, args=(config_key,))1542 t.start()1543 t.join()154415451546@pytest.mark.parametrize("debug", [True, False])1547@pytest.mark.parametrize("use_debugger", [True, False])1548@pytest.mark.parametrize("use_reloader", [True, False])1549@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1550def test_werkzeug_passthrough_errors(1551 monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1552):1553 rv = {}15541555 # Mocks werkzeug.serving.run_simple method1556 def run_simple_mock(*args, **kwargs):1557 rv["passthrough_errors"] = kwargs.get("passthrough_errors")15581559 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1560 app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1561 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)156215631564def test_max_content_length(app, client):1565 app.config["MAX_CONTENT_LENGTH"] = 6415661567 @app.before_request1568 def always_first():1569 flask.request.form["myfile"]1570 AssertionError()15711572 @app.route("/accept", methods=["POST"])1573 def accept_file():1574 flask.request.form["myfile"]1575 AssertionError()15761577 @app.errorhandler(413)1578 def catcher(error):1579 return "42"15801581 rv = client.post("/accept", data={"myfile": "foo" * 100})1582 assert rv.data == b"42"158315841585def test_url_processors(app, client):1586 @app.url_defaults1587 def add_language_code(endpoint, values):1588 if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1589 endpoint, "lang_code"1590 ):1591 values.setdefault("lang_code", flask.g.lang_code)15921593 @app.url_value_preprocessor1594 def pull_lang_code(endpoint, values):1595 flask.g.lang_code = values.pop("lang_code", None)15961597 @app.route("/<lang_code>/")1598 def index():1599 return flask.url_for("about")16001601 @app.route("/<lang_code>/about")1602 def about():1603 return flask.url_for("something_else")16041605 @app.route("/foo")1606 def something_else():1607 return flask.url_for("about", lang_code="en")16081609 assert client.get("/de/").data == b"/de/about"1610 assert client.get("/de/about").data == b"/foo"1611 assert client.get("/foo").data == b"/en/about"161216131614def test_inject_blueprint_url_defaults(app):1615 bp = flask.Blueprint("foo.bar.baz", __name__, template_folder="template")16161617 @bp.url_defaults1618 def bp_defaults(endpoint, values):1619 values["page"] = "login"16201621 @bp.route("/<page>")1622 def view(page):1623 pass16241625 app.register_blueprint(bp)16261627 values = dict()1628 app.inject_url_defaults("foo.bar.baz.view", values)1629 expected = dict(page="login")1630 assert values == expected16311632 with app.test_request_context("/somepage"):1633 url = flask.url_for("foo.bar.baz.view")1634 expected = "/login"1635 assert url == expected163616371638def test_nonascii_pathinfo(app, client):1639 @app.route("/киртест")1640 def index():1641 return "Hello World!"16421643 rv = client.get("/киртест")1644 assert rv.data == b"Hello World!"164516461647def test_debug_mode_complains_after_first_request(app, client):1648 app.debug = True16491650 @app.route("/")1651 def index():1652 return "Awesome"16531654 assert not app.got_first_request1655 assert client.get("/").data == b"Awesome"1656 with pytest.raises(AssertionError) as e:16571658 @app.route("/foo")1659 def broken():1660 return "Meh"16611662 assert "A setup function was called" in str(e.value)16631664 app.debug = False16651666 @app.route("/foo")1667 def working():1668 return "Meh"16691670 assert client.get("/foo").data == b"Meh"1671 assert app.got_first_request167216731674def test_before_first_request_functions(app, client):1675 got = []16761677 @app.before_first_request1678 def foo():1679 got.append(42)16801681 client.get("/")1682 assert got == [42]1683 client.get("/")1684 assert got == [42]1685 assert app.got_first_request168616871688def test_before_first_request_functions_concurrent(app, client):1689 got = []16901691 @app.before_first_request1692 def foo():1693 time.sleep(0.2)1694 got.append(42)16951696 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_request170517061707def test_routing_redirect_debugging(app, client):1708 app.debug = True17091710 @app.route("/foo/", methods=["GET", "POST"])1711 def foo():1712 return "success"17131714 with client:1715 with pytest.raises(AssertionError) as e:1716 client.post("/foo", data={})1717 assert "http://localhost/foo/" in str(e.value)1718 assert "Make sure to directly send your POST-request to this URL" in str(1719 e.value1720 )17211722 rv = client.get("/foo", data={}, follow_redirects=True)1723 assert rv.data == b"success"17241725 app.debug = False1726 with client:1727 rv = client.post("/foo", data={}, follow_redirects=True)1728 assert rv.data == b"success"172917301731def test_route_decorator_custom_endpoint(app, client):1732 app.debug = True17331734 @app.route("/foo/")1735 def foo():1736 return flask.request.endpoint17371738 @app.route("/bar/", endpoint="bar")1739 def for_bar():1740 return flask.request.endpoint17411742 @app.route("/bar/123", endpoint="123")1743 def for_bar_foo():1744 return flask.request.endpoint17451746 with app.test_request_context():1747 assert flask.url_for("foo") == "/foo/"1748 assert flask.url_for("bar") == "/bar/"1749 assert flask.url_for("123") == "/bar/123"17501751 assert client.get("/foo/").data == b"foo"1752 assert client.get("/bar/").data == b"bar"1753 assert client.get("/bar/123").data == b"123"175417551756def test_preserve_only_once(app, client):1757 app.debug = True17581759 @app.route("/fail")1760 def fail_func():1761 1 // 017621763 for _x in range(3):1764 with pytest.raises(ZeroDivisionError):1765 client.get("/fail")17661767 assert flask._request_ctx_stack.top is not None1768 assert flask._app_ctx_stack.top is not None1769 # implicit appctx disappears too1770 flask._request_ctx_stack.top.pop()1771 assert flask._request_ctx_stack.top is None1772 assert flask._app_ctx_stack.top is None177317741775def test_preserve_remembers_exception(app, client):1776 app.debug = True1777 errors = []17781779 @app.route("/fail")1780 def fail_func():1781 1 // 017821783 @app.route("/success")1784 def success_func():1785 return "Okay"17861787 @app.teardown_request1788 def teardown_handler(exc):1789 errors.append(exc)17901791 # After this failure we did not yet call the teardown handler1792 with pytest.raises(ZeroDivisionError):1793 client.get("/fail")1794 assert errors == []17951796 # But this request triggers it, and it's an error1797 client.get("/success")1798 assert len(errors) == 21799 assert isinstance(errors[0], ZeroDivisionError)18001801 # At this point another request does nothing.1802 client.get("/success")1803 assert len(errors) == 31804 assert errors[1] is None180518061807def test_get_method_on_g(app_ctx):1808 assert flask.g.get("x") is None1809 assert flask.g.get("x", 11) == 111810 flask.g.x = 421811 assert flask.g.get("x") == 421812 assert flask.g.x == 42181318141815def test_g_iteration_protocol(app_ctx):1816 flask.g.foo = 231817 flask.g.bar = 421818 assert "foo" in flask.g1819 assert "foos" not in flask.g1820 assert sorted(flask.g) == ["bar", "foo"]182118221823def test_subdomain_basic_support():1824 app = flask.Flask(__name__, subdomain_matching=True)1825 app.config["SERVER_NAME"] = "localhost.localdomain"1826 client = app.test_client()18271828 @app.route("/")1829 def normal_index():1830 return "normal index"18311832 @app.route("/", subdomain="test")1833 def test_index():1834 return "test index"18351836 rv = client.get("/", "http://localhost.localdomain/")1837 assert rv.data == b"normal index"18381839 rv = client.get("/", "http://test.localhost.localdomain/")1840 assert rv.data == b"test index"184118421843def test_subdomain_matching():1844 app = flask.Flask(__name__, subdomain_matching=True)1845 client = app.test_client()1846 app.config["SERVER_NAME"] = "localhost.localdomain"18471848 @app.route("/", subdomain="<user>")1849 def index(user):1850 return f"index for {user}"18511852 rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1853 assert rv.data == b"index for mitsuhiko"185418551856def test_subdomain_matching_with_ports():1857 app = flask.Flask(__name__, subdomain_matching=True)1858 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1859 client = app.test_client()18601861 @app.route("/", subdomain="<user>")1862 def index(user):1863 return f"index for {user}"18641865 rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1866 assert rv.data == b"index for mitsuhiko"186718681869@pytest.mark.parametrize("matching", (False, True))1870def test_subdomain_matching_other_name(matching):1871 app = flask.Flask(__name__, subdomain_matching=matching)1872 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1873 client = app.test_client()18741875 @app.route("/")1876 def index():1877 return "", 20418781879 # suppress Werkzeug 0.15 warning about name mismatch1880 with pytest.warns(None):1881 # ip address can't match name1882 rv = client.get("/", "http://127.0.0.1:3000/")1883 assert rv.status_code == 404 if matching else 20418841885 # allow all subdomains if matching is disabled1886 rv = client.get("/", "http://www.localhost.localdomain:3000/")1887 assert rv.status_code == 404 if matching else 204188818891890def test_multi_route_rules(app, client):1891 @app.route("/")1892 @app.route("/<test>/")1893 def index(test="a"):1894 return test18951896 rv = client.open("/")1897 assert rv.data == b"a"1898 rv = client.open("/b/")1899 assert rv.data == b"b"190019011902def test_multi_route_class_views(app, client):1903 class View:1904 def __init__(self, app):1905 app.add_url_rule("/", "index", self.index)1906 app.add_url_rule("/<test>/", "index", self.index)19071908 def index(self, test="a"):1909 return test19101911 _ = View(app)1912 rv = client.open("/")1913 assert rv.data == b"a"1914 rv = client.open("/b/")1915 assert rv.data == b"b"191619171918def test_run_defaults(monkeypatch, app):1919 rv = {}19201921 # Mocks werkzeug.serving.run_simple method1922 def run_simple_mock(*args, **kwargs):1923 rv["result"] = "running..."19241925 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1926 app.run()1927 assert rv["result"] == "running..."192819291930def test_run_server_port(monkeypatch, app):1931 rv = {}19321933 # Mocks werkzeug.serving.run_simple method1934 def run_simple_mock(hostname, port, application, *args, **kwargs):1935 rv["result"] = f"running on {hostname}:{port} ..."19361937 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1938 hostname, port = "localhost", 80001939 app.run(hostname, port, debug=True)1940 assert rv["result"] == f"running on {hostname}:{port} ..."194119421943@pytest.mark.parametrize(1944 "host,port,server_name,expect_host,expect_port",1945 (1946 (None, None, "pocoo.org:8080", "pocoo.org", 8080),1947 ("localhost", None, "pocoo.org:8080", "localhost", 8080),1948 (None, 80, "pocoo.org:8080", "pocoo.org", 80),1949 ("localhost", 80, "pocoo.org:8080", "localhost", 80),1950 ("localhost", 0, "localhost:8080", "localhost", 0),1951 (None, None, "localhost:8080", "localhost", 8080),1952 (None, None, "localhost:0", "localhost", 0),1953 ),1954)1955def test_run_from_config(1956 monkeypatch, host, port, server_name, expect_host, expect_port, app1957):1958 def run_simple_mock(hostname, port, *args, **kwargs):1959 assert hostname == expect_host1960 assert port == expect_port19611962 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1963 app.config["SERVER_NAME"] = server_name1964 app.run(host, port)196519661967def test_max_cookie_size(app, client, recwarn):1968 app.config["MAX_COOKIE_SIZE"] = 10019691970 # outside app context, default to Werkzeug static value,1971 # which is also the default config1972 response = flask.Response()1973 default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1974 assert response.max_cookie_size == default19751976 # inside app context, use app config1977 with app.app_context():1978 assert flask.Response().max_cookie_size == 10019791980 @app.route("/")1981 def index():1982 r = flask.Response("", status=204)1983 r.set_cookie("foo", "bar" * 100)1984 return r19851986 client.get("/")1987 assert len(recwarn) == 11988 w = recwarn.pop()1989 assert "cookie is too large" in str(w.message)19901991 app.config["MAX_COOKIE_SIZE"] = 019921993 client.get("/")1994 assert len(recwarn) == 0199519961997@require_cpython_gc1998def test_app_freed_on_zero_refcount():1999 # A Flask instance should not create a reference cycle that prevents CPython2000 # from freeing it when all external references to it are released (see #3761).The first 2,000 of 2,010 lines.