test_basic.py
This file
Path
tests/test_basic.py
2,026 lines · 54.4 KiB · Python
Last changed by
Merge pull request #4335 from pallets/drop-python-3.6David Lordbefore adoptionea93a52
History of this fileTake it
1import gc2import re3import time4import uuid5import weakref6from datetime import datetime7from platform import python_implementation8from threading import Thread910import pytest11import werkzeug.serving12from werkzeug.exceptions import BadRequest13from werkzeug.exceptions import Forbidden14from werkzeug.exceptions import NotFound15from werkzeug.http import parse_date16from werkzeug.routing import BuildError1718import flask192021require_cpython_gc = pytest.mark.skipif(22 python_implementation() != "CPython",23 reason="Requires CPython GC behavior",24)252627def test_options_work(app, client):28 @app.route("/", methods=["GET", "POST"])29 def index():30 return "Hello World"3132 rv = client.open("/", method="OPTIONS")33 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]34 assert rv.data == b""353637def test_options_on_multiple_rules(app, client):38 @app.route("/", methods=["GET", "POST"])39 def index():40 return "Hello World"4142 @app.route("/", methods=["PUT"])43 def index_put():44 return "Aha!"4546 rv = client.open("/", method="OPTIONS")47 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST", "PUT"]484950@pytest.mark.parametrize("method", ["get", "post", "put", "delete", "patch"])51def test_method_route(app, client, method):52 method_route = getattr(app, method)53 client_method = getattr(client, method)5455 @method_route("/")56 def hello():57 return "Hello"5859 assert client_method("/").data == b"Hello"606162def test_method_route_no_methods(app):63 with pytest.raises(TypeError):64 app.get("/", methods=["GET", "POST"])656667def test_provide_automatic_options_attr():68 app = flask.Flask(__name__)6970 def index():71 return "Hello World!"7273 index.provide_automatic_options = False74 app.route("/")(index)75 rv = app.test_client().open("/", method="OPTIONS")76 assert rv.status_code == 4057778 app = flask.Flask(__name__)7980 def index2():81 return "Hello World!"8283 index2.provide_automatic_options = True84 app.route("/", methods=["OPTIONS"])(index2)85 rv = app.test_client().open("/", method="OPTIONS")86 assert sorted(rv.allow) == ["OPTIONS"]878889def test_provide_automatic_options_kwarg(app, client):90 def index():91 return flask.request.method9293 def more():94 return flask.request.method9596 app.add_url_rule("/", view_func=index, provide_automatic_options=False)97 app.add_url_rule(98 "/more",99 view_func=more,100 methods=["GET", "POST"],101 provide_automatic_options=False,102 )103 assert client.get("/").data == b"GET"104105 rv = client.post("/")106 assert rv.status_code == 405107 assert sorted(rv.allow) == ["GET", "HEAD"]108109 rv = client.open("/", method="OPTIONS")110 assert rv.status_code == 405111112 rv = client.head("/")113 assert rv.status_code == 200114 assert not rv.data # head truncates115 assert client.post("/more").data == b"POST"116 assert client.get("/more").data == b"GET"117118 rv = client.delete("/more")119 assert rv.status_code == 405120 assert sorted(rv.allow) == ["GET", "HEAD", "POST"]121122 rv = client.open("/more", method="OPTIONS")123 assert rv.status_code == 405124125126def test_request_dispatching(app, client):127 @app.route("/")128 def index():129 return flask.request.method130131 @app.route("/more", methods=["GET", "POST"])132 def more():133 return flask.request.method134135 assert client.get("/").data == b"GET"136 rv = client.post("/")137 assert rv.status_code == 405138 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]139 rv = client.head("/")140 assert rv.status_code == 200141 assert not rv.data # head truncates142 assert client.post("/more").data == b"POST"143 assert client.get("/more").data == b"GET"144 rv = client.delete("/more")145 assert rv.status_code == 405146 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]147148149def test_disallow_string_for_allowed_methods(app):150 with pytest.raises(TypeError):151152 @app.route("/", methods="GET POST")153 def index():154 return "Hey"155156157def test_url_mapping(app, client):158 random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"159160 def index():161 return flask.request.method162163 def more():164 return flask.request.method165166 def options():167 return random_uuid4168169 app.add_url_rule("/", "index", index)170 app.add_url_rule("/more", "more", more, methods=["GET", "POST"])171172 # Issue 1288: Test that automatic options are not added173 # when non-uppercase 'options' in methods174 app.add_url_rule("/options", "options", options, methods=["options"])175176 assert client.get("/").data == b"GET"177 rv = client.post("/")178 assert rv.status_code == 405179 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]180 rv = client.head("/")181 assert rv.status_code == 200182 assert not rv.data # head truncates183 assert client.post("/more").data == b"POST"184 assert client.get("/more").data == b"GET"185 rv = client.delete("/more")186 assert rv.status_code == 405187 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]188 rv = client.open("/options", method="OPTIONS")189 assert rv.status_code == 200190 assert random_uuid4 in rv.data.decode("utf-8")191192193def test_werkzeug_routing(app, client):194 from werkzeug.routing import Submount, Rule195196 app.url_map.add(197 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])198 )199200 def bar():201 return "bar"202203 def index():204 return "index"205206 app.view_functions["bar"] = bar207 app.view_functions["index"] = index208209 assert client.get("/foo/").data == b"index"210 assert client.get("/foo/bar").data == b"bar"211212213def test_endpoint_decorator(app, client):214 from werkzeug.routing import Submount, Rule215216 app.url_map.add(217 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])218 )219220 @app.endpoint("bar")221 def bar():222 return "bar"223224 @app.endpoint("index")225 def index():226 return "index"227228 assert client.get("/foo/").data == b"index"229 assert client.get("/foo/bar").data == b"bar"230231232def test_session(app, client):233 @app.route("/set", methods=["POST"])234 def set():235 assert not flask.session.accessed236 assert not flask.session.modified237 flask.session["value"] = flask.request.form["value"]238 assert flask.session.accessed239 assert flask.session.modified240 return "value set"241242 @app.route("/get")243 def get():244 assert not flask.session.accessed245 assert not flask.session.modified246 v = flask.session.get("value", "None")247 assert flask.session.accessed248 assert not flask.session.modified249 return v250251 assert client.post("/set", data={"value": "42"}).data == b"value set"252 assert client.get("/get").data == b"42"253254255def test_session_using_server_name(app, client):256 app.config.update(SERVER_NAME="example.com")257258 @app.route("/")259 def index():260 flask.session["testing"] = 42261 return "Hello World"262263 rv = client.get("/", "http://example.com/")264 assert "domain=.example.com" in rv.headers["set-cookie"].lower()265 assert "httponly" in rv.headers["set-cookie"].lower()266267268def test_session_using_server_name_and_port(app, client):269 app.config.update(SERVER_NAME="example.com:8080")270271 @app.route("/")272 def index():273 flask.session["testing"] = 42274 return "Hello World"275276 rv = client.get("/", "http://example.com:8080/")277 assert "domain=.example.com" in rv.headers["set-cookie"].lower()278 assert "httponly" in rv.headers["set-cookie"].lower()279280281def test_session_using_server_name_port_and_path(app, client):282 app.config.update(SERVER_NAME="example.com:8080", APPLICATION_ROOT="/foo")283284 @app.route("/")285 def index():286 flask.session["testing"] = 42287 return "Hello World"288289 rv = client.get("/", "http://example.com:8080/foo")290 assert "domain=example.com" in rv.headers["set-cookie"].lower()291 assert "path=/foo" in rv.headers["set-cookie"].lower()292 assert "httponly" in rv.headers["set-cookie"].lower()293294295def test_session_using_application_root(app, client):296 class PrefixPathMiddleware:297 def __init__(self, app, prefix):298 self.app = app299 self.prefix = prefix300301 def __call__(self, environ, start_response):302 environ["SCRIPT_NAME"] = self.prefix303 return self.app(environ, start_response)304305 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, "/bar")306 app.config.update(APPLICATION_ROOT="/bar")307308 @app.route("/")309 def index():310 flask.session["testing"] = 42311 return "Hello World"312313 rv = client.get("/", "http://example.com:8080/")314 assert "path=/bar" in rv.headers["set-cookie"].lower()315316317def test_session_using_session_settings(app, client):318 app.config.update(319 SERVER_NAME="www.example.com:8080",320 APPLICATION_ROOT="/test",321 SESSION_COOKIE_DOMAIN=".example.com",322 SESSION_COOKIE_HTTPONLY=False,323 SESSION_COOKIE_SECURE=True,324 SESSION_COOKIE_SAMESITE="Lax",325 SESSION_COOKIE_PATH="/",326 )327328 @app.route("/")329 def index():330 flask.session["testing"] = 42331 return "Hello World"332333 rv = client.get("/", "http://www.example.com:8080/test/")334 cookie = rv.headers["set-cookie"].lower()335 assert "domain=.example.com" in cookie336 assert "path=/" in cookie337 assert "secure" in cookie338 assert "httponly" not in cookie339 assert "samesite" in cookie340341 @app.route("/clear")342 def clear():343 flask.session.pop("testing", None)344 return "Goodbye World"345346 rv = client.get("/clear", "http://www.example.com:8080/test/")347 cookie = rv.headers["set-cookie"].lower()348 assert "session=;" in cookie349 assert "domain=.example.com" in cookie350 assert "path=/" in cookie351 assert "secure" in cookie352 assert "samesite" in cookie353354355def test_session_using_samesite_attribute(app, client):356 @app.route("/")357 def index():358 flask.session["testing"] = 42359 return "Hello World"360361 app.config.update(SESSION_COOKIE_SAMESITE="invalid")362363 with pytest.raises(ValueError):364 client.get("/")365366 app.config.update(SESSION_COOKIE_SAMESITE=None)367 rv = client.get("/")368 cookie = rv.headers["set-cookie"].lower()369 assert "samesite" not in cookie370371 app.config.update(SESSION_COOKIE_SAMESITE="Strict")372 rv = client.get("/")373 cookie = rv.headers["set-cookie"].lower()374 assert "samesite=strict" in cookie375376 app.config.update(SESSION_COOKIE_SAMESITE="Lax")377 rv = client.get("/")378 cookie = rv.headers["set-cookie"].lower()379 assert "samesite=lax" in cookie380381382def test_session_localhost_warning(recwarn, app, client):383 app.config.update(SERVER_NAME="localhost:5000")384385 @app.route("/")386 def index():387 flask.session["testing"] = 42388 return "testing"389390 rv = client.get("/", "http://localhost:5000/")391 assert "domain" not in rv.headers["set-cookie"].lower()392 w = recwarn.pop(UserWarning)393 assert "'localhost' is not a valid cookie domain" in str(w.message)394395396def test_session_ip_warning(recwarn, app, client):397 app.config.update(SERVER_NAME="127.0.0.1:5000")398399 @app.route("/")400 def index():401 flask.session["testing"] = 42402 return "testing"403404 rv = client.get("/", "http://127.0.0.1:5000/")405 assert "domain=127.0.0.1" in rv.headers["set-cookie"].lower()406 w = recwarn.pop(UserWarning)407 assert "cookie domain is an IP" in str(w.message)408409410def test_missing_session(app):411 app.secret_key = None412413 def expect_exception(f, *args, **kwargs):414 e = pytest.raises(RuntimeError, f, *args, **kwargs)415 assert e.value.args and "session is unavailable" in e.value.args[0]416417 with app.test_request_context():418 assert flask.session.get("missing_key") is None419 expect_exception(flask.session.__setitem__, "foo", 42)420 expect_exception(flask.session.pop, "foo")421422423def test_session_expiration(app, client):424 permanent = True425426 @app.route("/")427 def index():428 flask.session["test"] = 42429 flask.session.permanent = permanent430 return ""431432 @app.route("/test")433 def test():434 return str(flask.session.permanent)435436 rv = client.get("/")437 assert "set-cookie" in rv.headers438 match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])439 expires = parse_date(match.group())440 expected = datetime.utcnow() + app.permanent_session_lifetime441 assert expires.year == expected.year442 assert expires.month == expected.month443 assert expires.day == expected.day444445 rv = client.get("/test")446 assert rv.data == b"True"447448 permanent = False449 rv = client.get("/")450 assert "set-cookie" in rv.headers451 match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])452 assert match is None453454455def test_session_stored_last(app, client):456 @app.after_request457 def modify_session(response):458 flask.session["foo"] = 42459 return response460461 @app.route("/")462 def dump_session_contents():463 return repr(flask.session.get("foo"))464465 assert client.get("/").data == b"None"466 assert client.get("/").data == b"42"467468469def test_session_special_types(app, client):470 now = datetime.utcnow().replace(microsecond=0)471 the_uuid = uuid.uuid4()472473 @app.route("/")474 def dump_session_contents():475 flask.session["t"] = (1, 2, 3)476 flask.session["b"] = b"\xff"477 flask.session["m"] = flask.Markup("<html>")478 flask.session["u"] = the_uuid479 flask.session["d"] = now480 flask.session["t_tag"] = {" t": "not-a-tuple"}481 flask.session["di_t_tag"] = {" t__": "not-a-tuple"}482 flask.session["di_tag"] = {" di": "not-a-dict"}483 return "", 204484485 with client:486 client.get("/")487 s = flask.session488 assert s["t"] == (1, 2, 3)489 assert type(s["b"]) == bytes490 assert s["b"] == b"\xff"491 assert type(s["m"]) == flask.Markup492 assert s["m"] == flask.Markup("<html>")493 assert s["u"] == the_uuid494 assert s["d"] == now495 assert s["t_tag"] == {" t": "not-a-tuple"}496 assert s["di_t_tag"] == {" t__": "not-a-tuple"}497 assert s["di_tag"] == {" di": "not-a-dict"}498499500def test_session_cookie_setting(app):501 is_permanent = True502503 @app.route("/bump")504 def bump():505 rv = flask.session["foo"] = flask.session.get("foo", 0) + 1506 flask.session.permanent = is_permanent507 return str(rv)508509 @app.route("/read")510 def read():511 return str(flask.session.get("foo", 0))512513 def run_test(expect_header):514 with app.test_client() as c:515 assert c.get("/bump").data == b"1"516 assert c.get("/bump").data == b"2"517 assert c.get("/bump").data == b"3"518519 rv = c.get("/read")520 set_cookie = rv.headers.get("set-cookie")521 assert (set_cookie is not None) == expect_header522 assert rv.data == b"3"523524 is_permanent = True525 app.config["SESSION_REFRESH_EACH_REQUEST"] = True526 run_test(expect_header=True)527528 is_permanent = True529 app.config["SESSION_REFRESH_EACH_REQUEST"] = False530 run_test(expect_header=False)531532 is_permanent = False533 app.config["SESSION_REFRESH_EACH_REQUEST"] = True534 run_test(expect_header=False)535536 is_permanent = False537 app.config["SESSION_REFRESH_EACH_REQUEST"] = False538 run_test(expect_header=False)539540541def test_session_vary_cookie(app, client):542 @app.route("/set")543 def set_session():544 flask.session["test"] = "test"545 return ""546547 @app.route("/get")548 def get():549 return flask.session.get("test")550551 @app.route("/getitem")552 def getitem():553 return flask.session["test"]554555 @app.route("/setdefault")556 def setdefault():557 return flask.session.setdefault("test", "default")558559 @app.route("/vary-cookie-header-set")560 def vary_cookie_header_set():561 response = flask.Response()562 response.vary.add("Cookie")563 flask.session["test"] = "test"564 return response565566 @app.route("/vary-header-set")567 def vary_header_set():568 response = flask.Response()569 response.vary.update(("Accept-Encoding", "Accept-Language"))570 flask.session["test"] = "test"571 return response572573 @app.route("/no-vary-header")574 def no_vary_header():575 return ""576577 def expect(path, header_value="Cookie"):578 rv = client.get(path)579580 if header_value:581 # The 'Vary' key should exist in the headers only once.582 assert len(rv.headers.get_all("Vary")) == 1583 assert rv.headers["Vary"] == header_value584 else:585 assert "Vary" not in rv.headers586587 expect("/set")588 expect("/get")589 expect("/getitem")590 expect("/setdefault")591 expect("/vary-cookie-header-set")592 expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")593 expect("/no-vary-header", None)594595596def test_flashes(app, req_ctx):597 assert not flask.session.modified598 flask.flash("Zap")599 flask.session.modified = False600 flask.flash("Zip")601 assert flask.session.modified602 assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]603604605def test_extended_flashing(app):606 # Be sure app.testing=True below, else tests can fail silently.607 #608 # Specifically, if app.testing is not set to True, the AssertionErrors609 # in the view functions will cause a 500 response to the test client610 # instead of propagating exceptions.611612 @app.route("/")613 def index():614 flask.flash("Hello World")615 flask.flash("Hello World", "error")616 flask.flash(flask.Markup("<em>Testing</em>"), "warning")617 return ""618619 @app.route("/test/")620 def test():621 messages = flask.get_flashed_messages()622 assert list(messages) == [623 "Hello World",624 "Hello World",625 flask.Markup("<em>Testing</em>"),626 ]627 return ""628629 @app.route("/test_with_categories/")630 def test_with_categories():631 messages = flask.get_flashed_messages(with_categories=True)632 assert len(messages) == 3633 assert list(messages) == [634 ("message", "Hello World"),635 ("error", "Hello World"),636 ("warning", flask.Markup("<em>Testing</em>")),637 ]638 return ""639640 @app.route("/test_filter/")641 def test_filter():642 messages = flask.get_flashed_messages(643 category_filter=["message"], with_categories=True644 )645 assert list(messages) == [("message", "Hello World")]646 return ""647648 @app.route("/test_filters/")649 def test_filters():650 messages = flask.get_flashed_messages(651 category_filter=["message", "warning"], with_categories=True652 )653 assert list(messages) == [654 ("message", "Hello World"),655 ("warning", flask.Markup("<em>Testing</em>")),656 ]657 return ""658659 @app.route("/test_filters_without_returning_categories/")660 def test_filters2():661 messages = flask.get_flashed_messages(category_filter=["message", "warning"])662 assert len(messages) == 2663 assert messages[0] == "Hello World"664 assert messages[1] == flask.Markup("<em>Testing</em>")665 return ""666667 # Create new test client on each test to clean flashed messages.668669 client = app.test_client()670 client.get("/")671 client.get("/test_with_categories/")672673 client = app.test_client()674 client.get("/")675 client.get("/test_filter/")676677 client = app.test_client()678 client.get("/")679 client.get("/test_filters/")680681 client = app.test_client()682 client.get("/")683 client.get("/test_filters_without_returning_categories/")684685686def test_request_processing(app, client):687 evts = []688689 @app.before_request690 def before_request():691 evts.append("before")692693 @app.after_request694 def after_request(response):695 response.data += b"|after"696 evts.append("after")697 return response698699 @app.route("/")700 def index():701 assert "before" in evts702 assert "after" not in evts703 return "request"704705 assert "after" not in evts706 rv = client.get("/").data707 assert "after" in evts708 assert rv == b"request|after"709710711def test_request_preprocessing_early_return(app, client):712 evts = []713714 @app.before_request715 def before_request1():716 evts.append(1)717718 @app.before_request719 def before_request2():720 evts.append(2)721 return "hello"722723 @app.before_request724 def before_request3():725 evts.append(3)726 return "bye"727728 @app.route("/")729 def index():730 evts.append("index")731 return "damnit"732733 rv = client.get("/").data.strip()734 assert rv == b"hello"735 assert evts == [1, 2]736737738def test_after_request_processing(app, client):739 @app.route("/")740 def index():741 @flask.after_this_request742 def foo(response):743 response.headers["X-Foo"] = "a header"744 return response745746 return "Test"747748 resp = client.get("/")749 assert resp.status_code == 200750 assert resp.headers["X-Foo"] == "a header"751752753def test_teardown_request_handler(app, client):754 called = []755756 @app.teardown_request757 def teardown_request(exc):758 called.append(True)759 return "Ignored"760761 @app.route("/")762 def root():763 return "Response"764765 rv = client.get("/")766 assert rv.status_code == 200767 assert b"Response" in rv.data768 assert len(called) == 1769770771def test_teardown_request_handler_debug_mode(app, client):772 called = []773774 @app.teardown_request775 def teardown_request(exc):776 called.append(True)777 return "Ignored"778779 @app.route("/")780 def root():781 return "Response"782783 rv = client.get("/")784 assert rv.status_code == 200785 assert b"Response" in rv.data786 assert len(called) == 1787788789def test_teardown_request_handler_error(app, client):790 called = []791 app.testing = False792793 @app.teardown_request794 def teardown_request1(exc):795 assert type(exc) == ZeroDivisionError796 called.append(True)797 # This raises a new error and blows away sys.exc_info(), so we can798 # test that all teardown_requests get passed the same original799 # exception.800 try:801 raise TypeError()802 except Exception:803 pass804805 @app.teardown_request806 def teardown_request2(exc):807 assert type(exc) == ZeroDivisionError808 called.append(True)809 # This raises a new error and blows away sys.exc_info(), so we can810 # test that all teardown_requests get passed the same original811 # exception.812 try:813 raise TypeError()814 except Exception:815 pass816817 @app.route("/")818 def fails():819 1 // 0820821 rv = client.get("/")822 assert rv.status_code == 500823 assert b"Internal Server Error" in rv.data824 assert len(called) == 2825826827def test_before_after_request_order(app, client):828 called = []829830 @app.before_request831 def before1():832 called.append(1)833834 @app.before_request835 def before2():836 called.append(2)837838 @app.after_request839 def after1(response):840 called.append(4)841 return response842843 @app.after_request844 def after2(response):845 called.append(3)846 return response847848 @app.teardown_request849 def finish1(exc):850 called.append(6)851852 @app.teardown_request853 def finish2(exc):854 called.append(5)855856 @app.route("/")857 def index():858 return "42"859860 rv = client.get("/")861 assert rv.data == b"42"862 assert called == [1, 2, 3, 4, 5, 6]863864865def test_error_handling(app, client):866 app.testing = False867868 @app.errorhandler(404)869 def not_found(e):870 return "not found", 404871872 @app.errorhandler(500)873 def internal_server_error(e):874 return "internal server error", 500875876 @app.errorhandler(Forbidden)877 def forbidden(e):878 return "forbidden", 403879880 @app.route("/")881 def index():882 flask.abort(404)883884 @app.route("/error")885 def error():886 1 // 0887888 @app.route("/forbidden")889 def error2():890 flask.abort(403)891892 rv = client.get("/")893 assert rv.status_code == 404894 assert rv.data == b"not found"895 rv = client.get("/error")896 assert rv.status_code == 500897 assert b"internal server error" == rv.data898 rv = client.get("/forbidden")899 assert rv.status_code == 403900 assert b"forbidden" == rv.data901902903def test_error_handler_unknown_code(app):904 with pytest.raises(KeyError) as exc_info:905 app.register_error_handler(999, lambda e: ("999", 999))906907 assert "Use a subclass" in exc_info.value.args[0]908909910def test_error_handling_processing(app, client):911 app.testing = False912913 @app.errorhandler(500)914 def internal_server_error(e):915 return "internal server error", 500916917 @app.route("/")918 def broken_func():919 1 // 0920921 @app.after_request922 def after_request(resp):923 resp.mimetype = "text/x-special"924 return resp925926 resp = client.get("/")927 assert resp.mimetype == "text/x-special"928 assert resp.data == b"internal server error"929930931def test_baseexception_error_handling(app, client):932 app.testing = False933934 @app.route("/")935 def broken_func():936 raise KeyboardInterrupt()937938 with pytest.raises(KeyboardInterrupt):939 client.get("/")940941 ctx = flask._request_ctx_stack.top942 assert ctx.preserved943 assert type(ctx._preserved_exc) is KeyboardInterrupt944945946def test_before_request_and_routing_errors(app, client):947 @app.before_request948 def attach_something():949 flask.g.something = "value"950951 @app.errorhandler(404)952 def return_something(error):953 return flask.g.something, 404954955 rv = client.get("/")956 assert rv.status_code == 404957 assert rv.data == b"value"958959960def test_user_error_handling(app, client):961 class MyException(Exception):962 pass963964 @app.errorhandler(MyException)965 def handle_my_exception(e):966 assert isinstance(e, MyException)967 return "42"968969 @app.route("/")970 def index():971 raise MyException()972973 assert client.get("/").data == b"42"974975976def test_http_error_subclass_handling(app, client):977 class ForbiddenSubclass(Forbidden):978 pass979980 @app.errorhandler(ForbiddenSubclass)981 def handle_forbidden_subclass(e):982 assert isinstance(e, ForbiddenSubclass)983 return "banana"984985 @app.errorhandler(403)986 def handle_403(e):987 assert not isinstance(e, ForbiddenSubclass)988 assert isinstance(e, Forbidden)989 return "apple"990991 @app.route("/1")992 def index1():993 raise ForbiddenSubclass()994995 @app.route("/2")996 def index2():997 flask.abort(403)998999 @app.route("/3")1000 def index3():1001 raise Forbidden()10021003 assert client.get("/1").data == b"banana"1004 assert client.get("/2").data == b"apple"1005 assert client.get("/3").data == b"apple"100610071008def test_errorhandler_precedence(app, client):1009 class E1(Exception):1010 pass10111012 class E2(Exception):1013 pass10141015 class E3(E1, E2):1016 pass10171018 @app.errorhandler(E2)1019 def handle_e2(e):1020 return "E2"10211022 @app.errorhandler(Exception)1023 def handle_exception(e):1024 return "Exception"10251026 @app.route("/E1")1027 def raise_e1():1028 raise E110291030 @app.route("/E3")1031 def raise_e3():1032 raise E310331034 rv = client.get("/E1")1035 assert rv.data == b"Exception"10361037 rv = client.get("/E3")1038 assert rv.data == b"E2"103910401041def test_trapping_of_bad_request_key_errors(app, client):1042 @app.route("/key")1043 def fail():1044 flask.request.form["missing_key"]10451046 @app.route("/abort")1047 def allow_abort():1048 flask.abort(400)10491050 rv = client.get("/key")1051 assert rv.status_code == 4001052 assert b"missing_key" not in rv.data1053 rv = client.get("/abort")1054 assert rv.status_code == 40010551056 app.debug = True1057 with pytest.raises(KeyError) as e:1058 client.get("/key")1059 assert e.errisinstance(BadRequest)1060 assert "missing_key" in e.value.get_description()1061 rv = client.get("/abort")1062 assert rv.status_code == 40010631064 app.debug = False1065 app.config["TRAP_BAD_REQUEST_ERRORS"] = True1066 with pytest.raises(KeyError):1067 client.get("/key")1068 with pytest.raises(BadRequest):1069 client.get("/abort")107010711072def test_trapping_of_all_http_exceptions(app, client):1073 app.config["TRAP_HTTP_EXCEPTIONS"] = True10741075 @app.route("/fail")1076 def fail():1077 flask.abort(404)10781079 with pytest.raises(NotFound):1080 client.get("/fail")108110821083def test_error_handler_after_processor_error(app, client):1084 app.testing = False10851086 @app.before_request1087 def before_request():1088 if _trigger == "before":1089 1 // 010901091 @app.after_request1092 def after_request(response):1093 if _trigger == "after":1094 1 // 01095 return response10961097 @app.route("/")1098 def index():1099 return "Foo"11001101 @app.errorhandler(500)1102 def internal_server_error(e):1103 return "Hello Server Error", 50011041105 for _trigger in "before", "after":1106 rv = client.get("/")1107 assert rv.status_code == 5001108 assert rv.data == b"Hello Server Error"110911101111def test_enctype_debug_helper(app, client):1112 from flask.debughelpers import DebugFilesKeyError11131114 app.debug = True11151116 @app.route("/fail", methods=["POST"])1117 def index():1118 return flask.request.files["foo"].filename11191120 # with statement is important because we leave an exception on the1121 # stack otherwise and we want to ensure that this is not the case1122 # to not negatively affect other tests.1123 with client:1124 with pytest.raises(DebugFilesKeyError) as e:1125 client.post("/fail", data={"foo": "index.txt"})1126 assert "no file contents were transmitted" in str(e.value)1127 assert "This was submitted: 'index.txt'" in str(e.value)112811291130def test_response_types(app, client):1131 @app.route("/text")1132 def from_text():1133 return "Hällo Wörld"11341135 @app.route("/bytes")1136 def from_bytes():1137 return "Hällo Wörld".encode()11381139 @app.route("/full_tuple")1140 def from_full_tuple():1141 return (1142 "Meh",1143 400,1144 {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1145 )11461147 @app.route("/text_headers")1148 def from_text_headers():1149 return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}11501151 @app.route("/text_status")1152 def from_text_status():1153 return "Hi, status!", 40011541155 @app.route("/response_headers")1156 def from_response_headers():1157 return (1158 flask.Response(1159 "Hello world", 404, {"Content-Type": "text/html", "X-Foo": "Baz"}1160 ),1161 {"Content-Type": "text/plain", "X-Foo": "Bar", "X-Bar": "Foo"},1162 )11631164 @app.route("/response_status")1165 def from_response_status():1166 return app.response_class("Hello world", 400), 50011671168 @app.route("/wsgi")1169 def from_wsgi():1170 return NotFound()11711172 @app.route("/dict")1173 def from_dict():1174 return {"foo": "bar"}, 20111751176 assert client.get("/text").data == "Hällo Wörld".encode()1177 assert client.get("/bytes").data == "Hällo Wörld".encode()11781179 rv = client.get("/full_tuple")1180 assert rv.data == b"Meh"1181 assert rv.headers["X-Foo"] == "Testing"1182 assert rv.status_code == 4001183 assert rv.mimetype == "text/plain"11841185 rv = client.get("/text_headers")1186 assert rv.data == b"Hello"1187 assert rv.headers["X-Foo"] == "Test"1188 assert rv.status_code == 2001189 assert rv.mimetype == "text/plain"11901191 rv = client.get("/text_status")1192 assert rv.data == b"Hi, status!"1193 assert rv.status_code == 4001194 assert rv.mimetype == "text/html"11951196 rv = client.get("/response_headers")1197 assert rv.data == b"Hello world"1198 assert rv.content_type == "text/plain"1199 assert rv.headers.getlist("X-Foo") == ["Bar"]1200 assert rv.headers["X-Bar"] == "Foo"1201 assert rv.status_code == 40412021203 rv = client.get("/response_status")1204 assert rv.data == b"Hello world"1205 assert rv.status_code == 50012061207 rv = client.get("/wsgi")1208 assert b"Not Found" in rv.data1209 assert rv.status_code == 40412101211 rv = client.get("/dict")1212 assert rv.json == {"foo": "bar"}1213 assert rv.status_code == 201121412151216def test_response_type_errors():1217 app = flask.Flask(__name__)1218 app.testing = True12191220 @app.route("/none")1221 def from_none():1222 pass12231224 @app.route("/small_tuple")1225 def from_small_tuple():1226 return ("Hello",)12271228 @app.route("/large_tuple")1229 def from_large_tuple():1230 return "Hello", 234, {"X-Foo": "Bar"}, "???"12311232 @app.route("/bad_type")1233 def from_bad_type():1234 return True12351236 @app.route("/bad_wsgi")1237 def from_bad_wsgi():1238 return lambda: None12391240 c = app.test_client()12411242 with pytest.raises(TypeError) as e:1243 c.get("/none")1244 assert "returned None" in str(e.value)1245 assert "from_none" in str(e.value)12461247 with pytest.raises(TypeError) as e:1248 c.get("/small_tuple")1249 assert "tuple must have the form" in str(e.value)12501251 pytest.raises(TypeError, c.get, "/large_tuple")12521253 with pytest.raises(TypeError) as e:1254 c.get("/bad_type")1255 assert "it was a bool" in str(e.value)12561257 pytest.raises(TypeError, c.get, "/bad_wsgi")125812591260def test_make_response(app, req_ctx):1261 rv = flask.make_response()1262 assert rv.status_code == 2001263 assert rv.data == b""1264 assert rv.mimetype == "text/html"12651266 rv = flask.make_response("Awesome")1267 assert rv.status_code == 2001268 assert rv.data == b"Awesome"1269 assert rv.mimetype == "text/html"12701271 rv = flask.make_response("W00t", 404)1272 assert rv.status_code == 4041273 assert rv.data == b"W00t"1274 assert rv.mimetype == "text/html"127512761277def test_make_response_with_response_instance(app, req_ctx):1278 rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1279 assert rv.status_code == 4001280 assert rv.data == b'{"msg":"W00t"}\n'1281 assert rv.mimetype == "application/json"12821283 rv = flask.make_response(flask.Response(""), 400)1284 assert rv.status_code == 4001285 assert rv.data == b""1286 assert rv.mimetype == "text/html"12871288 rv = flask.make_response(1289 flask.Response("", headers={"Content-Type": "text/html"}),1290 400,1291 [("X-Foo", "bar")],1292 )1293 assert rv.status_code == 4001294 assert rv.headers["Content-Type"] == "text/html"1295 assert rv.headers["X-Foo"] == "bar"129612971298def test_jsonify_no_prettyprint(app, req_ctx):1299 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1300 compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1301 uncompressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}13021303 rv = flask.make_response(flask.jsonify(uncompressed_msg), 200)1304 assert rv.data == compressed_msg130513061307def test_jsonify_prettyprint(app, req_ctx):1308 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1309 compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1310 pretty_response = (1311 b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'1312 )13131314 rv = flask.make_response(flask.jsonify(compressed_msg), 200)1315 assert rv.data == pretty_response131613171318def test_jsonify_mimetype(app, req_ctx):1319 app.config.update({"JSONIFY_MIMETYPE": "application/vnd.api+json"})1320 msg = {"msg": {"submsg": "W00t"}}1321 rv = flask.make_response(flask.jsonify(msg), 200)1322 assert rv.mimetype == "application/vnd.api+json"132313241325def test_json_dump_dataclass(app, req_ctx):1326 from dataclasses import make_dataclass13271328 Data = make_dataclass("Data", [("name", str)])1329 value = flask.json.dumps(Data("Flask"), app=app)1330 value = flask.json.loads(value, app=app)1331 assert value == {"name": "Flask"}133213331334def test_jsonify_args_and_kwargs_check(app, req_ctx):1335 with pytest.raises(TypeError) as e:1336 flask.jsonify("fake args", kwargs="fake")1337 assert "behavior undefined" in str(e.value)133813391340def test_url_generation(app, req_ctx):1341 @app.route("/hello/<name>", methods=["POST"])1342 def hello():1343 pass13441345 assert flask.url_for("hello", name="test x") == "/hello/test%20x"1346 assert (1347 flask.url_for("hello", name="test x", _external=True)1348 == "http://localhost/hello/test%20x"1349 )135013511352def test_build_error_handler(app):1353 # Test base case, a URL which results in a BuildError.1354 with app.test_request_context():1355 pytest.raises(BuildError, flask.url_for, "spam")13561357 # Verify the error is re-raised if not the current exception.1358 try:1359 with app.test_request_context():1360 flask.url_for("spam")1361 except BuildError as err:1362 error = err1363 try:1364 raise RuntimeError("Test case where BuildError is not current.")1365 except RuntimeError:1366 pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})13671368 # Test a custom handler.1369 def handler(error, endpoint, values):1370 # Just a test.1371 return "/test_handler/"13721373 app.url_build_error_handlers.append(handler)1374 with app.test_request_context():1375 assert flask.url_for("spam") == "/test_handler/"137613771378def test_build_error_handler_reraise(app):1379 # Test a custom handler which reraises the BuildError1380 def handler_raises_build_error(error, endpoint, values):1381 raise error13821383 app.url_build_error_handlers.append(handler_raises_build_error)13841385 with app.test_request_context():1386 pytest.raises(BuildError, flask.url_for, "not.existing")138713881389def test_url_for_passes_special_values_to_build_error_handler(app):1390 @app.url_build_error_handlers.append1391 def handler(error, endpoint, values):1392 assert values == {1393 "_external": False,1394 "_anchor": None,1395 "_method": None,1396 "_scheme": None,1397 }1398 return "handled"13991400 with app.test_request_context():1401 flask.url_for("/")140214031404def test_static_files(app, client):1405 rv = client.get("/static/index.html")1406 assert rv.status_code == 2001407 assert rv.data.strip() == b"<h1>Hello World!</h1>"1408 with app.test_request_context():1409 assert flask.url_for("static", filename="index.html") == "/static/index.html"1410 rv.close()141114121413def test_static_url_path():1414 app = flask.Flask(__name__, static_url_path="/foo")1415 app.testing = True1416 rv = app.test_client().get("/foo/index.html")1417 assert rv.status_code == 2001418 rv.close()14191420 with app.test_request_context():1421 assert flask.url_for("static", filename="index.html") == "/foo/index.html"142214231424def test_static_url_path_with_ending_slash():1425 app = flask.Flask(__name__, static_url_path="/foo/")1426 app.testing = True1427 rv = app.test_client().get("/foo/index.html")1428 assert rv.status_code == 2001429 rv.close()14301431 with app.test_request_context():1432 assert flask.url_for("static", filename="index.html") == "/foo/index.html"143314341435def test_static_url_empty_path(app):1436 app = flask.Flask(__name__, static_folder="", static_url_path="")1437 rv = app.test_client().open("/static/index.html", method="GET")1438 assert rv.status_code == 2001439 rv.close()144014411442def test_static_url_empty_path_default(app):1443 app = flask.Flask(__name__, static_folder="")1444 rv = app.test_client().open("/static/index.html", method="GET")1445 assert rv.status_code == 2001446 rv.close()144714481449def test_static_folder_with_pathlib_path(app):1450 from pathlib import Path14511452 app = flask.Flask(__name__, static_folder=Path("static"))1453 rv = app.test_client().open("/static/index.html", method="GET")1454 assert rv.status_code == 2001455 rv.close()145614571458def test_static_folder_with_ending_slash():1459 app = flask.Flask(__name__, static_folder="static/")14601461 @app.route("/<path:path>")1462 def catch_all(path):1463 return path14641465 rv = app.test_client().get("/catch/all")1466 assert rv.data == b"catch/all"146714681469def test_static_route_with_host_matching():1470 app = flask.Flask(__name__, host_matching=True, static_host="example.com")1471 c = app.test_client()1472 rv = c.get("http://example.com/static/index.html")1473 assert rv.status_code == 2001474 rv.close()1475 with app.test_request_context():1476 rv = flask.url_for("static", filename="index.html", _external=True)1477 assert rv == "http://example.com/static/index.html"1478 # Providing static_host without host_matching=True should error.1479 with pytest.raises(Exception):1480 flask.Flask(__name__, static_host="example.com")1481 # Providing host_matching=True with static_folder1482 # but without static_host should error.1483 with pytest.raises(Exception):1484 flask.Flask(__name__, host_matching=True)1485 # Providing host_matching=True without static_host1486 # but with static_folder=None should not error.1487 flask.Flask(__name__, host_matching=True, static_folder=None)148814891490def test_request_locals():1491 assert repr(flask.g) == "<LocalProxy unbound>"1492 assert not flask.g149314941495def test_server_name_subdomain():1496 app = flask.Flask(__name__, subdomain_matching=True)1497 client = app.test_client()14981499 @app.route("/")1500 def index():1501 return "default"15021503 @app.route("/", subdomain="foo")1504 def subdomain():1505 return "subdomain"15061507 app.config["SERVER_NAME"] = "dev.local:5000"1508 rv = client.get("/")1509 assert rv.data == b"default"15101511 rv = client.get("/", "http://dev.local:5000")1512 assert rv.data == b"default"15131514 rv = client.get("/", "https://dev.local:5000")1515 assert rv.data == b"default"15161517 app.config["SERVER_NAME"] = "dev.local:443"1518 rv = client.get("/", "https://dev.local")15191520 # Werkzeug 1.0 fixes matching https scheme with 443 port1521 if rv.status_code != 404:1522 assert rv.data == b"default"15231524 app.config["SERVER_NAME"] = "dev.local"1525 rv = client.get("/", "https://dev.local")1526 assert rv.data == b"default"15271528 # suppress Werkzeug 1.0 warning about name mismatch1529 with pytest.warns(None):1530 rv = client.get("/", "http://foo.localhost")1531 assert rv.status_code == 40415321533 rv = client.get("/", "http://foo.dev.local")1534 assert rv.data == b"subdomain"153515361537@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning")1538@pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning")1539def test_exception_propagation(app, client):1540 def apprunner(config_key):1541 @app.route("/")1542 def index():1543 1 // 015441545 if config_key is not None:1546 app.config[config_key] = True1547 with pytest.raises(Exception):1548 client.get("/")1549 else:1550 assert client.get("/").status_code == 50015511552 # we have to run this test in an isolated thread because if the1553 # debug flag is set to true and an exception happens the context is1554 # not torn down. This causes other tests that run after this fail1555 # when they expect no exception on the stack.1556 for config_key in "TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None:1557 t = Thread(target=apprunner, args=(config_key,))1558 t.start()1559 t.join()156015611562@pytest.mark.parametrize("debug", [True, False])1563@pytest.mark.parametrize("use_debugger", [True, False])1564@pytest.mark.parametrize("use_reloader", [True, False])1565@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1566def test_werkzeug_passthrough_errors(1567 monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1568):1569 rv = {}15701571 # Mocks werkzeug.serving.run_simple method1572 def run_simple_mock(*args, **kwargs):1573 rv["passthrough_errors"] = kwargs.get("passthrough_errors")15741575 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1576 app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1577 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)157815791580def test_max_content_length(app, client):1581 app.config["MAX_CONTENT_LENGTH"] = 6415821583 @app.before_request1584 def always_first():1585 flask.request.form["myfile"]1586 AssertionError()15871588 @app.route("/accept", methods=["POST"])1589 def accept_file():1590 flask.request.form["myfile"]1591 AssertionError()15921593 @app.errorhandler(413)1594 def catcher(error):1595 return "42"15961597 rv = client.post("/accept", data={"myfile": "foo" * 100})1598 assert rv.data == b"42"159916001601def test_url_processors(app, client):1602 @app.url_defaults1603 def add_language_code(endpoint, values):1604 if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1605 endpoint, "lang_code"1606 ):1607 values.setdefault("lang_code", flask.g.lang_code)16081609 @app.url_value_preprocessor1610 def pull_lang_code(endpoint, values):1611 flask.g.lang_code = values.pop("lang_code", None)16121613 @app.route("/<lang_code>/")1614 def index():1615 return flask.url_for("about")16161617 @app.route("/<lang_code>/about")1618 def about():1619 return flask.url_for("something_else")16201621 @app.route("/foo")1622 def something_else():1623 return flask.url_for("about", lang_code="en")16241625 assert client.get("/de/").data == b"/de/about"1626 assert client.get("/de/about").data == b"/foo"1627 assert client.get("/foo").data == b"/en/about"162816291630def test_inject_blueprint_url_defaults(app):1631 bp = flask.Blueprint("foo", __name__, template_folder="template")16321633 @bp.url_defaults1634 def bp_defaults(endpoint, values):1635 values["page"] = "login"16361637 @bp.route("/<page>")1638 def view(page):1639 pass16401641 app.register_blueprint(bp)16421643 values = dict()1644 app.inject_url_defaults("foo.view", values)1645 expected = dict(page="login")1646 assert values == expected16471648 with app.test_request_context("/somepage"):1649 url = flask.url_for("foo.view")1650 expected = "/login"1651 assert url == expected165216531654def test_nonascii_pathinfo(app, client):1655 @app.route("/киртест")1656 def index():1657 return "Hello World!"16581659 rv = client.get("/киртест")1660 assert rv.data == b"Hello World!"166116621663def test_debug_mode_complains_after_first_request(app, client):1664 app.debug = True16651666 @app.route("/")1667 def index():1668 return "Awesome"16691670 assert not app.got_first_request1671 assert client.get("/").data == b"Awesome"1672 with pytest.raises(AssertionError) as e:16731674 @app.route("/foo")1675 def broken():1676 return "Meh"16771678 assert "A setup function was called" in str(e.value)16791680 app.debug = False16811682 @app.route("/foo")1683 def working():1684 return "Meh"16851686 assert client.get("/foo").data == b"Meh"1687 assert app.got_first_request168816891690def test_before_first_request_functions(app, client):1691 got = []16921693 @app.before_first_request1694 def foo():1695 got.append(42)16961697 client.get("/")1698 assert got == [42]1699 client.get("/")1700 assert got == [42]1701 assert app.got_first_request170217031704def test_before_first_request_functions_concurrent(app, client):1705 got = []17061707 @app.before_first_request1708 def foo():1709 time.sleep(0.2)1710 got.append(42)17111712 def get_and_assert():1713 client.get("/")1714 assert got == [42]17151716 t = Thread(target=get_and_assert)1717 t.start()1718 get_and_assert()1719 t.join()1720 assert app.got_first_request172117221723def test_routing_redirect_debugging(app, client):1724 app.debug = True17251726 @app.route("/foo/", methods=["GET", "POST"])1727 def foo():1728 return "success"17291730 with client:1731 with pytest.raises(AssertionError) as e:1732 client.post("/foo", data={})1733 assert "http://localhost/foo/" in str(e.value)1734 assert "Make sure to directly send your POST-request to this URL" in str(1735 e.value1736 )17371738 rv = client.get("/foo", data={}, follow_redirects=True)1739 assert rv.data == b"success"17401741 app.debug = False1742 with client:1743 rv = client.post("/foo", data={}, follow_redirects=True)1744 assert rv.data == b"success"174517461747def test_route_decorator_custom_endpoint(app, client):1748 app.debug = True17491750 @app.route("/foo/")1751 def foo():1752 return flask.request.endpoint17531754 @app.route("/bar/", endpoint="bar")1755 def for_bar():1756 return flask.request.endpoint17571758 @app.route("/bar/123", endpoint="123")1759 def for_bar_foo():1760 return flask.request.endpoint17611762 with app.test_request_context():1763 assert flask.url_for("foo") == "/foo/"1764 assert flask.url_for("bar") == "/bar/"1765 assert flask.url_for("123") == "/bar/123"17661767 assert client.get("/foo/").data == b"foo"1768 assert client.get("/bar/").data == b"bar"1769 assert client.get("/bar/123").data == b"123"177017711772def test_preserve_only_once(app, client):1773 app.debug = True17741775 @app.route("/fail")1776 def fail_func():1777 1 // 017781779 for _x in range(3):1780 with pytest.raises(ZeroDivisionError):1781 client.get("/fail")17821783 assert flask._request_ctx_stack.top is not None1784 assert flask._app_ctx_stack.top is not None1785 # implicit appctx disappears too1786 flask._request_ctx_stack.top.pop()1787 assert flask._request_ctx_stack.top is None1788 assert flask._app_ctx_stack.top is None178917901791def test_preserve_remembers_exception(app, client):1792 app.debug = True1793 errors = []17941795 @app.route("/fail")1796 def fail_func():1797 1 // 017981799 @app.route("/success")1800 def success_func():1801 return "Okay"18021803 @app.teardown_request1804 def teardown_handler(exc):1805 errors.append(exc)18061807 # After this failure we did not yet call the teardown handler1808 with pytest.raises(ZeroDivisionError):1809 client.get("/fail")1810 assert errors == []18111812 # But this request triggers it, and it's an error1813 client.get("/success")1814 assert len(errors) == 21815 assert isinstance(errors[0], ZeroDivisionError)18161817 # At this point another request does nothing.1818 client.get("/success")1819 assert len(errors) == 31820 assert errors[1] is None182118221823def test_get_method_on_g(app_ctx):1824 assert flask.g.get("x") is None1825 assert flask.g.get("x", 11) == 111826 flask.g.x = 421827 assert flask.g.get("x") == 421828 assert flask.g.x == 42182918301831def test_g_iteration_protocol(app_ctx):1832 flask.g.foo = 231833 flask.g.bar = 421834 assert "foo" in flask.g1835 assert "foos" not in flask.g1836 assert sorted(flask.g) == ["bar", "foo"]183718381839def test_subdomain_basic_support():1840 app = flask.Flask(__name__, subdomain_matching=True)1841 app.config["SERVER_NAME"] = "localhost.localdomain"1842 client = app.test_client()18431844 @app.route("/")1845 def normal_index():1846 return "normal index"18471848 @app.route("/", subdomain="test")1849 def test_index():1850 return "test index"18511852 rv = client.get("/", "http://localhost.localdomain/")1853 assert rv.data == b"normal index"18541855 rv = client.get("/", "http://test.localhost.localdomain/")1856 assert rv.data == b"test index"185718581859def test_subdomain_matching():1860 app = flask.Flask(__name__, subdomain_matching=True)1861 client = app.test_client()1862 app.config["SERVER_NAME"] = "localhost.localdomain"18631864 @app.route("/", subdomain="<user>")1865 def index(user):1866 return f"index for {user}"18671868 rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1869 assert rv.data == b"index for mitsuhiko"187018711872def test_subdomain_matching_with_ports():1873 app = flask.Flask(__name__, subdomain_matching=True)1874 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1875 client = app.test_client()18761877 @app.route("/", subdomain="<user>")1878 def index(user):1879 return f"index for {user}"18801881 rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1882 assert rv.data == b"index for mitsuhiko"188318841885@pytest.mark.parametrize("matching", (False, True))1886def test_subdomain_matching_other_name(matching):1887 app = flask.Flask(__name__, subdomain_matching=matching)1888 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1889 client = app.test_client()18901891 @app.route("/")1892 def index():1893 return "", 20418941895 # suppress Werkzeug 0.15 warning about name mismatch1896 with pytest.warns(None):1897 # ip address can't match name1898 rv = client.get("/", "http://127.0.0.1:3000/")1899 assert rv.status_code == 404 if matching else 20419001901 # allow all subdomains if matching is disabled1902 rv = client.get("/", "http://www.localhost.localdomain:3000/")1903 assert rv.status_code == 404 if matching else 204190419051906def test_multi_route_rules(app, client):1907 @app.route("/")1908 @app.route("/<test>/")1909 def index(test="a"):1910 return test19111912 rv = client.open("/")1913 assert rv.data == b"a"1914 rv = client.open("/b/")1915 assert rv.data == b"b"191619171918def test_multi_route_class_views(app, client):1919 class View:1920 def __init__(self, app):1921 app.add_url_rule("/", "index", self.index)1922 app.add_url_rule("/<test>/", "index", self.index)19231924 def index(self, test="a"):1925 return test19261927 _ = View(app)1928 rv = client.open("/")1929 assert rv.data == b"a"1930 rv = client.open("/b/")1931 assert rv.data == b"b"193219331934def test_run_defaults(monkeypatch, app):1935 rv = {}19361937 # Mocks werkzeug.serving.run_simple method1938 def run_simple_mock(*args, **kwargs):1939 rv["result"] = "running..."19401941 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1942 app.run()1943 assert rv["result"] == "running..."194419451946def test_run_server_port(monkeypatch, app):1947 rv = {}19481949 # Mocks werkzeug.serving.run_simple method1950 def run_simple_mock(hostname, port, application, *args, **kwargs):1951 rv["result"] = f"running on {hostname}:{port} ..."19521953 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1954 hostname, port = "localhost", 80001955 app.run(hostname, port, debug=True)1956 assert rv["result"] == f"running on {hostname}:{port} ..."195719581959@pytest.mark.parametrize(1960 "host,port,server_name,expect_host,expect_port",1961 (1962 (None, None, "pocoo.org:8080", "pocoo.org", 8080),1963 ("localhost", None, "pocoo.org:8080", "localhost", 8080),1964 (None, 80, "pocoo.org:8080", "pocoo.org", 80),1965 ("localhost", 80, "pocoo.org:8080", "localhost", 80),1966 ("localhost", 0, "localhost:8080", "localhost", 0),1967 (None, None, "localhost:8080", "localhost", 8080),1968 (None, None, "localhost:0", "localhost", 0),1969 ),1970)1971def test_run_from_config(1972 monkeypatch, host, port, server_name, expect_host, expect_port, app1973):1974 def run_simple_mock(hostname, port, *args, **kwargs):1975 assert hostname == expect_host1976 assert port == expect_port19771978 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1979 app.config["SERVER_NAME"] = server_name1980 app.run(host, port)198119821983def test_max_cookie_size(app, client, recwarn):1984 app.config["MAX_COOKIE_SIZE"] = 10019851986 # outside app context, default to Werkzeug static value,1987 # which is also the default config1988 response = flask.Response()1989 default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1990 assert response.max_cookie_size == default19911992 # inside app context, use app config1993 with app.app_context():1994 assert flask.Response().max_cookie_size == 10019951996 @app.route("/")1997 def index():1998 r = flask.Response("", status=204)1999 r.set_cookie("foo", "bar" * 100)2000 return rThe first 2,000 of 2,026 lines.