test_basic.py
This file
Path
tests/test_basic.py
1,997 lines · 53.6 KiB · Python
Last changed by
update requirements (#3823)David Lordbefore adoption373f0dd
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 cookie324325326def test_session_using_samesite_attribute(app, client):327 @app.route("/")328 def index():329 flask.session["testing"] = 42330 return "Hello World"331332 app.config.update(SESSION_COOKIE_SAMESITE="invalid")333334 with pytest.raises(ValueError):335 client.get("/")336337 app.config.update(SESSION_COOKIE_SAMESITE=None)338 rv = client.get("/")339 cookie = rv.headers["set-cookie"].lower()340 assert "samesite" not in cookie341342 app.config.update(SESSION_COOKIE_SAMESITE="Strict")343 rv = client.get("/")344 cookie = rv.headers["set-cookie"].lower()345 assert "samesite=strict" in cookie346347 app.config.update(SESSION_COOKIE_SAMESITE="Lax")348 rv = client.get("/")349 cookie = rv.headers["set-cookie"].lower()350 assert "samesite=lax" in cookie351352353def test_session_localhost_warning(recwarn, app, client):354 app.config.update(SERVER_NAME="localhost:5000")355356 @app.route("/")357 def index():358 flask.session["testing"] = 42359 return "testing"360361 rv = client.get("/", "http://localhost:5000/")362 assert "domain" not in rv.headers["set-cookie"].lower()363 w = recwarn.pop(UserWarning)364 assert "'localhost' is not a valid cookie domain" in str(w.message)365366367def test_session_ip_warning(recwarn, app, client):368 app.config.update(SERVER_NAME="127.0.0.1:5000")369370 @app.route("/")371 def index():372 flask.session["testing"] = 42373 return "testing"374375 rv = client.get("/", "http://127.0.0.1:5000/")376 assert "domain=127.0.0.1" in rv.headers["set-cookie"].lower()377 w = recwarn.pop(UserWarning)378 assert "cookie domain is an IP" in str(w.message)379380381def test_missing_session(app):382 app.secret_key = None383384 def expect_exception(f, *args, **kwargs):385 e = pytest.raises(RuntimeError, f, *args, **kwargs)386 assert e.value.args and "session is unavailable" in e.value.args[0]387388 with app.test_request_context():389 assert flask.session.get("missing_key") is None390 expect_exception(flask.session.__setitem__, "foo", 42)391 expect_exception(flask.session.pop, "foo")392393394def test_session_expiration(app, client):395 permanent = True396397 @app.route("/")398 def index():399 flask.session["test"] = 42400 flask.session.permanent = permanent401 return ""402403 @app.route("/test")404 def test():405 return str(flask.session.permanent)406407 rv = client.get("/")408 assert "set-cookie" in rv.headers409 match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])410 expires = parse_date(match.group())411 expected = datetime.utcnow() + app.permanent_session_lifetime412 assert expires.year == expected.year413 assert expires.month == expected.month414 assert expires.day == expected.day415416 rv = client.get("/test")417 assert rv.data == b"True"418419 permanent = False420 rv = client.get("/")421 assert "set-cookie" in rv.headers422 match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])423 assert match is None424425426def test_session_stored_last(app, client):427 @app.after_request428 def modify_session(response):429 flask.session["foo"] = 42430 return response431432 @app.route("/")433 def dump_session_contents():434 return repr(flask.session.get("foo"))435436 assert client.get("/").data == b"None"437 assert client.get("/").data == b"42"438439440def test_session_special_types(app, client):441 now = datetime.utcnow().replace(microsecond=0)442 the_uuid = uuid.uuid4()443444 @app.route("/")445 def dump_session_contents():446 flask.session["t"] = (1, 2, 3)447 flask.session["b"] = b"\xff"448 flask.session["m"] = flask.Markup("<html>")449 flask.session["u"] = the_uuid450 flask.session["d"] = now451 flask.session["t_tag"] = {" t": "not-a-tuple"}452 flask.session["di_t_tag"] = {" t__": "not-a-tuple"}453 flask.session["di_tag"] = {" di": "not-a-dict"}454 return "", 204455456 with client:457 client.get("/")458 s = flask.session459 assert s["t"] == (1, 2, 3)460 assert type(s["b"]) == bytes461 assert s["b"] == b"\xff"462 assert type(s["m"]) == flask.Markup463 assert s["m"] == flask.Markup("<html>")464 assert s["u"] == the_uuid465 assert s["d"] == now466 assert s["t_tag"] == {" t": "not-a-tuple"}467 assert s["di_t_tag"] == {" t__": "not-a-tuple"}468 assert s["di_tag"] == {" di": "not-a-dict"}469470471def test_session_cookie_setting(app):472 is_permanent = True473474 @app.route("/bump")475 def bump():476 rv = flask.session["foo"] = flask.session.get("foo", 0) + 1477 flask.session.permanent = is_permanent478 return str(rv)479480 @app.route("/read")481 def read():482 return str(flask.session.get("foo", 0))483484 def run_test(expect_header):485 with app.test_client() as c:486 assert c.get("/bump").data == b"1"487 assert c.get("/bump").data == b"2"488 assert c.get("/bump").data == b"3"489490 rv = c.get("/read")491 set_cookie = rv.headers.get("set-cookie")492 assert (set_cookie is not None) == expect_header493 assert rv.data == b"3"494495 is_permanent = True496 app.config["SESSION_REFRESH_EACH_REQUEST"] = True497 run_test(expect_header=True)498499 is_permanent = True500 app.config["SESSION_REFRESH_EACH_REQUEST"] = False501 run_test(expect_header=False)502503 is_permanent = False504 app.config["SESSION_REFRESH_EACH_REQUEST"] = True505 run_test(expect_header=False)506507 is_permanent = False508 app.config["SESSION_REFRESH_EACH_REQUEST"] = False509 run_test(expect_header=False)510511512def test_session_vary_cookie(app, client):513 @app.route("/set")514 def set_session():515 flask.session["test"] = "test"516 return ""517518 @app.route("/get")519 def get():520 return flask.session.get("test")521522 @app.route("/getitem")523 def getitem():524 return flask.session["test"]525526 @app.route("/setdefault")527 def setdefault():528 return flask.session.setdefault("test", "default")529530 @app.route("/vary-cookie-header-set")531 def vary_cookie_header_set():532 response = flask.Response()533 response.vary.add("Cookie")534 flask.session["test"] = "test"535 return response536537 @app.route("/vary-header-set")538 def vary_header_set():539 response = flask.Response()540 response.vary.update(("Accept-Encoding", "Accept-Language"))541 flask.session["test"] = "test"542 return response543544 @app.route("/no-vary-header")545 def no_vary_header():546 return ""547548 def expect(path, header_value="Cookie"):549 rv = client.get(path)550551 if header_value:552 # The 'Vary' key should exist in the headers only once.553 assert len(rv.headers.get_all("Vary")) == 1554 assert rv.headers["Vary"] == header_value555 else:556 assert "Vary" not in rv.headers557558 expect("/set")559 expect("/get")560 expect("/getitem")561 expect("/setdefault")562 expect("/vary-cookie-header-set")563 expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")564 expect("/no-vary-header", None)565566567def test_flashes(app, req_ctx):568 assert not flask.session.modified569 flask.flash("Zap")570 flask.session.modified = False571 flask.flash("Zip")572 assert flask.session.modified573 assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]574575576def test_extended_flashing(app):577 # Be sure app.testing=True below, else tests can fail silently.578 #579 # Specifically, if app.testing is not set to True, the AssertionErrors580 # in the view functions will cause a 500 response to the test client581 # instead of propagating exceptions.582583 @app.route("/")584 def index():585 flask.flash("Hello World")586 flask.flash("Hello World", "error")587 flask.flash(flask.Markup("<em>Testing</em>"), "warning")588 return ""589590 @app.route("/test/")591 def test():592 messages = flask.get_flashed_messages()593 assert list(messages) == [594 "Hello World",595 "Hello World",596 flask.Markup("<em>Testing</em>"),597 ]598 return ""599600 @app.route("/test_with_categories/")601 def test_with_categories():602 messages = flask.get_flashed_messages(with_categories=True)603 assert len(messages) == 3604 assert list(messages) == [605 ("message", "Hello World"),606 ("error", "Hello World"),607 ("warning", flask.Markup("<em>Testing</em>")),608 ]609 return ""610611 @app.route("/test_filter/")612 def test_filter():613 messages = flask.get_flashed_messages(614 category_filter=["message"], with_categories=True615 )616 assert list(messages) == [("message", "Hello World")]617 return ""618619 @app.route("/test_filters/")620 def test_filters():621 messages = flask.get_flashed_messages(622 category_filter=["message", "warning"], with_categories=True623 )624 assert list(messages) == [625 ("message", "Hello World"),626 ("warning", flask.Markup("<em>Testing</em>")),627 ]628 return ""629630 @app.route("/test_filters_without_returning_categories/")631 def test_filters2():632 messages = flask.get_flashed_messages(category_filter=["message", "warning"])633 assert len(messages) == 2634 assert messages[0] == "Hello World"635 assert messages[1] == flask.Markup("<em>Testing</em>")636 return ""637638 # Create new test client on each test to clean flashed messages.639640 client = app.test_client()641 client.get("/")642 client.get("/test_with_categories/")643644 client = app.test_client()645 client.get("/")646 client.get("/test_filter/")647648 client = app.test_client()649 client.get("/")650 client.get("/test_filters/")651652 client = app.test_client()653 client.get("/")654 client.get("/test_filters_without_returning_categories/")655656657def test_request_processing(app, client):658 evts = []659660 @app.before_request661 def before_request():662 evts.append("before")663664 @app.after_request665 def after_request(response):666 response.data += b"|after"667 evts.append("after")668 return response669670 @app.route("/")671 def index():672 assert "before" in evts673 assert "after" not in evts674 return "request"675676 assert "after" not in evts677 rv = client.get("/").data678 assert "after" in evts679 assert rv == b"request|after"680681682def test_request_preprocessing_early_return(app, client):683 evts = []684685 @app.before_request686 def before_request1():687 evts.append(1)688689 @app.before_request690 def before_request2():691 evts.append(2)692 return "hello"693694 @app.before_request695 def before_request3():696 evts.append(3)697 return "bye"698699 @app.route("/")700 def index():701 evts.append("index")702 return "damnit"703704 rv = client.get("/").data.strip()705 assert rv == b"hello"706 assert evts == [1, 2]707708709def test_after_request_processing(app, client):710 @app.route("/")711 def index():712 @flask.after_this_request713 def foo(response):714 response.headers["X-Foo"] = "a header"715 return response716717 return "Test"718719 resp = client.get("/")720 assert resp.status_code == 200721 assert resp.headers["X-Foo"] == "a header"722723724def test_teardown_request_handler(app, client):725 called = []726727 @app.teardown_request728 def teardown_request(exc):729 called.append(True)730 return "Ignored"731732 @app.route("/")733 def root():734 return "Response"735736 rv = client.get("/")737 assert rv.status_code == 200738 assert b"Response" in rv.data739 assert len(called) == 1740741742def test_teardown_request_handler_debug_mode(app, client):743 called = []744745 @app.teardown_request746 def teardown_request(exc):747 called.append(True)748 return "Ignored"749750 @app.route("/")751 def root():752 return "Response"753754 rv = client.get("/")755 assert rv.status_code == 200756 assert b"Response" in rv.data757 assert len(called) == 1758759760def test_teardown_request_handler_error(app, client):761 called = []762 app.testing = False763764 @app.teardown_request765 def teardown_request1(exc):766 assert type(exc) == ZeroDivisionError767 called.append(True)768 # This raises a new error and blows away sys.exc_info(), so we can769 # test that all teardown_requests get passed the same original770 # exception.771 try:772 raise TypeError()773 except Exception:774 pass775776 @app.teardown_request777 def teardown_request2(exc):778 assert type(exc) == ZeroDivisionError779 called.append(True)780 # This raises a new error and blows away sys.exc_info(), so we can781 # test that all teardown_requests get passed the same original782 # exception.783 try:784 raise TypeError()785 except Exception:786 pass787788 @app.route("/")789 def fails():790 1 // 0791792 rv = client.get("/")793 assert rv.status_code == 500794 assert b"Internal Server Error" in rv.data795 assert len(called) == 2796797798def test_before_after_request_order(app, client):799 called = []800801 @app.before_request802 def before1():803 called.append(1)804805 @app.before_request806 def before2():807 called.append(2)808809 @app.after_request810 def after1(response):811 called.append(4)812 return response813814 @app.after_request815 def after2(response):816 called.append(3)817 return response818819 @app.teardown_request820 def finish1(exc):821 called.append(6)822823 @app.teardown_request824 def finish2(exc):825 called.append(5)826827 @app.route("/")828 def index():829 return "42"830831 rv = client.get("/")832 assert rv.data == b"42"833 assert called == [1, 2, 3, 4, 5, 6]834835836def test_error_handling(app, client):837 app.testing = False838839 @app.errorhandler(404)840 def not_found(e):841 return "not found", 404842843 @app.errorhandler(500)844 def internal_server_error(e):845 return "internal server error", 500846847 @app.errorhandler(Forbidden)848 def forbidden(e):849 return "forbidden", 403850851 @app.route("/")852 def index():853 flask.abort(404)854855 @app.route("/error")856 def error():857 1 // 0858859 @app.route("/forbidden")860 def error2():861 flask.abort(403)862863 rv = client.get("/")864 assert rv.status_code == 404865 assert rv.data == b"not found"866 rv = client.get("/error")867 assert rv.status_code == 500868 assert b"internal server error" == rv.data869 rv = client.get("/forbidden")870 assert rv.status_code == 403871 assert b"forbidden" == rv.data872873874def test_error_handler_unknown_code(app):875 with pytest.raises(KeyError) as exc_info:876 app.register_error_handler(999, lambda e: ("999", 999))877878 assert "Use a subclass" in exc_info.value.args[0]879880881def test_error_handling_processing(app, client):882 app.testing = False883884 @app.errorhandler(500)885 def internal_server_error(e):886 return "internal server error", 500887888 @app.route("/")889 def broken_func():890 1 // 0891892 @app.after_request893 def after_request(resp):894 resp.mimetype = "text/x-special"895 return resp896897 resp = client.get("/")898 assert resp.mimetype == "text/x-special"899 assert resp.data == b"internal server error"900901902def test_baseexception_error_handling(app, client):903 app.testing = False904905 @app.route("/")906 def broken_func():907 raise KeyboardInterrupt()908909 with pytest.raises(KeyboardInterrupt):910 client.get("/")911912 ctx = flask._request_ctx_stack.top913 assert ctx.preserved914 assert type(ctx._preserved_exc) is KeyboardInterrupt915916917def test_before_request_and_routing_errors(app, client):918 @app.before_request919 def attach_something():920 flask.g.something = "value"921922 @app.errorhandler(404)923 def return_something(error):924 return flask.g.something, 404925926 rv = client.get("/")927 assert rv.status_code == 404928 assert rv.data == b"value"929930931def test_user_error_handling(app, client):932 class MyException(Exception):933 pass934935 @app.errorhandler(MyException)936 def handle_my_exception(e):937 assert isinstance(e, MyException)938 return "42"939940 @app.route("/")941 def index():942 raise MyException()943944 assert client.get("/").data == b"42"945946947def test_http_error_subclass_handling(app, client):948 class ForbiddenSubclass(Forbidden):949 pass950951 @app.errorhandler(ForbiddenSubclass)952 def handle_forbidden_subclass(e):953 assert isinstance(e, ForbiddenSubclass)954 return "banana"955956 @app.errorhandler(403)957 def handle_403(e):958 assert not isinstance(e, ForbiddenSubclass)959 assert isinstance(e, Forbidden)960 return "apple"961962 @app.route("/1")963 def index1():964 raise ForbiddenSubclass()965966 @app.route("/2")967 def index2():968 flask.abort(403)969970 @app.route("/3")971 def index3():972 raise Forbidden()973974 assert client.get("/1").data == b"banana"975 assert client.get("/2").data == b"apple"976 assert client.get("/3").data == b"apple"977978979def test_errorhandler_precedence(app, client):980 class E1(Exception):981 pass982983 class E2(Exception):984 pass985986 class E3(E1, E2):987 pass988989 @app.errorhandler(E2)990 def handle_e2(e):991 return "E2"992993 @app.errorhandler(Exception)994 def handle_exception(e):995 return "Exception"996997 @app.route("/E1")998 def raise_e1():999 raise E110001001 @app.route("/E3")1002 def raise_e3():1003 raise E310041005 rv = client.get("/E1")1006 assert rv.data == b"Exception"10071008 rv = client.get("/E3")1009 assert rv.data == b"E2"101010111012def test_trapping_of_bad_request_key_errors(app, client):1013 @app.route("/key")1014 def fail():1015 flask.request.form["missing_key"]10161017 @app.route("/abort")1018 def allow_abort():1019 flask.abort(400)10201021 rv = client.get("/key")1022 assert rv.status_code == 4001023 assert b"missing_key" not in rv.data1024 rv = client.get("/abort")1025 assert rv.status_code == 40010261027 app.debug = True1028 with pytest.raises(KeyError) as e:1029 client.get("/key")1030 assert e.errisinstance(BadRequest)1031 assert "missing_key" in e.value.get_description()1032 rv = client.get("/abort")1033 assert rv.status_code == 40010341035 app.debug = False1036 app.config["TRAP_BAD_REQUEST_ERRORS"] = True1037 with pytest.raises(KeyError):1038 client.get("/key")1039 with pytest.raises(BadRequest):1040 client.get("/abort")104110421043def test_trapping_of_all_http_exceptions(app, client):1044 app.config["TRAP_HTTP_EXCEPTIONS"] = True10451046 @app.route("/fail")1047 def fail():1048 flask.abort(404)10491050 with pytest.raises(NotFound):1051 client.get("/fail")105210531054def test_error_handler_after_processor_error(app, client):1055 app.testing = False10561057 @app.before_request1058 def before_request():1059 if _trigger == "before":1060 1 // 010611062 @app.after_request1063 def after_request(response):1064 if _trigger == "after":1065 1 // 01066 return response10671068 @app.route("/")1069 def index():1070 return "Foo"10711072 @app.errorhandler(500)1073 def internal_server_error(e):1074 return "Hello Server Error", 50010751076 for _trigger in "before", "after":1077 rv = client.get("/")1078 assert rv.status_code == 5001079 assert rv.data == b"Hello Server Error"108010811082def test_enctype_debug_helper(app, client):1083 from flask.debughelpers import DebugFilesKeyError10841085 app.debug = True10861087 @app.route("/fail", methods=["POST"])1088 def index():1089 return flask.request.files["foo"].filename10901091 # with statement is important because we leave an exception on the1092 # stack otherwise and we want to ensure that this is not the case1093 # to not negatively affect other tests.1094 with client:1095 with pytest.raises(DebugFilesKeyError) as e:1096 client.post("/fail", data={"foo": "index.txt"})1097 assert "no file contents were transmitted" in str(e.value)1098 assert "This was submitted: 'index.txt'" in str(e.value)109911001101def test_response_types(app, client):1102 @app.route("/text")1103 def from_text():1104 return "Hällo Wörld"11051106 @app.route("/bytes")1107 def from_bytes():1108 return "Hällo Wörld".encode()11091110 @app.route("/full_tuple")1111 def from_full_tuple():1112 return (1113 "Meh",1114 400,1115 {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1116 )11171118 @app.route("/text_headers")1119 def from_text_headers():1120 return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}11211122 @app.route("/text_status")1123 def from_text_status():1124 return "Hi, status!", 40011251126 @app.route("/response_headers")1127 def from_response_headers():1128 return (1129 flask.Response(1130 "Hello world", 404, {"Content-Type": "text/html", "X-Foo": "Baz"}1131 ),1132 {"Content-Type": "text/plain", "X-Foo": "Bar", "X-Bar": "Foo"},1133 )11341135 @app.route("/response_status")1136 def from_response_status():1137 return app.response_class("Hello world", 400), 50011381139 @app.route("/wsgi")1140 def from_wsgi():1141 return NotFound()11421143 @app.route("/dict")1144 def from_dict():1145 return {"foo": "bar"}, 20111461147 assert client.get("/text").data == "Hällo Wörld".encode()1148 assert client.get("/bytes").data == "Hällo Wörld".encode()11491150 rv = client.get("/full_tuple")1151 assert rv.data == b"Meh"1152 assert rv.headers["X-Foo"] == "Testing"1153 assert rv.status_code == 4001154 assert rv.mimetype == "text/plain"11551156 rv = client.get("/text_headers")1157 assert rv.data == b"Hello"1158 assert rv.headers["X-Foo"] == "Test"1159 assert rv.status_code == 2001160 assert rv.mimetype == "text/plain"11611162 rv = client.get("/text_status")1163 assert rv.data == b"Hi, status!"1164 assert rv.status_code == 4001165 assert rv.mimetype == "text/html"11661167 rv = client.get("/response_headers")1168 assert rv.data == b"Hello world"1169 assert rv.content_type == "text/plain"1170 assert rv.headers.getlist("X-Foo") == ["Bar"]1171 assert rv.headers["X-Bar"] == "Foo"1172 assert rv.status_code == 40411731174 rv = client.get("/response_status")1175 assert rv.data == b"Hello world"1176 assert rv.status_code == 50011771178 rv = client.get("/wsgi")1179 assert b"Not Found" in rv.data1180 assert rv.status_code == 40411811182 rv = client.get("/dict")1183 assert rv.json == {"foo": "bar"}1184 assert rv.status_code == 201118511861187def test_response_type_errors():1188 app = flask.Flask(__name__)1189 app.testing = True11901191 @app.route("/none")1192 def from_none():1193 pass11941195 @app.route("/small_tuple")1196 def from_small_tuple():1197 return ("Hello",)11981199 @app.route("/large_tuple")1200 def from_large_tuple():1201 return "Hello", 234, {"X-Foo": "Bar"}, "???"12021203 @app.route("/bad_type")1204 def from_bad_type():1205 return True12061207 @app.route("/bad_wsgi")1208 def from_bad_wsgi():1209 return lambda: None12101211 c = app.test_client()12121213 with pytest.raises(TypeError) as e:1214 c.get("/none")1215 assert "returned None" in str(e.value)1216 assert "from_none" in str(e.value)12171218 with pytest.raises(TypeError) as e:1219 c.get("/small_tuple")1220 assert "tuple must have the form" in str(e.value)12211222 pytest.raises(TypeError, c.get, "/large_tuple")12231224 with pytest.raises(TypeError) as e:1225 c.get("/bad_type")1226 assert "it was a bool" in str(e.value)12271228 pytest.raises(TypeError, c.get, "/bad_wsgi")122912301231def test_make_response(app, req_ctx):1232 rv = flask.make_response()1233 assert rv.status_code == 2001234 assert rv.data == b""1235 assert rv.mimetype == "text/html"12361237 rv = flask.make_response("Awesome")1238 assert rv.status_code == 2001239 assert rv.data == b"Awesome"1240 assert rv.mimetype == "text/html"12411242 rv = flask.make_response("W00t", 404)1243 assert rv.status_code == 4041244 assert rv.data == b"W00t"1245 assert rv.mimetype == "text/html"124612471248def test_make_response_with_response_instance(app, req_ctx):1249 rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1250 assert rv.status_code == 4001251 assert rv.data == b'{"msg":"W00t"}\n'1252 assert rv.mimetype == "application/json"12531254 rv = flask.make_response(flask.Response(""), 400)1255 assert rv.status_code == 4001256 assert rv.data == b""1257 assert rv.mimetype == "text/html"12581259 rv = flask.make_response(1260 flask.Response("", headers={"Content-Type": "text/html"}),1261 400,1262 [("X-Foo", "bar")],1263 )1264 assert rv.status_code == 4001265 assert rv.headers["Content-Type"] == "text/html"1266 assert rv.headers["X-Foo"] == "bar"126712681269def test_jsonify_no_prettyprint(app, req_ctx):1270 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1271 compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1272 uncompressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}12731274 rv = flask.make_response(flask.jsonify(uncompressed_msg), 200)1275 assert rv.data == compressed_msg127612771278def test_jsonify_prettyprint(app, req_ctx):1279 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1280 compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1281 pretty_response = (1282 b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'1283 )12841285 rv = flask.make_response(flask.jsonify(compressed_msg), 200)1286 assert rv.data == pretty_response128712881289def test_jsonify_mimetype(app, req_ctx):1290 app.config.update({"JSONIFY_MIMETYPE": "application/vnd.api+json"})1291 msg = {"msg": {"submsg": "W00t"}}1292 rv = flask.make_response(flask.jsonify(msg), 200)1293 assert rv.mimetype == "application/vnd.api+json"129412951296@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")1297def test_json_dump_dataclass(app, req_ctx):1298 from dataclasses import make_dataclass12991300 Data = make_dataclass("Data", [("name", str)])1301 value = flask.json.dumps(Data("Flask"), app=app)1302 value = flask.json.loads(value, app=app)1303 assert value == {"name": "Flask"}130413051306def test_jsonify_args_and_kwargs_check(app, req_ctx):1307 with pytest.raises(TypeError) as e:1308 flask.jsonify("fake args", kwargs="fake")1309 assert "behavior undefined" in str(e.value)131013111312def test_url_generation(app, req_ctx):1313 @app.route("/hello/<name>", methods=["POST"])1314 def hello():1315 pass13161317 assert flask.url_for("hello", name="test x") == "/hello/test%20x"1318 assert (1319 flask.url_for("hello", name="test x", _external=True)1320 == "http://localhost/hello/test%20x"1321 )132213231324def test_build_error_handler(app):1325 # Test base case, a URL which results in a BuildError.1326 with app.test_request_context():1327 pytest.raises(BuildError, flask.url_for, "spam")13281329 # Verify the error is re-raised if not the current exception.1330 try:1331 with app.test_request_context():1332 flask.url_for("spam")1333 except BuildError as err:1334 error = err1335 try:1336 raise RuntimeError("Test case where BuildError is not current.")1337 except RuntimeError:1338 pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})13391340 # Test a custom handler.1341 def handler(error, endpoint, values):1342 # Just a test.1343 return "/test_handler/"13441345 app.url_build_error_handlers.append(handler)1346 with app.test_request_context():1347 assert flask.url_for("spam") == "/test_handler/"134813491350def test_build_error_handler_reraise(app):1351 # Test a custom handler which reraises the BuildError1352 def handler_raises_build_error(error, endpoint, values):1353 raise error13541355 app.url_build_error_handlers.append(handler_raises_build_error)13561357 with app.test_request_context():1358 pytest.raises(BuildError, flask.url_for, "not.existing")135913601361def test_url_for_passes_special_values_to_build_error_handler(app):1362 @app.url_build_error_handlers.append1363 def handler(error, endpoint, values):1364 assert values == {1365 "_external": False,1366 "_anchor": None,1367 "_method": None,1368 "_scheme": None,1369 }1370 return "handled"13711372 with app.test_request_context():1373 flask.url_for("/")137413751376def test_static_files(app, client):1377 rv = client.get("/static/index.html")1378 assert rv.status_code == 2001379 assert rv.data.strip() == b"<h1>Hello World!</h1>"1380 with app.test_request_context():1381 assert flask.url_for("static", filename="index.html") == "/static/index.html"1382 rv.close()138313841385def test_static_url_path():1386 app = flask.Flask(__name__, static_url_path="/foo")1387 app.testing = True1388 rv = app.test_client().get("/foo/index.html")1389 assert rv.status_code == 2001390 rv.close()13911392 with app.test_request_context():1393 assert flask.url_for("static", filename="index.html") == "/foo/index.html"139413951396def test_static_url_path_with_ending_slash():1397 app = flask.Flask(__name__, static_url_path="/foo/")1398 app.testing = True1399 rv = app.test_client().get("/foo/index.html")1400 assert rv.status_code == 2001401 rv.close()14021403 with app.test_request_context():1404 assert flask.url_for("static", filename="index.html") == "/foo/index.html"140514061407def test_static_url_empty_path(app):1408 app = flask.Flask(__name__, static_folder="", static_url_path="")1409 rv = app.test_client().open("/static/index.html", method="GET")1410 assert rv.status_code == 2001411 rv.close()141214131414def test_static_url_empty_path_default(app):1415 app = flask.Flask(__name__, static_folder="")1416 rv = app.test_client().open("/static/index.html", method="GET")1417 assert rv.status_code == 2001418 rv.close()141914201421@pytest.mark.skipif(sys.version_info < (3, 6), reason="requires Python >= 3.6")1422def test_static_folder_with_pathlib_path(app):1423 from pathlib import Path14241425 app = flask.Flask(__name__, static_folder=Path("static"))1426 rv = app.test_client().open("/static/index.html", method="GET")1427 assert rv.status_code == 2001428 rv.close()142914301431def test_static_folder_with_ending_slash():1432 app = flask.Flask(__name__, static_folder="static/")14331434 @app.route("/<path:path>")1435 def catch_all(path):1436 return path14371438 rv = app.test_client().get("/catch/all")1439 assert rv.data == b"catch/all"144014411442def test_static_route_with_host_matching():1443 app = flask.Flask(__name__, host_matching=True, static_host="example.com")1444 c = app.test_client()1445 rv = c.get("http://example.com/static/index.html")1446 assert rv.status_code == 2001447 rv.close()1448 with app.test_request_context():1449 rv = flask.url_for("static", filename="index.html", _external=True)1450 assert rv == "http://example.com/static/index.html"1451 # Providing static_host without host_matching=True should error.1452 with pytest.raises(Exception):1453 flask.Flask(__name__, static_host="example.com")1454 # Providing host_matching=True with static_folder1455 # but without static_host should error.1456 with pytest.raises(Exception):1457 flask.Flask(__name__, host_matching=True)1458 # Providing host_matching=True without static_host1459 # but with static_folder=None should not error.1460 flask.Flask(__name__, host_matching=True, static_folder=None)146114621463def test_request_locals():1464 assert repr(flask.g) == "<LocalProxy unbound>"1465 assert not flask.g146614671468def test_server_name_subdomain():1469 app = flask.Flask(__name__, subdomain_matching=True)1470 client = app.test_client()14711472 @app.route("/")1473 def index():1474 return "default"14751476 @app.route("/", subdomain="foo")1477 def subdomain():1478 return "subdomain"14791480 app.config["SERVER_NAME"] = "dev.local:5000"1481 rv = client.get("/")1482 assert rv.data == b"default"14831484 rv = client.get("/", "http://dev.local:5000")1485 assert rv.data == b"default"14861487 rv = client.get("/", "https://dev.local:5000")1488 assert rv.data == b"default"14891490 app.config["SERVER_NAME"] = "dev.local:443"1491 rv = client.get("/", "https://dev.local")14921493 # Werkzeug 1.0 fixes matching https scheme with 443 port1494 if rv.status_code != 404:1495 assert rv.data == b"default"14961497 app.config["SERVER_NAME"] = "dev.local"1498 rv = client.get("/", "https://dev.local")1499 assert rv.data == b"default"15001501 # suppress Werkzeug 1.0 warning about name mismatch1502 with pytest.warns(None):1503 rv = client.get("/", "http://foo.localhost")1504 assert rv.status_code == 40415051506 rv = client.get("/", "http://foo.dev.local")1507 assert rv.data == b"subdomain"150815091510def test_exception_propagation(app, client):1511 def apprunner(config_key):1512 @app.route("/")1513 def index():1514 1 // 015151516 if config_key is not None:1517 app.config[config_key] = True1518 with pytest.raises(Exception):1519 client.get("/")1520 else:1521 assert client.get("/").status_code == 50015221523 # we have to run this test in an isolated thread because if the1524 # debug flag is set to true and an exception happens the context is1525 # not torn down. This causes other tests that run after this fail1526 # when they expect no exception on the stack.1527 for config_key in "TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None:1528 t = Thread(target=apprunner, args=(config_key,))1529 t.start()1530 t.join()153115321533@pytest.mark.parametrize("debug", [True, False])1534@pytest.mark.parametrize("use_debugger", [True, False])1535@pytest.mark.parametrize("use_reloader", [True, False])1536@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1537def test_werkzeug_passthrough_errors(1538 monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1539):1540 rv = {}15411542 # Mocks werkzeug.serving.run_simple method1543 def run_simple_mock(*args, **kwargs):1544 rv["passthrough_errors"] = kwargs.get("passthrough_errors")15451546 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1547 app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1548 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)154915501551def test_max_content_length(app, client):1552 app.config["MAX_CONTENT_LENGTH"] = 6415531554 @app.before_request1555 def always_first():1556 flask.request.form["myfile"]1557 AssertionError()15581559 @app.route("/accept", methods=["POST"])1560 def accept_file():1561 flask.request.form["myfile"]1562 AssertionError()15631564 @app.errorhandler(413)1565 def catcher(error):1566 return "42"15671568 rv = client.post("/accept", data={"myfile": "foo" * 100})1569 assert rv.data == b"42"157015711572def test_url_processors(app, client):1573 @app.url_defaults1574 def add_language_code(endpoint, values):1575 if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1576 endpoint, "lang_code"1577 ):1578 values.setdefault("lang_code", flask.g.lang_code)15791580 @app.url_value_preprocessor1581 def pull_lang_code(endpoint, values):1582 flask.g.lang_code = values.pop("lang_code", None)15831584 @app.route("/<lang_code>/")1585 def index():1586 return flask.url_for("about")15871588 @app.route("/<lang_code>/about")1589 def about():1590 return flask.url_for("something_else")15911592 @app.route("/foo")1593 def something_else():1594 return flask.url_for("about", lang_code="en")15951596 assert client.get("/de/").data == b"/de/about"1597 assert client.get("/de/about").data == b"/foo"1598 assert client.get("/foo").data == b"/en/about"159916001601def test_inject_blueprint_url_defaults(app):1602 bp = flask.Blueprint("foo.bar.baz", __name__, template_folder="template")16031604 @bp.url_defaults1605 def bp_defaults(endpoint, values):1606 values["page"] = "login"16071608 @bp.route("/<page>")1609 def view(page):1610 pass16111612 app.register_blueprint(bp)16131614 values = dict()1615 app.inject_url_defaults("foo.bar.baz.view", values)1616 expected = dict(page="login")1617 assert values == expected16181619 with app.test_request_context("/somepage"):1620 url = flask.url_for("foo.bar.baz.view")1621 expected = "/login"1622 assert url == expected162316241625def test_nonascii_pathinfo(app, client):1626 @app.route("/киртест")1627 def index():1628 return "Hello World!"16291630 rv = client.get("/киртест")1631 assert rv.data == b"Hello World!"163216331634def test_debug_mode_complains_after_first_request(app, client):1635 app.debug = True16361637 @app.route("/")1638 def index():1639 return "Awesome"16401641 assert not app.got_first_request1642 assert client.get("/").data == b"Awesome"1643 with pytest.raises(AssertionError) as e:16441645 @app.route("/foo")1646 def broken():1647 return "Meh"16481649 assert "A setup function was called" in str(e.value)16501651 app.debug = False16521653 @app.route("/foo")1654 def working():1655 return "Meh"16561657 assert client.get("/foo").data == b"Meh"1658 assert app.got_first_request165916601661def test_before_first_request_functions(app, client):1662 got = []16631664 @app.before_first_request1665 def foo():1666 got.append(42)16671668 client.get("/")1669 assert got == [42]1670 client.get("/")1671 assert got == [42]1672 assert app.got_first_request167316741675def test_before_first_request_functions_concurrent(app, client):1676 got = []16771678 @app.before_first_request1679 def foo():1680 time.sleep(0.2)1681 got.append(42)16821683 def get_and_assert():1684 client.get("/")1685 assert got == [42]16861687 t = Thread(target=get_and_assert)1688 t.start()1689 get_and_assert()1690 t.join()1691 assert app.got_first_request169216931694def test_routing_redirect_debugging(app, client):1695 app.debug = True16961697 @app.route("/foo/", methods=["GET", "POST"])1698 def foo():1699 return "success"17001701 with client:1702 with pytest.raises(AssertionError) as e:1703 client.post("/foo", data={})1704 assert "http://localhost/foo/" in str(e.value)1705 assert "Make sure to directly send your POST-request to this URL" in str(1706 e.value1707 )17081709 rv = client.get("/foo", data={}, follow_redirects=True)1710 assert rv.data == b"success"17111712 app.debug = False1713 with client:1714 rv = client.post("/foo", data={}, follow_redirects=True)1715 assert rv.data == b"success"171617171718def test_route_decorator_custom_endpoint(app, client):1719 app.debug = True17201721 @app.route("/foo/")1722 def foo():1723 return flask.request.endpoint17241725 @app.route("/bar/", endpoint="bar")1726 def for_bar():1727 return flask.request.endpoint17281729 @app.route("/bar/123", endpoint="123")1730 def for_bar_foo():1731 return flask.request.endpoint17321733 with app.test_request_context():1734 assert flask.url_for("foo") == "/foo/"1735 assert flask.url_for("bar") == "/bar/"1736 assert flask.url_for("123") == "/bar/123"17371738 assert client.get("/foo/").data == b"foo"1739 assert client.get("/bar/").data == b"bar"1740 assert client.get("/bar/123").data == b"123"174117421743def test_preserve_only_once(app, client):1744 app.debug = True17451746 @app.route("/fail")1747 def fail_func():1748 1 // 017491750 for _x in range(3):1751 with pytest.raises(ZeroDivisionError):1752 client.get("/fail")17531754 assert flask._request_ctx_stack.top is not None1755 assert flask._app_ctx_stack.top is not None1756 # implicit appctx disappears too1757 flask._request_ctx_stack.top.pop()1758 assert flask._request_ctx_stack.top is None1759 assert flask._app_ctx_stack.top is None176017611762def test_preserve_remembers_exception(app, client):1763 app.debug = True1764 errors = []17651766 @app.route("/fail")1767 def fail_func():1768 1 // 017691770 @app.route("/success")1771 def success_func():1772 return "Okay"17731774 @app.teardown_request1775 def teardown_handler(exc):1776 errors.append(exc)17771778 # After this failure we did not yet call the teardown handler1779 with pytest.raises(ZeroDivisionError):1780 client.get("/fail")1781 assert errors == []17821783 # But this request triggers it, and it's an error1784 client.get("/success")1785 assert len(errors) == 21786 assert isinstance(errors[0], ZeroDivisionError)17871788 # At this point another request does nothing.1789 client.get("/success")1790 assert len(errors) == 31791 assert errors[1] is None179217931794def test_get_method_on_g(app_ctx):1795 assert flask.g.get("x") is None1796 assert flask.g.get("x", 11) == 111797 flask.g.x = 421798 assert flask.g.get("x") == 421799 assert flask.g.x == 42180018011802def test_g_iteration_protocol(app_ctx):1803 flask.g.foo = 231804 flask.g.bar = 421805 assert "foo" in flask.g1806 assert "foos" not in flask.g1807 assert sorted(flask.g) == ["bar", "foo"]180818091810def test_subdomain_basic_support():1811 app = flask.Flask(__name__, subdomain_matching=True)1812 app.config["SERVER_NAME"] = "localhost.localdomain"1813 client = app.test_client()18141815 @app.route("/")1816 def normal_index():1817 return "normal index"18181819 @app.route("/", subdomain="test")1820 def test_index():1821 return "test index"18221823 rv = client.get("/", "http://localhost.localdomain/")1824 assert rv.data == b"normal index"18251826 rv = client.get("/", "http://test.localhost.localdomain/")1827 assert rv.data == b"test index"182818291830def test_subdomain_matching():1831 app = flask.Flask(__name__, subdomain_matching=True)1832 client = app.test_client()1833 app.config["SERVER_NAME"] = "localhost.localdomain"18341835 @app.route("/", subdomain="<user>")1836 def index(user):1837 return f"index for {user}"18381839 rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1840 assert rv.data == b"index for mitsuhiko"184118421843def test_subdomain_matching_with_ports():1844 app = flask.Flask(__name__, subdomain_matching=True)1845 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1846 client = app.test_client()18471848 @app.route("/", subdomain="<user>")1849 def index(user):1850 return f"index for {user}"18511852 rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1853 assert rv.data == b"index for mitsuhiko"185418551856@pytest.mark.parametrize("matching", (False, True))1857def test_subdomain_matching_other_name(matching):1858 app = flask.Flask(__name__, subdomain_matching=matching)1859 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1860 client = app.test_client()18611862 @app.route("/")1863 def index():1864 return "", 20418651866 # suppress Werkzeug 0.15 warning about name mismatch1867 with pytest.warns(None):1868 # ip address can't match name1869 rv = client.get("/", "http://127.0.0.1:3000/")1870 assert rv.status_code == 404 if matching else 20418711872 # allow all subdomains if matching is disabled1873 rv = client.get("/", "http://www.localhost.localdomain:3000/")1874 assert rv.status_code == 404 if matching else 204187518761877def test_multi_route_rules(app, client):1878 @app.route("/")1879 @app.route("/<test>/")1880 def index(test="a"):1881 return test18821883 rv = client.open("/")1884 assert rv.data == b"a"1885 rv = client.open("/b/")1886 assert rv.data == b"b"188718881889def test_multi_route_class_views(app, client):1890 class View:1891 def __init__(self, app):1892 app.add_url_rule("/", "index", self.index)1893 app.add_url_rule("/<test>/", "index", self.index)18941895 def index(self, test="a"):1896 return test18971898 _ = View(app)1899 rv = client.open("/")1900 assert rv.data == b"a"1901 rv = client.open("/b/")1902 assert rv.data == b"b"190319041905def test_run_defaults(monkeypatch, app):1906 rv = {}19071908 # Mocks werkzeug.serving.run_simple method1909 def run_simple_mock(*args, **kwargs):1910 rv["result"] = "running..."19111912 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1913 app.run()1914 assert rv["result"] == "running..."191519161917def test_run_server_port(monkeypatch, app):1918 rv = {}19191920 # Mocks werkzeug.serving.run_simple method1921 def run_simple_mock(hostname, port, application, *args, **kwargs):1922 rv["result"] = f"running on {hostname}:{port} ..."19231924 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1925 hostname, port = "localhost", 80001926 app.run(hostname, port, debug=True)1927 assert rv["result"] == f"running on {hostname}:{port} ..."192819291930@pytest.mark.parametrize(1931 "host,port,server_name,expect_host,expect_port",1932 (1933 (None, None, "pocoo.org:8080", "pocoo.org", 8080),1934 ("localhost", None, "pocoo.org:8080", "localhost", 8080),1935 (None, 80, "pocoo.org:8080", "pocoo.org", 80),1936 ("localhost", 80, "pocoo.org:8080", "localhost", 80),1937 ("localhost", 0, "localhost:8080", "localhost", 0),1938 (None, None, "localhost:8080", "localhost", 8080),1939 (None, None, "localhost:0", "localhost", 0),1940 ),1941)1942def test_run_from_config(1943 monkeypatch, host, port, server_name, expect_host, expect_port, app1944):1945 def run_simple_mock(hostname, port, *args, **kwargs):1946 assert hostname == expect_host1947 assert port == expect_port19481949 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1950 app.config["SERVER_NAME"] = server_name1951 app.run(host, port)195219531954def test_max_cookie_size(app, client, recwarn):1955 app.config["MAX_COOKIE_SIZE"] = 10019561957 # outside app context, default to Werkzeug static value,1958 # which is also the default config1959 response = flask.Response()1960 default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1961 assert response.max_cookie_size == default19621963 # inside app context, use app config1964 with app.app_context():1965 assert flask.Response().max_cookie_size == 10019661967 @app.route("/")1968 def index():1969 r = flask.Response("", status=204)1970 r.set_cookie("foo", "bar" * 100)1971 return r19721973 client.get("/")1974 assert len(recwarn) == 11975 w = recwarn.pop()1976 assert "cookie is too large" in str(w.message)19771978 app.config["MAX_COOKIE_SIZE"] = 019791980 client.get("/")1981 assert len(recwarn) == 0198219831984@require_cpython_gc1985def test_app_freed_on_zero_refcount():1986 # A Flask instance should not create a reference cycle that prevents CPython1987 # from freeing it when all external references to it are released (see #3761).1988 gc.disable()1989 try:1990 app = flask.Flask(__name__)1991 assert app.view_functions["static"]1992 weak = weakref.ref(app)1993 assert weak() is not None1994 del app1995 assert weak() is None1996 finally:1997 gc.enable()