test_basic.py
This file
Path
tests/test_basic.py
1,959 lines · 52.5 KiB · Python
Last changed by
remove unused module docstringsDavid Lordbefore adoptionf2f027d
History of this fileTake it
1import re2import sys3import time4import uuid5from datetime import datetime6from threading import Thread78import pytest9import werkzeug.serving10from werkzeug.exceptions import BadRequest11from werkzeug.exceptions import Forbidden12from werkzeug.exceptions import NotFound13from werkzeug.http import parse_date14from werkzeug.routing import BuildError1516import flask171819def test_options_work(app, client):20 @app.route("/", methods=["GET", "POST"])21 def index():22 return "Hello World"2324 rv = client.open("/", method="OPTIONS")25 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]26 assert rv.data == b""272829def test_options_on_multiple_rules(app, client):30 @app.route("/", methods=["GET", "POST"])31 def index():32 return "Hello World"3334 @app.route("/", methods=["PUT"])35 def index_put():36 return "Aha!"3738 rv = client.open("/", method="OPTIONS")39 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST", "PUT"]404142def test_provide_automatic_options_attr():43 app = flask.Flask(__name__)4445 def index():46 return "Hello World!"4748 index.provide_automatic_options = False49 app.route("/")(index)50 rv = app.test_client().open("/", method="OPTIONS")51 assert rv.status_code == 4055253 app = flask.Flask(__name__)5455 def index2():56 return "Hello World!"5758 index2.provide_automatic_options = True59 app.route("/", methods=["OPTIONS"])(index2)60 rv = app.test_client().open("/", method="OPTIONS")61 assert sorted(rv.allow) == ["OPTIONS"]626364def test_provide_automatic_options_kwarg(app, client):65 def index():66 return flask.request.method6768 def more():69 return flask.request.method7071 app.add_url_rule("/", view_func=index, provide_automatic_options=False)72 app.add_url_rule(73 "/more",74 view_func=more,75 methods=["GET", "POST"],76 provide_automatic_options=False,77 )78 assert client.get("/").data == b"GET"7980 rv = client.post("/")81 assert rv.status_code == 40582 assert sorted(rv.allow) == ["GET", "HEAD"]8384 rv = client.open("/", method="OPTIONS")85 assert rv.status_code == 4058687 rv = client.head("/")88 assert rv.status_code == 20089 assert not rv.data # head truncates90 assert client.post("/more").data == b"POST"91 assert client.get("/more").data == b"GET"9293 rv = client.delete("/more")94 assert rv.status_code == 40595 assert sorted(rv.allow) == ["GET", "HEAD", "POST"]9697 rv = client.open("/more", method="OPTIONS")98 assert rv.status_code == 40599100101def test_request_dispatching(app, client):102 @app.route("/")103 def index():104 return flask.request.method105106 @app.route("/more", methods=["GET", "POST"])107 def more():108 return flask.request.method109110 assert client.get("/").data == b"GET"111 rv = client.post("/")112 assert rv.status_code == 405113 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]114 rv = client.head("/")115 assert rv.status_code == 200116 assert not rv.data # head truncates117 assert client.post("/more").data == b"POST"118 assert client.get("/more").data == b"GET"119 rv = client.delete("/more")120 assert rv.status_code == 405121 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]122123124def test_disallow_string_for_allowed_methods(app):125 with pytest.raises(TypeError):126127 @app.route("/", methods="GET POST")128 def index():129 return "Hey"130131132def test_url_mapping(app, client):133 random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"134135 def index():136 return flask.request.method137138 def more():139 return flask.request.method140141 def options():142 return random_uuid4143144 app.add_url_rule("/", "index", index)145 app.add_url_rule("/more", "more", more, methods=["GET", "POST"])146147 # Issue 1288: Test that automatic options are not added148 # when non-uppercase 'options' in methods149 app.add_url_rule("/options", "options", options, methods=["options"])150151 assert client.get("/").data == b"GET"152 rv = client.post("/")153 assert rv.status_code == 405154 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]155 rv = client.head("/")156 assert rv.status_code == 200157 assert not rv.data # head truncates158 assert client.post("/more").data == b"POST"159 assert client.get("/more").data == b"GET"160 rv = client.delete("/more")161 assert rv.status_code == 405162 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]163 rv = client.open("/options", method="OPTIONS")164 assert rv.status_code == 200165 assert random_uuid4 in rv.data.decode("utf-8")166167168def test_werkzeug_routing(app, client):169 from werkzeug.routing import Submount, Rule170171 app.url_map.add(172 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])173 )174175 def bar():176 return "bar"177178 def index():179 return "index"180181 app.view_functions["bar"] = bar182 app.view_functions["index"] = index183184 assert client.get("/foo/").data == b"index"185 assert client.get("/foo/bar").data == b"bar"186187188def test_endpoint_decorator(app, client):189 from werkzeug.routing import Submount, Rule190191 app.url_map.add(192 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])193 )194195 @app.endpoint("bar")196 def bar():197 return "bar"198199 @app.endpoint("index")200 def index():201 return "index"202203 assert client.get("/foo/").data == b"index"204 assert client.get("/foo/bar").data == b"bar"205206207def test_session(app, client):208 @app.route("/set", methods=["POST"])209 def set():210 assert not flask.session.accessed211 assert not flask.session.modified212 flask.session["value"] = flask.request.form["value"]213 assert flask.session.accessed214 assert flask.session.modified215 return "value set"216217 @app.route("/get")218 def get():219 assert not flask.session.accessed220 assert not flask.session.modified221 v = flask.session.get("value", "None")222 assert flask.session.accessed223 assert not flask.session.modified224 return v225226 assert client.post("/set", data={"value": "42"}).data == b"value set"227 assert client.get("/get").data == b"42"228229230def test_session_using_server_name(app, client):231 app.config.update(SERVER_NAME="example.com")232233 @app.route("/")234 def index():235 flask.session["testing"] = 42236 return "Hello World"237238 rv = client.get("/", "http://example.com/")239 assert "domain=.example.com" in rv.headers["set-cookie"].lower()240 assert "httponly" in rv.headers["set-cookie"].lower()241242243def test_session_using_server_name_and_port(app, client):244 app.config.update(SERVER_NAME="example.com:8080")245246 @app.route("/")247 def index():248 flask.session["testing"] = 42249 return "Hello World"250251 rv = client.get("/", "http://example.com:8080/")252 assert "domain=.example.com" in rv.headers["set-cookie"].lower()253 assert "httponly" in rv.headers["set-cookie"].lower()254255256def test_session_using_server_name_port_and_path(app, client):257 app.config.update(SERVER_NAME="example.com:8080", APPLICATION_ROOT="/foo")258259 @app.route("/")260 def index():261 flask.session["testing"] = 42262 return "Hello World"263264 rv = client.get("/", "http://example.com:8080/foo")265 assert "domain=example.com" in rv.headers["set-cookie"].lower()266 assert "path=/foo" in rv.headers["set-cookie"].lower()267 assert "httponly" in rv.headers["set-cookie"].lower()268269270def test_session_using_application_root(app, client):271 class PrefixPathMiddleware:272 def __init__(self, app, prefix):273 self.app = app274 self.prefix = prefix275276 def __call__(self, environ, start_response):277 environ["SCRIPT_NAME"] = self.prefix278 return self.app(environ, start_response)279280 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, "/bar")281 app.config.update(APPLICATION_ROOT="/bar")282283 @app.route("/")284 def index():285 flask.session["testing"] = 42286 return "Hello World"287288 rv = client.get("/", "http://example.com:8080/")289 assert "path=/bar" in rv.headers["set-cookie"].lower()290291292def test_session_using_session_settings(app, client):293 app.config.update(294 SERVER_NAME="www.example.com:8080",295 APPLICATION_ROOT="/test",296 SESSION_COOKIE_DOMAIN=".example.com",297 SESSION_COOKIE_HTTPONLY=False,298 SESSION_COOKIE_SECURE=True,299 SESSION_COOKIE_SAMESITE="Lax",300 SESSION_COOKIE_PATH="/",301 )302303 @app.route("/")304 def index():305 flask.session["testing"] = 42306 return "Hello World"307308 rv = client.get("/", "http://www.example.com:8080/test/")309 cookie = rv.headers["set-cookie"].lower()310 assert "domain=.example.com" in cookie311 assert "path=/" in cookie312 assert "secure" in cookie313 assert "httponly" not in cookie314 assert "samesite" in cookie315316317def test_session_using_samesite_attribute(app, client):318 @app.route("/")319 def index():320 flask.session["testing"] = 42321 return "Hello World"322323 app.config.update(SESSION_COOKIE_SAMESITE="invalid")324325 with pytest.raises(ValueError):326 client.get("/")327328 app.config.update(SESSION_COOKIE_SAMESITE=None)329 rv = client.get("/")330 cookie = rv.headers["set-cookie"].lower()331 assert "samesite" not in cookie332333 app.config.update(SESSION_COOKIE_SAMESITE="Strict")334 rv = client.get("/")335 cookie = rv.headers["set-cookie"].lower()336 assert "samesite=strict" in cookie337338 app.config.update(SESSION_COOKIE_SAMESITE="Lax")339 rv = client.get("/")340 cookie = rv.headers["set-cookie"].lower()341 assert "samesite=lax" in cookie342343344def test_session_localhost_warning(recwarn, app, client):345 app.config.update(SERVER_NAME="localhost:5000")346347 @app.route("/")348 def index():349 flask.session["testing"] = 42350 return "testing"351352 rv = client.get("/", "http://localhost:5000/")353 assert "domain" not in rv.headers["set-cookie"].lower()354 w = recwarn.pop(UserWarning)355 assert "'localhost' is not a valid cookie domain" in str(w.message)356357358def test_session_ip_warning(recwarn, app, client):359 app.config.update(SERVER_NAME="127.0.0.1:5000")360361 @app.route("/")362 def index():363 flask.session["testing"] = 42364 return "testing"365366 rv = client.get("/", "http://127.0.0.1:5000/")367 assert "domain=127.0.0.1" in rv.headers["set-cookie"].lower()368 w = recwarn.pop(UserWarning)369 assert "cookie domain is an IP" in str(w.message)370371372def test_missing_session(app):373 app.secret_key = None374375 def expect_exception(f, *args, **kwargs):376 e = pytest.raises(RuntimeError, f, *args, **kwargs)377 assert e.value.args and "session is unavailable" in e.value.args[0]378379 with app.test_request_context():380 assert flask.session.get("missing_key") is None381 expect_exception(flask.session.__setitem__, "foo", 42)382 expect_exception(flask.session.pop, "foo")383384385def test_session_expiration(app, client):386 permanent = True387388 @app.route("/")389 def index():390 flask.session["test"] = 42391 flask.session.permanent = permanent392 return ""393394 @app.route("/test")395 def test():396 return str(flask.session.permanent)397398 rv = client.get("/")399 assert "set-cookie" in rv.headers400 match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])401 expires = parse_date(match.group())402 expected = datetime.utcnow() + app.permanent_session_lifetime403 assert expires.year == expected.year404 assert expires.month == expected.month405 assert expires.day == expected.day406407 rv = client.get("/test")408 assert rv.data == b"True"409410 permanent = False411 rv = client.get("/")412 assert "set-cookie" in rv.headers413 match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])414 assert match is None415416417def test_session_stored_last(app, client):418 @app.after_request419 def modify_session(response):420 flask.session["foo"] = 42421 return response422423 @app.route("/")424 def dump_session_contents():425 return repr(flask.session.get("foo"))426427 assert client.get("/").data == b"None"428 assert client.get("/").data == b"42"429430431def test_session_special_types(app, client):432 now = datetime.utcnow().replace(microsecond=0)433 the_uuid = uuid.uuid4()434435 @app.route("/")436 def dump_session_contents():437 flask.session["t"] = (1, 2, 3)438 flask.session["b"] = b"\xff"439 flask.session["m"] = flask.Markup("<html>")440 flask.session["u"] = the_uuid441 flask.session["d"] = now442 flask.session["t_tag"] = {" t": "not-a-tuple"}443 flask.session["di_t_tag"] = {" t__": "not-a-tuple"}444 flask.session["di_tag"] = {" di": "not-a-dict"}445 return "", 204446447 with client:448 client.get("/")449 s = flask.session450 assert s["t"] == (1, 2, 3)451 assert type(s["b"]) == bytes452 assert s["b"] == b"\xff"453 assert type(s["m"]) == flask.Markup454 assert s["m"] == flask.Markup("<html>")455 assert s["u"] == the_uuid456 assert s["d"] == now457 assert s["t_tag"] == {" t": "not-a-tuple"}458 assert s["di_t_tag"] == {" t__": "not-a-tuple"}459 assert s["di_tag"] == {" di": "not-a-dict"}460461462def test_session_cookie_setting(app):463 is_permanent = True464465 @app.route("/bump")466 def bump():467 rv = flask.session["foo"] = flask.session.get("foo", 0) + 1468 flask.session.permanent = is_permanent469 return str(rv)470471 @app.route("/read")472 def read():473 return str(flask.session.get("foo", 0))474475 def run_test(expect_header):476 with app.test_client() as c:477 assert c.get("/bump").data == b"1"478 assert c.get("/bump").data == b"2"479 assert c.get("/bump").data == b"3"480481 rv = c.get("/read")482 set_cookie = rv.headers.get("set-cookie")483 assert (set_cookie is not None) == expect_header484 assert rv.data == b"3"485486 is_permanent = True487 app.config["SESSION_REFRESH_EACH_REQUEST"] = True488 run_test(expect_header=True)489490 is_permanent = True491 app.config["SESSION_REFRESH_EACH_REQUEST"] = False492 run_test(expect_header=False)493494 is_permanent = False495 app.config["SESSION_REFRESH_EACH_REQUEST"] = True496 run_test(expect_header=False)497498 is_permanent = False499 app.config["SESSION_REFRESH_EACH_REQUEST"] = False500 run_test(expect_header=False)501502503def test_session_vary_cookie(app, client):504 @app.route("/set")505 def set_session():506 flask.session["test"] = "test"507 return ""508509 @app.route("/get")510 def get():511 return flask.session.get("test")512513 @app.route("/getitem")514 def getitem():515 return flask.session["test"]516517 @app.route("/setdefault")518 def setdefault():519 return flask.session.setdefault("test", "default")520521 @app.route("/vary-cookie-header-set")522 def vary_cookie_header_set():523 response = flask.Response()524 response.vary.add("Cookie")525 flask.session["test"] = "test"526 return response527528 @app.route("/vary-header-set")529 def vary_header_set():530 response = flask.Response()531 response.vary.update(("Accept-Encoding", "Accept-Language"))532 flask.session["test"] = "test"533 return response534535 @app.route("/no-vary-header")536 def no_vary_header():537 return ""538539 def expect(path, header_value="Cookie"):540 rv = client.get(path)541542 if header_value:543 # The 'Vary' key should exist in the headers only once.544 assert len(rv.headers.get_all("Vary")) == 1545 assert rv.headers["Vary"] == header_value546 else:547 assert "Vary" not in rv.headers548549 expect("/set")550 expect("/get")551 expect("/getitem")552 expect("/setdefault")553 expect("/vary-cookie-header-set")554 expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")555 expect("/no-vary-header", None)556557558def test_flashes(app, req_ctx):559 assert not flask.session.modified560 flask.flash("Zap")561 flask.session.modified = False562 flask.flash("Zip")563 assert flask.session.modified564 assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]565566567def test_extended_flashing(app):568 # Be sure app.testing=True below, else tests can fail silently.569 #570 # Specifically, if app.testing is not set to True, the AssertionErrors571 # in the view functions will cause a 500 response to the test client572 # instead of propagating exceptions.573574 @app.route("/")575 def index():576 flask.flash("Hello World")577 flask.flash("Hello World", "error")578 flask.flash(flask.Markup("<em>Testing</em>"), "warning")579 return ""580581 @app.route("/test/")582 def test():583 messages = flask.get_flashed_messages()584 assert list(messages) == [585 "Hello World",586 "Hello World",587 flask.Markup("<em>Testing</em>"),588 ]589 return ""590591 @app.route("/test_with_categories/")592 def test_with_categories():593 messages = flask.get_flashed_messages(with_categories=True)594 assert len(messages) == 3595 assert list(messages) == [596 ("message", "Hello World"),597 ("error", "Hello World"),598 ("warning", flask.Markup("<em>Testing</em>")),599 ]600 return ""601602 @app.route("/test_filter/")603 def test_filter():604 messages = flask.get_flashed_messages(605 category_filter=["message"], with_categories=True606 )607 assert list(messages) == [("message", "Hello World")]608 return ""609610 @app.route("/test_filters/")611 def test_filters():612 messages = flask.get_flashed_messages(613 category_filter=["message", "warning"], with_categories=True614 )615 assert list(messages) == [616 ("message", "Hello World"),617 ("warning", flask.Markup("<em>Testing</em>")),618 ]619 return ""620621 @app.route("/test_filters_without_returning_categories/")622 def test_filters2():623 messages = flask.get_flashed_messages(category_filter=["message", "warning"])624 assert len(messages) == 2625 assert messages[0] == "Hello World"626 assert messages[1] == flask.Markup("<em>Testing</em>")627 return ""628629 # Create new test client on each test to clean flashed messages.630631 client = app.test_client()632 client.get("/")633 client.get("/test_with_categories/")634635 client = app.test_client()636 client.get("/")637 client.get("/test_filter/")638639 client = app.test_client()640 client.get("/")641 client.get("/test_filters/")642643 client = app.test_client()644 client.get("/")645 client.get("/test_filters_without_returning_categories/")646647648def test_request_processing(app, client):649 evts = []650651 @app.before_request652 def before_request():653 evts.append("before")654655 @app.after_request656 def after_request(response):657 response.data += b"|after"658 evts.append("after")659 return response660661 @app.route("/")662 def index():663 assert "before" in evts664 assert "after" not in evts665 return "request"666667 assert "after" not in evts668 rv = client.get("/").data669 assert "after" in evts670 assert rv == b"request|after"671672673def test_request_preprocessing_early_return(app, client):674 evts = []675676 @app.before_request677 def before_request1():678 evts.append(1)679680 @app.before_request681 def before_request2():682 evts.append(2)683 return "hello"684685 @app.before_request686 def before_request3():687 evts.append(3)688 return "bye"689690 @app.route("/")691 def index():692 evts.append("index")693 return "damnit"694695 rv = client.get("/").data.strip()696 assert rv == b"hello"697 assert evts == [1, 2]698699700def test_after_request_processing(app, client):701 @app.route("/")702 def index():703 @flask.after_this_request704 def foo(response):705 response.headers["X-Foo"] = "a header"706 return response707708 return "Test"709710 resp = client.get("/")711 assert resp.status_code == 200712 assert resp.headers["X-Foo"] == "a header"713714715def test_teardown_request_handler(app, client):716 called = []717718 @app.teardown_request719 def teardown_request(exc):720 called.append(True)721 return "Ignored"722723 @app.route("/")724 def root():725 return "Response"726727 rv = client.get("/")728 assert rv.status_code == 200729 assert b"Response" in rv.data730 assert len(called) == 1731732733def test_teardown_request_handler_debug_mode(app, client):734 called = []735736 @app.teardown_request737 def teardown_request(exc):738 called.append(True)739 return "Ignored"740741 @app.route("/")742 def root():743 return "Response"744745 rv = client.get("/")746 assert rv.status_code == 200747 assert b"Response" in rv.data748 assert len(called) == 1749750751def test_teardown_request_handler_error(app, client):752 called = []753 app.testing = False754755 @app.teardown_request756 def teardown_request1(exc):757 assert type(exc) == ZeroDivisionError758 called.append(True)759 # This raises a new error and blows away sys.exc_info(), so we can760 # test that all teardown_requests get passed the same original761 # exception.762 try:763 raise TypeError()764 except Exception:765 pass766767 @app.teardown_request768 def teardown_request2(exc):769 assert type(exc) == ZeroDivisionError770 called.append(True)771 # This raises a new error and blows away sys.exc_info(), so we can772 # test that all teardown_requests get passed the same original773 # exception.774 try:775 raise TypeError()776 except Exception:777 pass778779 @app.route("/")780 def fails():781 1 // 0782783 rv = client.get("/")784 assert rv.status_code == 500785 assert b"Internal Server Error" in rv.data786 assert len(called) == 2787788789def test_before_after_request_order(app, client):790 called = []791792 @app.before_request793 def before1():794 called.append(1)795796 @app.before_request797 def before2():798 called.append(2)799800 @app.after_request801 def after1(response):802 called.append(4)803 return response804805 @app.after_request806 def after2(response):807 called.append(3)808 return response809810 @app.teardown_request811 def finish1(exc):812 called.append(6)813814 @app.teardown_request815 def finish2(exc):816 called.append(5)817818 @app.route("/")819 def index():820 return "42"821822 rv = client.get("/")823 assert rv.data == b"42"824 assert called == [1, 2, 3, 4, 5, 6]825826827def test_error_handling(app, client):828 app.testing = False829830 @app.errorhandler(404)831 def not_found(e):832 return "not found", 404833834 @app.errorhandler(500)835 def internal_server_error(e):836 return "internal server error", 500837838 @app.errorhandler(Forbidden)839 def forbidden(e):840 return "forbidden", 403841842 @app.route("/")843 def index():844 flask.abort(404)845846 @app.route("/error")847 def error():848 1 // 0849850 @app.route("/forbidden")851 def error2():852 flask.abort(403)853854 rv = client.get("/")855 assert rv.status_code == 404856 assert rv.data == b"not found"857 rv = client.get("/error")858 assert rv.status_code == 500859 assert b"internal server error" == rv.data860 rv = client.get("/forbidden")861 assert rv.status_code == 403862 assert b"forbidden" == rv.data863864865def test_error_handler_unknown_code(app):866 with pytest.raises(KeyError) as exc_info:867 app.register_error_handler(999, lambda e: ("999", 999))868869 assert "Use a subclass" in exc_info.value.args[0]870871872def test_error_handling_processing(app, client):873 app.testing = False874875 @app.errorhandler(500)876 def internal_server_error(e):877 return "internal server error", 500878879 @app.route("/")880 def broken_func():881 1 // 0882883 @app.after_request884 def after_request(resp):885 resp.mimetype = "text/x-special"886 return resp887888 resp = client.get("/")889 assert resp.mimetype == "text/x-special"890 assert resp.data == b"internal server error"891892893def test_baseexception_error_handling(app, client):894 app.testing = False895896 @app.route("/")897 def broken_func():898 raise KeyboardInterrupt()899900 with pytest.raises(KeyboardInterrupt):901 client.get("/")902903 ctx = flask._request_ctx_stack.top904 assert ctx.preserved905 assert type(ctx._preserved_exc) is KeyboardInterrupt906907908def test_before_request_and_routing_errors(app, client):909 @app.before_request910 def attach_something():911 flask.g.something = "value"912913 @app.errorhandler(404)914 def return_something(error):915 return flask.g.something, 404916917 rv = client.get("/")918 assert rv.status_code == 404919 assert rv.data == b"value"920921922def test_user_error_handling(app, client):923 class MyException(Exception):924 pass925926 @app.errorhandler(MyException)927 def handle_my_exception(e):928 assert isinstance(e, MyException)929 return "42"930931 @app.route("/")932 def index():933 raise MyException()934935 assert client.get("/").data == b"42"936937938def test_http_error_subclass_handling(app, client):939 class ForbiddenSubclass(Forbidden):940 pass941942 @app.errorhandler(ForbiddenSubclass)943 def handle_forbidden_subclass(e):944 assert isinstance(e, ForbiddenSubclass)945 return "banana"946947 @app.errorhandler(403)948 def handle_403(e):949 assert not isinstance(e, ForbiddenSubclass)950 assert isinstance(e, Forbidden)951 return "apple"952953 @app.route("/1")954 def index1():955 raise ForbiddenSubclass()956957 @app.route("/2")958 def index2():959 flask.abort(403)960961 @app.route("/3")962 def index3():963 raise Forbidden()964965 assert client.get("/1").data == b"banana"966 assert client.get("/2").data == b"apple"967 assert client.get("/3").data == b"apple"968969970def test_errorhandler_precedence(app, client):971 class E1(Exception):972 pass973974 class E2(Exception):975 pass976977 class E3(E1, E2):978 pass979980 @app.errorhandler(E2)981 def handle_e2(e):982 return "E2"983984 @app.errorhandler(Exception)985 def handle_exception(e):986 return "Exception"987988 @app.route("/E1")989 def raise_e1():990 raise E1991992 @app.route("/E3")993 def raise_e3():994 raise E3995996 rv = client.get("/E1")997 assert rv.data == b"Exception"998999 rv = client.get("/E3")1000 assert rv.data == b"E2"100110021003def test_trapping_of_bad_request_key_errors(app, client):1004 @app.route("/key")1005 def fail():1006 flask.request.form["missing_key"]10071008 @app.route("/abort")1009 def allow_abort():1010 flask.abort(400)10111012 rv = client.get("/key")1013 assert rv.status_code == 4001014 assert b"missing_key" not in rv.data1015 rv = client.get("/abort")1016 assert rv.status_code == 40010171018 app.debug = True1019 with pytest.raises(KeyError) as e:1020 client.get("/key")1021 assert e.errisinstance(BadRequest)1022 assert "missing_key" in e.value.get_description()1023 rv = client.get("/abort")1024 assert rv.status_code == 40010251026 app.debug = False1027 app.config["TRAP_BAD_REQUEST_ERRORS"] = True1028 with pytest.raises(KeyError):1029 client.get("/key")1030 with pytest.raises(BadRequest):1031 client.get("/abort")103210331034def test_trapping_of_all_http_exceptions(app, client):1035 app.config["TRAP_HTTP_EXCEPTIONS"] = True10361037 @app.route("/fail")1038 def fail():1039 flask.abort(404)10401041 with pytest.raises(NotFound):1042 client.get("/fail")104310441045def test_error_handler_after_processor_error(app, client):1046 app.testing = False10471048 @app.before_request1049 def before_request():1050 if _trigger == "before":1051 1 // 010521053 @app.after_request1054 def after_request(response):1055 if _trigger == "after":1056 1 // 01057 return response10581059 @app.route("/")1060 def index():1061 return "Foo"10621063 @app.errorhandler(500)1064 def internal_server_error(e):1065 return "Hello Server Error", 50010661067 for _trigger in "before", "after":1068 rv = client.get("/")1069 assert rv.status_code == 5001070 assert rv.data == b"Hello Server Error"107110721073def test_enctype_debug_helper(app, client):1074 from flask.debughelpers import DebugFilesKeyError10751076 app.debug = True10771078 @app.route("/fail", methods=["POST"])1079 def index():1080 return flask.request.files["foo"].filename10811082 # with statement is important because we leave an exception on the1083 # stack otherwise and we want to ensure that this is not the case1084 # to not negatively affect other tests.1085 with client:1086 with pytest.raises(DebugFilesKeyError) as e:1087 client.post("/fail", data={"foo": "index.txt"})1088 assert "no file contents were transmitted" in str(e.value)1089 assert "This was submitted: 'index.txt'" in str(e.value)109010911092def test_response_types(app, client):1093 @app.route("/text")1094 def from_text():1095 return "Hällo Wörld"10961097 @app.route("/bytes")1098 def from_bytes():1099 return "Hällo Wörld".encode()11001101 @app.route("/full_tuple")1102 def from_full_tuple():1103 return (1104 "Meh",1105 400,1106 {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1107 )11081109 @app.route("/text_headers")1110 def from_text_headers():1111 return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}11121113 @app.route("/text_status")1114 def from_text_status():1115 return "Hi, status!", 40011161117 @app.route("/response_headers")1118 def from_response_headers():1119 return (1120 flask.Response("Hello world", 404, {"X-Foo": "Baz"}),1121 {"X-Foo": "Bar", "X-Bar": "Foo"},1122 )11231124 @app.route("/response_status")1125 def from_response_status():1126 return app.response_class("Hello world", 400), 50011271128 @app.route("/wsgi")1129 def from_wsgi():1130 return NotFound()11311132 @app.route("/dict")1133 def from_dict():1134 return {"foo": "bar"}, 20111351136 assert client.get("/text").data == "Hällo Wörld".encode()1137 assert client.get("/bytes").data == "Hällo Wörld".encode()11381139 rv = client.get("/full_tuple")1140 assert rv.data == b"Meh"1141 assert rv.headers["X-Foo"] == "Testing"1142 assert rv.status_code == 4001143 assert rv.mimetype == "text/plain"11441145 rv = client.get("/text_headers")1146 assert rv.data == b"Hello"1147 assert rv.headers["X-Foo"] == "Test"1148 assert rv.status_code == 2001149 assert rv.mimetype == "text/plain"11501151 rv = client.get("/text_status")1152 assert rv.data == b"Hi, status!"1153 assert rv.status_code == 4001154 assert rv.mimetype == "text/html"11551156 rv = client.get("/response_headers")1157 assert rv.data == b"Hello world"1158 assert rv.headers.getlist("X-Foo") == ["Baz", "Bar"]1159 assert rv.headers["X-Bar"] == "Foo"1160 assert rv.status_code == 40411611162 rv = client.get("/response_status")1163 assert rv.data == b"Hello world"1164 assert rv.status_code == 50011651166 rv = client.get("/wsgi")1167 assert b"Not Found" in rv.data1168 assert rv.status_code == 40411691170 rv = client.get("/dict")1171 assert rv.json == {"foo": "bar"}1172 assert rv.status_code == 201117311741175def test_response_type_errors():1176 app = flask.Flask(__name__)1177 app.testing = True11781179 @app.route("/none")1180 def from_none():1181 pass11821183 @app.route("/small_tuple")1184 def from_small_tuple():1185 return ("Hello",)11861187 @app.route("/large_tuple")1188 def from_large_tuple():1189 return "Hello", 234, {"X-Foo": "Bar"}, "???"11901191 @app.route("/bad_type")1192 def from_bad_type():1193 return True11941195 @app.route("/bad_wsgi")1196 def from_bad_wsgi():1197 return lambda: None11981199 c = app.test_client()12001201 with pytest.raises(TypeError) as e:1202 c.get("/none")1203 assert "returned None" in str(e.value)1204 assert "from_none" in str(e.value)12051206 with pytest.raises(TypeError) as e:1207 c.get("/small_tuple")1208 assert "tuple must have the form" in str(e.value)12091210 pytest.raises(TypeError, c.get, "/large_tuple")12111212 with pytest.raises(TypeError) as e:1213 c.get("/bad_type")1214 assert "it was a bool" in str(e.value)12151216 pytest.raises(TypeError, c.get, "/bad_wsgi")121712181219def test_make_response(app, req_ctx):1220 rv = flask.make_response()1221 assert rv.status_code == 2001222 assert rv.data == b""1223 assert rv.mimetype == "text/html"12241225 rv = flask.make_response("Awesome")1226 assert rv.status_code == 2001227 assert rv.data == b"Awesome"1228 assert rv.mimetype == "text/html"12291230 rv = flask.make_response("W00t", 404)1231 assert rv.status_code == 4041232 assert rv.data == b"W00t"1233 assert rv.mimetype == "text/html"123412351236def test_make_response_with_response_instance(app, req_ctx):1237 rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1238 assert rv.status_code == 4001239 assert rv.data == b'{"msg":"W00t"}\n'1240 assert rv.mimetype == "application/json"12411242 rv = flask.make_response(flask.Response(""), 400)1243 assert rv.status_code == 4001244 assert rv.data == b""1245 assert rv.mimetype == "text/html"12461247 rv = flask.make_response(1248 flask.Response("", headers={"Content-Type": "text/html"}),1249 400,1250 [("X-Foo", "bar")],1251 )1252 assert rv.status_code == 4001253 assert rv.headers["Content-Type"] == "text/html"1254 assert rv.headers["X-Foo"] == "bar"125512561257def test_jsonify_no_prettyprint(app, req_ctx):1258 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1259 compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1260 uncompressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}12611262 rv = flask.make_response(flask.jsonify(uncompressed_msg), 200)1263 assert rv.data == compressed_msg126412651266def test_jsonify_prettyprint(app, req_ctx):1267 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1268 compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1269 pretty_response = (1270 b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'1271 )12721273 rv = flask.make_response(flask.jsonify(compressed_msg), 200)1274 assert rv.data == pretty_response127512761277def test_jsonify_mimetype(app, req_ctx):1278 app.config.update({"JSONIFY_MIMETYPE": "application/vnd.api+json"})1279 msg = {"msg": {"submsg": "W00t"}}1280 rv = flask.make_response(flask.jsonify(msg), 200)1281 assert rv.mimetype == "application/vnd.api+json"128212831284@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")1285def test_json_dump_dataclass(app, req_ctx):1286 from dataclasses import make_dataclass12871288 Data = make_dataclass("Data", [("name", str)])1289 value = flask.json.dumps(Data("Flask"), app=app)1290 value = flask.json.loads(value, app=app)1291 assert value == {"name": "Flask"}129212931294def test_jsonify_args_and_kwargs_check(app, req_ctx):1295 with pytest.raises(TypeError) as e:1296 flask.jsonify("fake args", kwargs="fake")1297 assert "behavior undefined" in str(e.value)129812991300def test_url_generation(app, req_ctx):1301 @app.route("/hello/<name>", methods=["POST"])1302 def hello():1303 pass13041305 assert flask.url_for("hello", name="test x") == "/hello/test%20x"1306 assert (1307 flask.url_for("hello", name="test x", _external=True)1308 == "http://localhost/hello/test%20x"1309 )131013111312def test_build_error_handler(app):1313 # Test base case, a URL which results in a BuildError.1314 with app.test_request_context():1315 pytest.raises(BuildError, flask.url_for, "spam")13161317 # Verify the error is re-raised if not the current exception.1318 try:1319 with app.test_request_context():1320 flask.url_for("spam")1321 except BuildError as err:1322 error = err1323 try:1324 raise RuntimeError("Test case where BuildError is not current.")1325 except RuntimeError:1326 pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})13271328 # Test a custom handler.1329 def handler(error, endpoint, values):1330 # Just a test.1331 return "/test_handler/"13321333 app.url_build_error_handlers.append(handler)1334 with app.test_request_context():1335 assert flask.url_for("spam") == "/test_handler/"133613371338def test_build_error_handler_reraise(app):1339 # Test a custom handler which reraises the BuildError1340 def handler_raises_build_error(error, endpoint, values):1341 raise error13421343 app.url_build_error_handlers.append(handler_raises_build_error)13441345 with app.test_request_context():1346 pytest.raises(BuildError, flask.url_for, "not.existing")134713481349def test_url_for_passes_special_values_to_build_error_handler(app):1350 @app.url_build_error_handlers.append1351 def handler(error, endpoint, values):1352 assert values == {1353 "_external": False,1354 "_anchor": None,1355 "_method": None,1356 "_scheme": None,1357 }1358 return "handled"13591360 with app.test_request_context():1361 flask.url_for("/")136213631364def test_static_files(app, client):1365 rv = client.get("/static/index.html")1366 assert rv.status_code == 2001367 assert rv.data.strip() == b"<h1>Hello World!</h1>"1368 with app.test_request_context():1369 assert flask.url_for("static", filename="index.html") == "/static/index.html"1370 rv.close()137113721373def test_static_url_path():1374 app = flask.Flask(__name__, static_url_path="/foo")1375 app.testing = True1376 rv = app.test_client().get("/foo/index.html")1377 assert rv.status_code == 2001378 rv.close()13791380 with app.test_request_context():1381 assert flask.url_for("static", filename="index.html") == "/foo/index.html"138213831384def test_static_url_path_with_ending_slash():1385 app = flask.Flask(__name__, static_url_path="/foo/")1386 app.testing = True1387 rv = app.test_client().get("/foo/index.html")1388 assert rv.status_code == 2001389 rv.close()13901391 with app.test_request_context():1392 assert flask.url_for("static", filename="index.html") == "/foo/index.html"139313941395def test_static_url_empty_path(app):1396 app = flask.Flask(__name__, static_folder="", static_url_path="")1397 rv = app.test_client().open("/static/index.html", method="GET")1398 assert rv.status_code == 2001399 rv.close()140014011402def test_static_url_empty_path_default(app):1403 app = flask.Flask(__name__, static_folder="")1404 rv = app.test_client().open("/static/index.html", method="GET")1405 assert rv.status_code == 2001406 rv.close()140714081409def test_static_folder_with_ending_slash():1410 app = flask.Flask(__name__, static_folder="static/")14111412 @app.route("/<path:path>")1413 def catch_all(path):1414 return path14151416 rv = app.test_client().get("/catch/all")1417 assert rv.data == b"catch/all"141814191420def test_static_route_with_host_matching():1421 app = flask.Flask(__name__, host_matching=True, static_host="example.com")1422 c = app.test_client()1423 rv = c.get("http://example.com/static/index.html")1424 assert rv.status_code == 2001425 rv.close()1426 with app.test_request_context():1427 rv = flask.url_for("static", filename="index.html", _external=True)1428 assert rv == "http://example.com/static/index.html"1429 # Providing static_host without host_matching=True should error.1430 with pytest.raises(Exception):1431 flask.Flask(__name__, static_host="example.com")1432 # Providing host_matching=True with static_folder1433 # but without static_host should error.1434 with pytest.raises(Exception):1435 flask.Flask(__name__, host_matching=True)1436 # Providing host_matching=True without static_host1437 # but with static_folder=None should not error.1438 flask.Flask(__name__, host_matching=True, static_folder=None)143914401441def test_request_locals():1442 assert repr(flask.g) == "<LocalProxy unbound>"1443 assert not flask.g144414451446def test_server_name_subdomain():1447 app = flask.Flask(__name__, subdomain_matching=True)1448 client = app.test_client()14491450 @app.route("/")1451 def index():1452 return "default"14531454 @app.route("/", subdomain="foo")1455 def subdomain():1456 return "subdomain"14571458 app.config["SERVER_NAME"] = "dev.local:5000"1459 rv = client.get("/")1460 assert rv.data == b"default"14611462 rv = client.get("/", "http://dev.local:5000")1463 assert rv.data == b"default"14641465 rv = client.get("/", "https://dev.local:5000")1466 assert rv.data == b"default"14671468 app.config["SERVER_NAME"] = "dev.local:443"1469 rv = client.get("/", "https://dev.local")14701471 # Werkzeug 1.0 fixes matching https scheme with 443 port1472 if rv.status_code != 404:1473 assert rv.data == b"default"14741475 app.config["SERVER_NAME"] = "dev.local"1476 rv = client.get("/", "https://dev.local")1477 assert rv.data == b"default"14781479 # suppress Werkzeug 1.0 warning about name mismatch1480 with pytest.warns(None):1481 rv = client.get("/", "http://foo.localhost")1482 assert rv.status_code == 40414831484 rv = client.get("/", "http://foo.dev.local")1485 assert rv.data == b"subdomain"148614871488def test_exception_propagation(app, client):1489 def apprunner(config_key):1490 @app.route("/")1491 def index():1492 1 // 014931494 if config_key is not None:1495 app.config[config_key] = True1496 with pytest.raises(Exception):1497 client.get("/")1498 else:1499 assert client.get("/").status_code == 50015001501 # we have to run this test in an isolated thread because if the1502 # debug flag is set to true and an exception happens the context is1503 # not torn down. This causes other tests that run after this fail1504 # when they expect no exception on the stack.1505 for config_key in "TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None:1506 t = Thread(target=apprunner, args=(config_key,))1507 t.start()1508 t.join()150915101511@pytest.mark.parametrize("debug", [True, False])1512@pytest.mark.parametrize("use_debugger", [True, False])1513@pytest.mark.parametrize("use_reloader", [True, False])1514@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1515def test_werkzeug_passthrough_errors(1516 monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1517):1518 rv = {}15191520 # Mocks werkzeug.serving.run_simple method1521 def run_simple_mock(*args, **kwargs):1522 rv["passthrough_errors"] = kwargs.get("passthrough_errors")15231524 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1525 app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1526 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)152715281529def test_max_content_length(app, client):1530 app.config["MAX_CONTENT_LENGTH"] = 6415311532 @app.before_request1533 def always_first():1534 flask.request.form["myfile"]1535 AssertionError()15361537 @app.route("/accept", methods=["POST"])1538 def accept_file():1539 flask.request.form["myfile"]1540 AssertionError()15411542 @app.errorhandler(413)1543 def catcher(error):1544 return "42"15451546 rv = client.post("/accept", data={"myfile": "foo" * 100})1547 assert rv.data == b"42"154815491550def test_url_processors(app, client):1551 @app.url_defaults1552 def add_language_code(endpoint, values):1553 if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1554 endpoint, "lang_code"1555 ):1556 values.setdefault("lang_code", flask.g.lang_code)15571558 @app.url_value_preprocessor1559 def pull_lang_code(endpoint, values):1560 flask.g.lang_code = values.pop("lang_code", None)15611562 @app.route("/<lang_code>/")1563 def index():1564 return flask.url_for("about")15651566 @app.route("/<lang_code>/about")1567 def about():1568 return flask.url_for("something_else")15691570 @app.route("/foo")1571 def something_else():1572 return flask.url_for("about", lang_code="en")15731574 assert client.get("/de/").data == b"/de/about"1575 assert client.get("/de/about").data == b"/foo"1576 assert client.get("/foo").data == b"/en/about"157715781579def test_inject_blueprint_url_defaults(app):1580 bp = flask.Blueprint("foo.bar.baz", __name__, template_folder="template")15811582 @bp.url_defaults1583 def bp_defaults(endpoint, values):1584 values["page"] = "login"15851586 @bp.route("/<page>")1587 def view(page):1588 pass15891590 app.register_blueprint(bp)15911592 values = dict()1593 app.inject_url_defaults("foo.bar.baz.view", values)1594 expected = dict(page="login")1595 assert values == expected15961597 with app.test_request_context("/somepage"):1598 url = flask.url_for("foo.bar.baz.view")1599 expected = "/login"1600 assert url == expected160116021603def test_nonascii_pathinfo(app, client):1604 @app.route("/киртест")1605 def index():1606 return "Hello World!"16071608 rv = client.get("/киртест")1609 assert rv.data == b"Hello World!"161016111612def test_debug_mode_complains_after_first_request(app, client):1613 app.debug = True16141615 @app.route("/")1616 def index():1617 return "Awesome"16181619 assert not app.got_first_request1620 assert client.get("/").data == b"Awesome"1621 with pytest.raises(AssertionError) as e:16221623 @app.route("/foo")1624 def broken():1625 return "Meh"16261627 assert "A setup function was called" in str(e.value)16281629 app.debug = False16301631 @app.route("/foo")1632 def working():1633 return "Meh"16341635 assert client.get("/foo").data == b"Meh"1636 assert app.got_first_request163716381639def test_before_first_request_functions(app, client):1640 got = []16411642 @app.before_first_request1643 def foo():1644 got.append(42)16451646 client.get("/")1647 assert got == [42]1648 client.get("/")1649 assert got == [42]1650 assert app.got_first_request165116521653def test_before_first_request_functions_concurrent(app, client):1654 got = []16551656 @app.before_first_request1657 def foo():1658 time.sleep(0.2)1659 got.append(42)16601661 def get_and_assert():1662 client.get("/")1663 assert got == [42]16641665 t = Thread(target=get_and_assert)1666 t.start()1667 get_and_assert()1668 t.join()1669 assert app.got_first_request167016711672def test_routing_redirect_debugging(app, client):1673 app.debug = True16741675 @app.route("/foo/", methods=["GET", "POST"])1676 def foo():1677 return "success"16781679 with client:1680 with pytest.raises(AssertionError) as e:1681 client.post("/foo", data={})1682 assert "http://localhost/foo/" in str(e.value)1683 assert "Make sure to directly send your POST-request to this URL" in str(1684 e.value1685 )16861687 rv = client.get("/foo", data={}, follow_redirects=True)1688 assert rv.data == b"success"16891690 app.debug = False1691 with client:1692 rv = client.post("/foo", data={}, follow_redirects=True)1693 assert rv.data == b"success"169416951696def test_route_decorator_custom_endpoint(app, client):1697 app.debug = True16981699 @app.route("/foo/")1700 def foo():1701 return flask.request.endpoint17021703 @app.route("/bar/", endpoint="bar")1704 def for_bar():1705 return flask.request.endpoint17061707 @app.route("/bar/123", endpoint="123")1708 def for_bar_foo():1709 return flask.request.endpoint17101711 with app.test_request_context():1712 assert flask.url_for("foo") == "/foo/"1713 assert flask.url_for("bar") == "/bar/"1714 assert flask.url_for("123") == "/bar/123"17151716 assert client.get("/foo/").data == b"foo"1717 assert client.get("/bar/").data == b"bar"1718 assert client.get("/bar/123").data == b"123"171917201721def test_preserve_only_once(app, client):1722 app.debug = True17231724 @app.route("/fail")1725 def fail_func():1726 1 // 017271728 for _x in range(3):1729 with pytest.raises(ZeroDivisionError):1730 client.get("/fail")17311732 assert flask._request_ctx_stack.top is not None1733 assert flask._app_ctx_stack.top is not None1734 # implicit appctx disappears too1735 flask._request_ctx_stack.top.pop()1736 assert flask._request_ctx_stack.top is None1737 assert flask._app_ctx_stack.top is None173817391740def test_preserve_remembers_exception(app, client):1741 app.debug = True1742 errors = []17431744 @app.route("/fail")1745 def fail_func():1746 1 // 017471748 @app.route("/success")1749 def success_func():1750 return "Okay"17511752 @app.teardown_request1753 def teardown_handler(exc):1754 errors.append(exc)17551756 # After this failure we did not yet call the teardown handler1757 with pytest.raises(ZeroDivisionError):1758 client.get("/fail")1759 assert errors == []17601761 # But this request triggers it, and it's an error1762 client.get("/success")1763 assert len(errors) == 21764 assert isinstance(errors[0], ZeroDivisionError)17651766 # At this point another request does nothing.1767 client.get("/success")1768 assert len(errors) == 31769 assert errors[1] is None177017711772def test_get_method_on_g(app_ctx):1773 assert flask.g.get("x") is None1774 assert flask.g.get("x", 11) == 111775 flask.g.x = 421776 assert flask.g.get("x") == 421777 assert flask.g.x == 42177817791780def test_g_iteration_protocol(app_ctx):1781 flask.g.foo = 231782 flask.g.bar = 421783 assert "foo" in flask.g1784 assert "foos" not in flask.g1785 assert sorted(flask.g) == ["bar", "foo"]178617871788def test_subdomain_basic_support():1789 app = flask.Flask(__name__, subdomain_matching=True)1790 app.config["SERVER_NAME"] = "localhost.localdomain"1791 client = app.test_client()17921793 @app.route("/")1794 def normal_index():1795 return "normal index"17961797 @app.route("/", subdomain="test")1798 def test_index():1799 return "test index"18001801 rv = client.get("/", "http://localhost.localdomain/")1802 assert rv.data == b"normal index"18031804 rv = client.get("/", "http://test.localhost.localdomain/")1805 assert rv.data == b"test index"180618071808def test_subdomain_matching():1809 app = flask.Flask(__name__, subdomain_matching=True)1810 client = app.test_client()1811 app.config["SERVER_NAME"] = "localhost.localdomain"18121813 @app.route("/", subdomain="<user>")1814 def index(user):1815 return f"index for {user}"18161817 rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1818 assert rv.data == b"index for mitsuhiko"181918201821def test_subdomain_matching_with_ports():1822 app = flask.Flask(__name__, subdomain_matching=True)1823 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1824 client = app.test_client()18251826 @app.route("/", subdomain="<user>")1827 def index(user):1828 return f"index for {user}"18291830 rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1831 assert rv.data == b"index for mitsuhiko"183218331834@pytest.mark.parametrize("matching", (False, True))1835def test_subdomain_matching_other_name(matching):1836 app = flask.Flask(__name__, subdomain_matching=matching)1837 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1838 client = app.test_client()18391840 @app.route("/")1841 def index():1842 return "", 20418431844 # suppress Werkzeug 0.15 warning about name mismatch1845 with pytest.warns(None):1846 # ip address can't match name1847 rv = client.get("/", "http://127.0.0.1:3000/")1848 assert rv.status_code == 404 if matching else 20418491850 # allow all subdomains if matching is disabled1851 rv = client.get("/", "http://www.localhost.localdomain:3000/")1852 assert rv.status_code == 404 if matching else 204185318541855def test_multi_route_rules(app, client):1856 @app.route("/")1857 @app.route("/<test>/")1858 def index(test="a"):1859 return test18601861 rv = client.open("/")1862 assert rv.data == b"a"1863 rv = client.open("/b/")1864 assert rv.data == b"b"186518661867def test_multi_route_class_views(app, client):1868 class View:1869 def __init__(self, app):1870 app.add_url_rule("/", "index", self.index)1871 app.add_url_rule("/<test>/", "index", self.index)18721873 def index(self, test="a"):1874 return test18751876 _ = View(app)1877 rv = client.open("/")1878 assert rv.data == b"a"1879 rv = client.open("/b/")1880 assert rv.data == b"b"188118821883def test_run_defaults(monkeypatch, app):1884 rv = {}18851886 # Mocks werkzeug.serving.run_simple method1887 def run_simple_mock(*args, **kwargs):1888 rv["result"] = "running..."18891890 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1891 app.run()1892 assert rv["result"] == "running..."189318941895def test_run_server_port(monkeypatch, app):1896 rv = {}18971898 # Mocks werkzeug.serving.run_simple method1899 def run_simple_mock(hostname, port, application, *args, **kwargs):1900 rv["result"] = f"running on {hostname}:{port} ..."19011902 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1903 hostname, port = "localhost", 80001904 app.run(hostname, port, debug=True)1905 assert rv["result"] == f"running on {hostname}:{port} ..."190619071908@pytest.mark.parametrize(1909 "host,port,server_name,expect_host,expect_port",1910 (1911 (None, None, "pocoo.org:8080", "pocoo.org", 8080),1912 ("localhost", None, "pocoo.org:8080", "localhost", 8080),1913 (None, 80, "pocoo.org:8080", "pocoo.org", 80),1914 ("localhost", 80, "pocoo.org:8080", "localhost", 80),1915 ("localhost", 0, "localhost:8080", "localhost", 0),1916 (None, None, "localhost:8080", "localhost", 8080),1917 (None, None, "localhost:0", "localhost", 0),1918 ),1919)1920def test_run_from_config(1921 monkeypatch, host, port, server_name, expect_host, expect_port, app1922):1923 def run_simple_mock(hostname, port, *args, **kwargs):1924 assert hostname == expect_host1925 assert port == expect_port19261927 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1928 app.config["SERVER_NAME"] = server_name1929 app.run(host, port)193019311932def test_max_cookie_size(app, client, recwarn):1933 app.config["MAX_COOKIE_SIZE"] = 10019341935 # outside app context, default to Werkzeug static value,1936 # which is also the default config1937 response = flask.Response()1938 default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1939 assert response.max_cookie_size == default19401941 # inside app context, use app config1942 with app.app_context():1943 assert flask.Response().max_cookie_size == 10019441945 @app.route("/")1946 def index():1947 r = flask.Response("", status=204)1948 r.set_cookie("foo", "bar" * 100)1949 return r19501951 client.get("/")1952 assert len(recwarn) == 11953 w = recwarn.pop()1954 assert "cookie is too large" in str(w.message)19551956 app.config["MAX_COOKIE_SIZE"] = 019571958 client.get("/")1959 assert len(recwarn) == 0