test_basic.py
This file
Path
tests/test_basic.py
1,987 lines · 53.2 KiB · Python
Last changed by
Merge pull request #4049 from brettlangdon/fix.os.fspathDavid Lordbefore adoption5f8d3ea
History of this fileTake it
1# -*- coding: utf-8 -*-2"""3 tests.basic4 ~~~~~~~~~~~~~~~~~~~~~56 The basic functionality.78 :copyright: 2010 Pallets9 :license: BSD-3-Clause10"""11import re12import sys13import time14import uuid15from datetime import datetime16from threading import Thread1718import pytest19import werkzeug.serving20from werkzeug.exceptions import BadRequest21from werkzeug.exceptions import Forbidden22from werkzeug.exceptions import NotFound23from werkzeug.http import parse_date24from werkzeug.routing import BuildError2526import flask27from flask._compat import text_type282930def test_options_work(app, client):31 @app.route("/", methods=["GET", "POST"])32 def index():33 return "Hello World"3435 rv = client.open("/", method="OPTIONS")36 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]37 assert rv.data == b""383940def test_options_on_multiple_rules(app, client):41 @app.route("/", methods=["GET", "POST"])42 def index():43 return "Hello World"4445 @app.route("/", methods=["PUT"])46 def index_put():47 return "Aha!"4849 rv = client.open("/", method="OPTIONS")50 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST", "PUT"]515253def test_provide_automatic_options_attr():54 app = flask.Flask(__name__)5556 def index():57 return "Hello World!"5859 index.provide_automatic_options = False60 app.route("/")(index)61 rv = app.test_client().open("/", method="OPTIONS")62 assert rv.status_code == 4056364 app = flask.Flask(__name__)6566 def index2():67 return "Hello World!"6869 index2.provide_automatic_options = True70 app.route("/", methods=["OPTIONS"])(index2)71 rv = app.test_client().open("/", method="OPTIONS")72 assert sorted(rv.allow) == ["OPTIONS"]737475def test_provide_automatic_options_kwarg(app, client):76 def index():77 return flask.request.method7879 def more():80 return flask.request.method8182 app.add_url_rule("/", view_func=index, provide_automatic_options=False)83 app.add_url_rule(84 "/more",85 view_func=more,86 methods=["GET", "POST"],87 provide_automatic_options=False,88 )89 assert client.get("/").data == b"GET"9091 rv = client.post("/")92 assert rv.status_code == 40593 assert sorted(rv.allow) == ["GET", "HEAD"]9495 # Older versions of Werkzeug.test.Client don't have an options method96 if hasattr(client, "options"):97 rv = client.options("/")98 else:99 rv = client.open("/", method="OPTIONS")100101 assert rv.status_code == 405102103 rv = client.head("/")104 assert rv.status_code == 200105 assert not rv.data # head truncates106 assert client.post("/more").data == b"POST"107 assert client.get("/more").data == b"GET"108109 rv = client.delete("/more")110 assert rv.status_code == 405111 assert sorted(rv.allow) == ["GET", "HEAD", "POST"]112113 if hasattr(client, "options"):114 rv = client.options("/more")115 else:116 rv = client.open("/more", method="OPTIONS")117118 assert rv.status_code == 405119120121def test_request_dispatching(app, client):122 @app.route("/")123 def index():124 return flask.request.method125126 @app.route("/more", methods=["GET", "POST"])127 def more():128 return flask.request.method129130 assert client.get("/").data == b"GET"131 rv = client.post("/")132 assert rv.status_code == 405133 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]134 rv = client.head("/")135 assert rv.status_code == 200136 assert not rv.data # head truncates137 assert client.post("/more").data == b"POST"138 assert client.get("/more").data == b"GET"139 rv = client.delete("/more")140 assert rv.status_code == 405141 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]142143144def test_disallow_string_for_allowed_methods(app):145 with pytest.raises(TypeError):146147 @app.route("/", methods="GET POST")148 def index():149 return "Hey"150151152def test_url_mapping(app, client):153 random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"154155 def index():156 return flask.request.method157158 def more():159 return flask.request.method160161 def options():162 return random_uuid4163164 app.add_url_rule("/", "index", index)165 app.add_url_rule("/more", "more", more, methods=["GET", "POST"])166167 # Issue 1288: Test that automatic options are not added168 # when non-uppercase 'options' in methods169 app.add_url_rule("/options", "options", options, methods=["options"])170171 assert client.get("/").data == b"GET"172 rv = client.post("/")173 assert rv.status_code == 405174 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]175 rv = client.head("/")176 assert rv.status_code == 200177 assert not rv.data # head truncates178 assert client.post("/more").data == b"POST"179 assert client.get("/more").data == b"GET"180 rv = client.delete("/more")181 assert rv.status_code == 405182 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]183 rv = client.open("/options", method="OPTIONS")184 assert rv.status_code == 200185 assert random_uuid4 in rv.data.decode("utf-8")186187188def test_werkzeug_routing(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 def bar():196 return "bar"197198 def index():199 return "index"200201 app.view_functions["bar"] = bar202 app.view_functions["index"] = index203204 assert client.get("/foo/").data == b"index"205 assert client.get("/foo/bar").data == b"bar"206207208def test_endpoint_decorator(app, client):209 from werkzeug.routing import Submount, Rule210211 app.url_map.add(212 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])213 )214215 @app.endpoint("bar")216 def bar():217 return "bar"218219 @app.endpoint("index")220 def index():221 return "index"222223 assert client.get("/foo/").data == b"index"224 assert client.get("/foo/bar").data == b"bar"225226227def test_session(app, client):228 @app.route("/set", methods=["POST"])229 def set():230 assert not flask.session.accessed231 assert not flask.session.modified232 flask.session["value"] = flask.request.form["value"]233 assert flask.session.accessed234 assert flask.session.modified235 return "value set"236237 @app.route("/get")238 def get():239 assert not flask.session.accessed240 assert not flask.session.modified241 v = flask.session.get("value", "None")242 assert flask.session.accessed243 assert not flask.session.modified244 return v245246 assert client.post("/set", data={"value": "42"}).data == b"value set"247 assert client.get("/get").data == b"42"248249250def test_session_using_server_name(app, client):251 app.config.update(SERVER_NAME="example.com")252253 @app.route("/")254 def index():255 flask.session["testing"] = 42256 return "Hello World"257258 rv = client.get("/", "http://example.com/")259 assert "domain=.example.com" in rv.headers["set-cookie"].lower()260 assert "httponly" in rv.headers["set-cookie"].lower()261262263def test_session_using_server_name_and_port(app, client):264 app.config.update(SERVER_NAME="example.com:8080")265266 @app.route("/")267 def index():268 flask.session["testing"] = 42269 return "Hello World"270271 rv = client.get("/", "http://example.com:8080/")272 assert "domain=.example.com" in rv.headers["set-cookie"].lower()273 assert "httponly" in rv.headers["set-cookie"].lower()274275276def test_session_using_server_name_port_and_path(app, client):277 app.config.update(SERVER_NAME="example.com:8080", APPLICATION_ROOT="/foo")278279 @app.route("/")280 def index():281 flask.session["testing"] = 42282 return "Hello World"283284 rv = client.get("/", "http://example.com:8080/foo")285 assert "domain=example.com" in rv.headers["set-cookie"].lower()286 assert "path=/foo" in rv.headers["set-cookie"].lower()287 assert "httponly" in rv.headers["set-cookie"].lower()288289290def test_session_using_application_root(app, client):291 class PrefixPathMiddleware(object):292 def __init__(self, app, prefix):293 self.app = app294 self.prefix = prefix295296 def __call__(self, environ, start_response):297 environ["SCRIPT_NAME"] = self.prefix298 return self.app(environ, start_response)299300 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, "/bar")301 app.config.update(APPLICATION_ROOT="/bar")302303 @app.route("/")304 def index():305 flask.session["testing"] = 42306 return "Hello World"307308 rv = client.get("/", "http://example.com:8080/")309 assert "path=/bar" in rv.headers["set-cookie"].lower()310311312def test_session_using_session_settings(app, client):313 app.config.update(314 SERVER_NAME="www.example.com:8080",315 APPLICATION_ROOT="/test",316 SESSION_COOKIE_DOMAIN=".example.com",317 SESSION_COOKIE_HTTPONLY=False,318 SESSION_COOKIE_SECURE=True,319 SESSION_COOKIE_SAMESITE="Lax",320 SESSION_COOKIE_PATH="/",321 )322323 @app.route("/")324 def index():325 flask.session["testing"] = 42326 return "Hello World"327328 rv = client.get("/", "http://www.example.com:8080/test/")329 cookie = rv.headers["set-cookie"].lower()330 assert "domain=.example.com" in cookie331 assert "path=/" in cookie332 assert "secure" in cookie333 assert "httponly" not in cookie334 assert "samesite" in cookie335336337def test_session_using_samesite_attribute(app, client):338 @app.route("/")339 def index():340 flask.session["testing"] = 42341 return "Hello World"342343 app.config.update(SESSION_COOKIE_SAMESITE="invalid")344345 with pytest.raises(ValueError):346 client.get("/")347348 app.config.update(SESSION_COOKIE_SAMESITE=None)349 rv = client.get("/")350 cookie = rv.headers["set-cookie"].lower()351 assert "samesite" not in cookie352353 app.config.update(SESSION_COOKIE_SAMESITE="Strict")354 rv = client.get("/")355 cookie = rv.headers["set-cookie"].lower()356 assert "samesite=strict" in cookie357358 app.config.update(SESSION_COOKIE_SAMESITE="Lax")359 rv = client.get("/")360 cookie = rv.headers["set-cookie"].lower()361 assert "samesite=lax" in cookie362363364def test_session_localhost_warning(recwarn, app, client):365 app.config.update(SERVER_NAME="localhost:5000")366367 @app.route("/")368 def index():369 flask.session["testing"] = 42370 return "testing"371372 rv = client.get("/", "http://localhost:5000/")373 assert "domain" not in rv.headers["set-cookie"].lower()374 w = recwarn.pop(UserWarning)375 assert '"localhost" is not a valid cookie domain' in str(w.message)376377378def test_session_ip_warning(recwarn, app, client):379 app.config.update(SERVER_NAME="127.0.0.1:5000")380381 @app.route("/")382 def index():383 flask.session["testing"] = 42384 return "testing"385386 rv = client.get("/", "http://127.0.0.1:5000/")387 assert "domain=127.0.0.1" in rv.headers["set-cookie"].lower()388 w = recwarn.pop(UserWarning)389 assert "cookie domain is an IP" in str(w.message)390391392def test_missing_session(app):393 app.secret_key = None394395 def expect_exception(f, *args, **kwargs):396 e = pytest.raises(RuntimeError, f, *args, **kwargs)397 assert e.value.args and "session is unavailable" in e.value.args[0]398399 with app.test_request_context():400 assert flask.session.get("missing_key") is None401 expect_exception(flask.session.__setitem__, "foo", 42)402 expect_exception(flask.session.pop, "foo")403404405def test_session_expiration(app, client):406 permanent = True407408 @app.route("/")409 def index():410 flask.session["test"] = 42411 flask.session.permanent = permanent412 return ""413414 @app.route("/test")415 def test():416 return text_type(flask.session.permanent)417418 rv = client.get("/")419 assert "set-cookie" in rv.headers420 match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])421 expires = parse_date(match.group())422 expected = datetime.utcnow() + app.permanent_session_lifetime423 assert expires.year == expected.year424 assert expires.month == expected.month425 assert expires.day == expected.day426427 rv = client.get("/test")428 assert rv.data == b"True"429430 permanent = False431 rv = client.get("/")432 assert "set-cookie" in rv.headers433 match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])434 assert match is None435436437def test_session_stored_last(app, client):438 @app.after_request439 def modify_session(response):440 flask.session["foo"] = 42441 return response442443 @app.route("/")444 def dump_session_contents():445 return repr(flask.session.get("foo"))446447 assert client.get("/").data == b"None"448 assert client.get("/").data == b"42"449450451def test_session_special_types(app, client):452 now = datetime.utcnow().replace(microsecond=0)453 the_uuid = uuid.uuid4()454455 @app.route("/")456 def dump_session_contents():457 flask.session["t"] = (1, 2, 3)458 flask.session["b"] = b"\xff"459 flask.session["m"] = flask.Markup("<html>")460 flask.session["u"] = the_uuid461 flask.session["d"] = now462 flask.session["t_tag"] = {" t": "not-a-tuple"}463 flask.session["di_t_tag"] = {" t__": "not-a-tuple"}464 flask.session["di_tag"] = {" di": "not-a-dict"}465 return "", 204466467 with client:468 client.get("/")469 s = flask.session470 assert s["t"] == (1, 2, 3)471 assert type(s["b"]) == bytes472 assert s["b"] == b"\xff"473 assert type(s["m"]) == flask.Markup474 assert s["m"] == flask.Markup("<html>")475 assert s["u"] == the_uuid476 assert s["d"] == now477 assert s["t_tag"] == {" t": "not-a-tuple"}478 assert s["di_t_tag"] == {" t__": "not-a-tuple"}479 assert s["di_tag"] == {" di": "not-a-dict"}480481482def test_session_cookie_setting(app):483 is_permanent = True484485 @app.route("/bump")486 def bump():487 rv = flask.session["foo"] = flask.session.get("foo", 0) + 1488 flask.session.permanent = is_permanent489 return str(rv)490491 @app.route("/read")492 def read():493 return str(flask.session.get("foo", 0))494495 def run_test(expect_header):496 with app.test_client() as c:497 assert c.get("/bump").data == b"1"498 assert c.get("/bump").data == b"2"499 assert c.get("/bump").data == b"3"500501 rv = c.get("/read")502 set_cookie = rv.headers.get("set-cookie")503 assert (set_cookie is not None) == expect_header504 assert rv.data == b"3"505506 is_permanent = True507 app.config["SESSION_REFRESH_EACH_REQUEST"] = True508 run_test(expect_header=True)509510 is_permanent = True511 app.config["SESSION_REFRESH_EACH_REQUEST"] = False512 run_test(expect_header=False)513514 is_permanent = False515 app.config["SESSION_REFRESH_EACH_REQUEST"] = True516 run_test(expect_header=False)517518 is_permanent = False519 app.config["SESSION_REFRESH_EACH_REQUEST"] = False520 run_test(expect_header=False)521522523def test_session_vary_cookie(app, client):524 @app.route("/set")525 def set_session():526 flask.session["test"] = "test"527 return ""528529 @app.route("/get")530 def get():531 return flask.session.get("test")532533 @app.route("/getitem")534 def getitem():535 return flask.session["test"]536537 @app.route("/setdefault")538 def setdefault():539 return flask.session.setdefault("test", "default")540541 @app.route("/vary-cookie-header-set")542 def vary_cookie_header_set():543 response = flask.Response()544 response.vary.add("Cookie")545 flask.session["test"] = "test"546 return response547548 @app.route("/vary-header-set")549 def vary_header_set():550 response = flask.Response()551 response.vary.update(("Accept-Encoding", "Accept-Language"))552 flask.session["test"] = "test"553 return response554555 @app.route("/no-vary-header")556 def no_vary_header():557 return ""558559 def expect(path, header_value="Cookie"):560 rv = client.get(path)561562 if header_value:563 # The 'Vary' key should exist in the headers only once.564 assert len(rv.headers.get_all("Vary")) == 1565 assert rv.headers["Vary"] == header_value566 else:567 assert "Vary" not in rv.headers568569 expect("/set")570 expect("/get")571 expect("/getitem")572 expect("/setdefault")573 expect("/vary-cookie-header-set")574 expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")575 expect("/no-vary-header", None)576577578def test_flashes(app, req_ctx):579 assert not flask.session.modified580 flask.flash("Zap")581 flask.session.modified = False582 flask.flash("Zip")583 assert flask.session.modified584 assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]585586587def test_extended_flashing(app):588 # Be sure app.testing=True below, else tests can fail silently.589 #590 # Specifically, if app.testing is not set to True, the AssertionErrors591 # in the view functions will cause a 500 response to the test client592 # instead of propagating exceptions.593594 @app.route("/")595 def index():596 flask.flash(u"Hello World")597 flask.flash(u"Hello World", "error")598 flask.flash(flask.Markup(u"<em>Testing</em>"), "warning")599 return ""600601 @app.route("/test/")602 def test():603 messages = flask.get_flashed_messages()604 assert list(messages) == [605 u"Hello World",606 u"Hello World",607 flask.Markup(u"<em>Testing</em>"),608 ]609 return ""610611 @app.route("/test_with_categories/")612 def test_with_categories():613 messages = flask.get_flashed_messages(with_categories=True)614 assert len(messages) == 3615 assert list(messages) == [616 ("message", u"Hello World"),617 ("error", u"Hello World"),618 ("warning", flask.Markup(u"<em>Testing</em>")),619 ]620 return ""621622 @app.route("/test_filter/")623 def test_filter():624 messages = flask.get_flashed_messages(625 category_filter=["message"], with_categories=True626 )627 assert list(messages) == [("message", u"Hello World")]628 return ""629630 @app.route("/test_filters/")631 def test_filters():632 messages = flask.get_flashed_messages(633 category_filter=["message", "warning"], with_categories=True634 )635 assert list(messages) == [636 ("message", u"Hello World"),637 ("warning", flask.Markup(u"<em>Testing</em>")),638 ]639 return ""640641 @app.route("/test_filters_without_returning_categories/")642 def test_filters2():643 messages = flask.get_flashed_messages(category_filter=["message", "warning"])644 assert len(messages) == 2645 assert messages[0] == u"Hello World"646 assert messages[1] == flask.Markup(u"<em>Testing</em>")647 return ""648649 # Create new test client on each test to clean flashed messages.650651 client = app.test_client()652 client.get("/")653 client.get("/test_with_categories/")654655 client = app.test_client()656 client.get("/")657 client.get("/test_filter/")658659 client = app.test_client()660 client.get("/")661 client.get("/test_filters/")662663 client = app.test_client()664 client.get("/")665 client.get("/test_filters_without_returning_categories/")666667668def test_request_processing(app, client):669 evts = []670671 @app.before_request672 def before_request():673 evts.append("before")674675 @app.after_request676 def after_request(response):677 response.data += b"|after"678 evts.append("after")679 return response680681 @app.route("/")682 def index():683 assert "before" in evts684 assert "after" not in evts685 return "request"686687 assert "after" not in evts688 rv = client.get("/").data689 assert "after" in evts690 assert rv == b"request|after"691692693def test_request_preprocessing_early_return(app, client):694 evts = []695696 @app.before_request697 def before_request1():698 evts.append(1)699700 @app.before_request701 def before_request2():702 evts.append(2)703 return "hello"704705 @app.before_request706 def before_request3():707 evts.append(3)708 return "bye"709710 @app.route("/")711 def index():712 evts.append("index")713 return "damnit"714715 rv = client.get("/").data.strip()716 assert rv == b"hello"717 assert evts == [1, 2]718719720def test_after_request_processing(app, client):721 @app.route("/")722 def index():723 @flask.after_this_request724 def foo(response):725 response.headers["X-Foo"] = "a header"726 return response727728 return "Test"729730 resp = client.get("/")731 assert resp.status_code == 200732 assert resp.headers["X-Foo"] == "a header"733734735def test_teardown_request_handler(app, client):736 called = []737738 @app.teardown_request739 def teardown_request(exc):740 called.append(True)741 return "Ignored"742743 @app.route("/")744 def root():745 return "Response"746747 rv = client.get("/")748 assert rv.status_code == 200749 assert b"Response" in rv.data750 assert len(called) == 1751752753def test_teardown_request_handler_debug_mode(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_error(app, client):772 called = []773 app.testing = False774775 @app.teardown_request776 def teardown_request1(exc):777 assert type(exc) == ZeroDivisionError778 called.append(True)779 # This raises a new error and blows away sys.exc_info(), so we can780 # test that all teardown_requests get passed the same original781 # exception.782 try:783 raise TypeError()784 except Exception:785 pass786787 @app.teardown_request788 def teardown_request2(exc):789 assert type(exc) == ZeroDivisionError790 called.append(True)791 # This raises a new error and blows away sys.exc_info(), so we can792 # test that all teardown_requests get passed the same original793 # exception.794 try:795 raise TypeError()796 except Exception:797 pass798799 @app.route("/")800 def fails():801 1 // 0802803 rv = client.get("/")804 assert rv.status_code == 500805 assert b"Internal Server Error" in rv.data806 assert len(called) == 2807808809def test_before_after_request_order(app, client):810 called = []811812 @app.before_request813 def before1():814 called.append(1)815816 @app.before_request817 def before2():818 called.append(2)819820 @app.after_request821 def after1(response):822 called.append(4)823 return response824825 @app.after_request826 def after2(response):827 called.append(3)828 return response829830 @app.teardown_request831 def finish1(exc):832 called.append(6)833834 @app.teardown_request835 def finish2(exc):836 called.append(5)837838 @app.route("/")839 def index():840 return "42"841842 rv = client.get("/")843 assert rv.data == b"42"844 assert called == [1, 2, 3, 4, 5, 6]845846847def test_error_handling(app, client):848 app.testing = False849850 @app.errorhandler(404)851 def not_found(e):852 return "not found", 404853854 @app.errorhandler(500)855 def internal_server_error(e):856 return "internal server error", 500857858 @app.errorhandler(Forbidden)859 def forbidden(e):860 return "forbidden", 403861862 @app.route("/")863 def index():864 flask.abort(404)865866 @app.route("/error")867 def error():868 1 // 0869870 @app.route("/forbidden")871 def error2():872 flask.abort(403)873874 rv = client.get("/")875 assert rv.status_code == 404876 assert rv.data == b"not found"877 rv = client.get("/error")878 assert rv.status_code == 500879 assert b"internal server error" == rv.data880 rv = client.get("/forbidden")881 assert rv.status_code == 403882 assert b"forbidden" == rv.data883884885def test_error_handler_unknown_code(app):886 with pytest.raises(KeyError) as exc_info:887 app.register_error_handler(999, lambda e: ("999", 999))888889 assert "Use a subclass" in exc_info.value.args[0]890891892def test_error_handling_processing(app, client):893 app.testing = False894895 @app.errorhandler(500)896 def internal_server_error(e):897 return "internal server error", 500898899 @app.route("/")900 def broken_func():901 1 // 0902903 @app.after_request904 def after_request(resp):905 resp.mimetype = "text/x-special"906 return resp907908 resp = client.get("/")909 assert resp.mimetype == "text/x-special"910 assert resp.data == b"internal server error"911912913def test_baseexception_error_handling(app, client):914 app.testing = False915916 @app.route("/")917 def broken_func():918 raise KeyboardInterrupt()919920 with pytest.raises(KeyboardInterrupt):921 client.get("/")922923 ctx = flask._request_ctx_stack.top924 assert ctx.preserved925 assert type(ctx._preserved_exc) is KeyboardInterrupt926927928def test_before_request_and_routing_errors(app, client):929 @app.before_request930 def attach_something():931 flask.g.something = "value"932933 @app.errorhandler(404)934 def return_something(error):935 return flask.g.something, 404936937 rv = client.get("/")938 assert rv.status_code == 404939 assert rv.data == b"value"940941942def test_user_error_handling(app, client):943 class MyException(Exception):944 pass945946 @app.errorhandler(MyException)947 def handle_my_exception(e):948 assert isinstance(e, MyException)949 return "42"950951 @app.route("/")952 def index():953 raise MyException()954955 assert client.get("/").data == b"42"956957958def test_http_error_subclass_handling(app, client):959 class ForbiddenSubclass(Forbidden):960 pass961962 @app.errorhandler(ForbiddenSubclass)963 def handle_forbidden_subclass(e):964 assert isinstance(e, ForbiddenSubclass)965 return "banana"966967 @app.errorhandler(403)968 def handle_403(e):969 assert not isinstance(e, ForbiddenSubclass)970 assert isinstance(e, Forbidden)971 return "apple"972973 @app.route("/1")974 def index1():975 raise ForbiddenSubclass()976977 @app.route("/2")978 def index2():979 flask.abort(403)980981 @app.route("/3")982 def index3():983 raise Forbidden()984985 assert client.get("/1").data == b"banana"986 assert client.get("/2").data == b"apple"987 assert client.get("/3").data == b"apple"988989990def test_errorhandler_precedence(app, client):991 class E1(Exception):992 pass993994 class E2(Exception):995 pass996997 class E3(E1, E2):998 pass9991000 @app.errorhandler(E2)1001 def handle_e2(e):1002 return "E2"10031004 @app.errorhandler(Exception)1005 def handle_exception(e):1006 return "Exception"10071008 @app.route("/E1")1009 def raise_e1():1010 raise E110111012 @app.route("/E3")1013 def raise_e3():1014 raise E310151016 rv = client.get("/E1")1017 assert rv.data == b"Exception"10181019 rv = client.get("/E3")1020 assert rv.data == b"E2"102110221023def test_trapping_of_bad_request_key_errors(app, client):1024 @app.route("/key")1025 def fail():1026 flask.request.form["missing_key"]10271028 @app.route("/abort")1029 def allow_abort():1030 flask.abort(400)10311032 rv = client.get("/key")1033 assert rv.status_code == 4001034 assert b"missing_key" not in rv.data1035 rv = client.get("/abort")1036 assert rv.status_code == 40010371038 app.debug = True1039 with pytest.raises(KeyError) as e:1040 client.get("/key")1041 assert e.errisinstance(BadRequest)1042 assert "missing_key" in e.value.get_description()1043 rv = client.get("/abort")1044 assert rv.status_code == 40010451046 app.debug = False1047 app.config["TRAP_BAD_REQUEST_ERRORS"] = True1048 with pytest.raises(KeyError):1049 client.get("/key")1050 with pytest.raises(BadRequest):1051 client.get("/abort")105210531054def test_trapping_of_all_http_exceptions(app, client):1055 app.config["TRAP_HTTP_EXCEPTIONS"] = True10561057 @app.route("/fail")1058 def fail():1059 flask.abort(404)10601061 with pytest.raises(NotFound):1062 client.get("/fail")106310641065def test_error_handler_after_processor_error(app, client):1066 app.testing = False10671068 @app.before_request1069 def before_request():1070 if _trigger == "before":1071 1 // 010721073 @app.after_request1074 def after_request(response):1075 if _trigger == "after":1076 1 // 01077 return response10781079 @app.route("/")1080 def index():1081 return "Foo"10821083 @app.errorhandler(500)1084 def internal_server_error(e):1085 return "Hello Server Error", 50010861087 for _trigger in "before", "after":1088 rv = client.get("/")1089 assert rv.status_code == 5001090 assert rv.data == b"Hello Server Error"109110921093def test_enctype_debug_helper(app, client):1094 from flask.debughelpers import DebugFilesKeyError10951096 app.debug = True10971098 @app.route("/fail", methods=["POST"])1099 def index():1100 return flask.request.files["foo"].filename11011102 # with statement is important because we leave an exception on the1103 # stack otherwise and we want to ensure that this is not the case1104 # to not negatively affect other tests.1105 with client:1106 with pytest.raises(DebugFilesKeyError) as e:1107 client.post("/fail", data={"foo": "index.txt"})1108 assert "no file contents were transmitted" in str(e.value)1109 assert 'This was submitted: "index.txt"' in str(e.value)111011111112def test_response_types(app, client):1113 @app.route("/text")1114 def from_text():1115 return u"Hällo Wörld"11161117 @app.route("/bytes")1118 def from_bytes():1119 return u"Hällo Wörld".encode("utf-8")11201121 @app.route("/full_tuple")1122 def from_full_tuple():1123 return (1124 "Meh",1125 400,1126 {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1127 )11281129 @app.route("/text_headers")1130 def from_text_headers():1131 return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}11321133 @app.route("/text_status")1134 def from_text_status():1135 return "Hi, status!", 40011361137 @app.route("/response_headers")1138 def from_response_headers():1139 return (1140 flask.Response("Hello world", 404, {"X-Foo": "Baz"}),1141 {"X-Foo": "Bar", "X-Bar": "Foo"},1142 )11431144 @app.route("/response_status")1145 def from_response_status():1146 return app.response_class("Hello world", 400), 50011471148 @app.route("/wsgi")1149 def from_wsgi():1150 return NotFound()11511152 @app.route("/dict")1153 def from_dict():1154 return {"foo": "bar"}, 20111551156 assert client.get("/text").data == u"Hällo Wörld".encode("utf-8")1157 assert client.get("/bytes").data == u"Hällo Wörld".encode("utf-8")11581159 rv = client.get("/full_tuple")1160 assert rv.data == b"Meh"1161 assert rv.headers["X-Foo"] == "Testing"1162 assert rv.status_code == 4001163 assert rv.mimetype == "text/plain"11641165 rv = client.get("/text_headers")1166 assert rv.data == b"Hello"1167 assert rv.headers["X-Foo"] == "Test"1168 assert rv.status_code == 2001169 assert rv.mimetype == "text/plain"11701171 rv = client.get("/text_status")1172 assert rv.data == b"Hi, status!"1173 assert rv.status_code == 4001174 assert rv.mimetype == "text/html"11751176 rv = client.get("/response_headers")1177 assert rv.data == b"Hello world"1178 assert rv.headers.getlist("X-Foo") == ["Baz", "Bar"]1179 assert rv.headers["X-Bar"] == "Foo"1180 assert rv.status_code == 40411811182 rv = client.get("/response_status")1183 assert rv.data == b"Hello world"1184 assert rv.status_code == 50011851186 rv = client.get("/wsgi")1187 assert b"Not Found" in rv.data1188 assert rv.status_code == 40411891190 rv = client.get("/dict")1191 assert rv.json == {"foo": "bar"}1192 assert rv.status_code == 201119311941195def test_response_type_errors():1196 app = flask.Flask(__name__)1197 app.testing = True11981199 @app.route("/none")1200 def from_none():1201 pass12021203 @app.route("/small_tuple")1204 def from_small_tuple():1205 return ("Hello",)12061207 @app.route("/large_tuple")1208 def from_large_tuple():1209 return "Hello", 234, {"X-Foo": "Bar"}, "???"12101211 @app.route("/bad_type")1212 def from_bad_type():1213 return True12141215 @app.route("/bad_wsgi")1216 def from_bad_wsgi():1217 return lambda: None12181219 c = app.test_client()12201221 with pytest.raises(TypeError) as e:1222 c.get("/none")1223 assert "returned None" in str(e.value)12241225 with pytest.raises(TypeError) as e:1226 c.get("/small_tuple")1227 assert "tuple must have the form" in str(e.value)12281229 pytest.raises(TypeError, c.get, "/large_tuple")12301231 with pytest.raises(TypeError) as e:1232 c.get("/bad_type")1233 assert "it was a bool" in str(e.value)12341235 pytest.raises(TypeError, c.get, "/bad_wsgi")123612371238def test_make_response(app, req_ctx):1239 rv = flask.make_response()1240 assert rv.status_code == 2001241 assert rv.data == b""1242 assert rv.mimetype == "text/html"12431244 rv = flask.make_response("Awesome")1245 assert rv.status_code == 2001246 assert rv.data == b"Awesome"1247 assert rv.mimetype == "text/html"12481249 rv = flask.make_response("W00t", 404)1250 assert rv.status_code == 4041251 assert rv.data == b"W00t"1252 assert rv.mimetype == "text/html"125312541255def test_make_response_with_response_instance(app, req_ctx):1256 rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1257 assert rv.status_code == 4001258 assert rv.data == b'{"msg":"W00t"}\n'1259 assert rv.mimetype == "application/json"12601261 rv = flask.make_response(flask.Response(""), 400)1262 assert rv.status_code == 4001263 assert rv.data == b""1264 assert rv.mimetype == "text/html"12651266 rv = flask.make_response(1267 flask.Response("", headers={"Content-Type": "text/html"}),1268 400,1269 [("X-Foo", "bar")],1270 )1271 assert rv.status_code == 4001272 assert rv.headers["Content-Type"] == "text/html"1273 assert rv.headers["X-Foo"] == "bar"127412751276def test_jsonify_no_prettyprint(app, req_ctx):1277 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1278 compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1279 uncompressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}12801281 rv = flask.make_response(flask.jsonify(uncompressed_msg), 200)1282 assert rv.data == compressed_msg128312841285def test_jsonify_prettyprint(app, req_ctx):1286 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1287 compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1288 pretty_response = (1289 b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'1290 )12911292 rv = flask.make_response(flask.jsonify(compressed_msg), 200)1293 assert rv.data == pretty_response129412951296def test_jsonify_mimetype(app, req_ctx):1297 app.config.update({"JSONIFY_MIMETYPE": "application/vnd.api+json"})1298 msg = {"msg": {"submsg": "W00t"}}1299 rv = flask.make_response(flask.jsonify(msg), 200)1300 assert rv.mimetype == "application/vnd.api+json"130113021303@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")1304def test_json_dump_dataclass(app, req_ctx):1305 from dataclasses import make_dataclass13061307 Data = make_dataclass("Data", [("name", str)])1308 value = flask.json.dumps(Data("Flask"), app=app)1309 value = flask.json.loads(value, app=app)1310 assert value == {"name": "Flask"}131113121313def test_jsonify_args_and_kwargs_check(app, req_ctx):1314 with pytest.raises(TypeError) as e:1315 flask.jsonify("fake args", kwargs="fake")1316 assert "behavior undefined" in str(e.value)131713181319def test_url_generation(app, req_ctx):1320 @app.route("/hello/<name>", methods=["POST"])1321 def hello():1322 pass13231324 assert flask.url_for("hello", name="test x") == "/hello/test%20x"1325 assert (1326 flask.url_for("hello", name="test x", _external=True)1327 == "http://localhost/hello/test%20x"1328 )132913301331def test_build_error_handler(app):1332 # Test base case, a URL which results in a BuildError.1333 with app.test_request_context():1334 pytest.raises(BuildError, flask.url_for, "spam")13351336 # Verify the error is re-raised if not the current exception.1337 try:1338 with app.test_request_context():1339 flask.url_for("spam")1340 except BuildError as err:1341 error = err1342 try:1343 raise RuntimeError("Test case where BuildError is not current.")1344 except RuntimeError:1345 pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})13461347 # Test a custom handler.1348 def handler(error, endpoint, values):1349 # Just a test.1350 return "/test_handler/"13511352 app.url_build_error_handlers.append(handler)1353 with app.test_request_context():1354 assert flask.url_for("spam") == "/test_handler/"135513561357def test_build_error_handler_reraise(app):1358 # Test a custom handler which reraises the BuildError1359 def handler_raises_build_error(error, endpoint, values):1360 raise error13611362 app.url_build_error_handlers.append(handler_raises_build_error)13631364 with app.test_request_context():1365 pytest.raises(BuildError, flask.url_for, "not.existing")136613671368def test_url_for_passes_special_values_to_build_error_handler(app):1369 @app.url_build_error_handlers.append1370 def handler(error, endpoint, values):1371 assert values == {1372 "_external": False,1373 "_anchor": None,1374 "_method": None,1375 "_scheme": None,1376 }1377 return "handled"13781379 with app.test_request_context():1380 flask.url_for("/")138113821383def test_static_files(app, client):1384 rv = client.get("/static/index.html")1385 assert rv.status_code == 2001386 assert rv.data.strip() == b"<h1>Hello World!</h1>"1387 with app.test_request_context():1388 assert flask.url_for("static", filename="index.html") == "/static/index.html"1389 rv.close()139013911392def test_static_url_path():1393 app = flask.Flask(__name__, static_url_path="/foo")1394 app.testing = True1395 rv = app.test_client().get("/foo/index.html")1396 assert rv.status_code == 2001397 rv.close()13981399 with app.test_request_context():1400 assert flask.url_for("static", filename="index.html") == "/foo/index.html"140114021403def test_static_url_path_with_ending_slash():1404 app = flask.Flask(__name__, static_url_path="/foo/")1405 app.testing = True1406 rv = app.test_client().get("/foo/index.html")1407 assert rv.status_code == 2001408 rv.close()14091410 with app.test_request_context():1411 assert flask.url_for("static", filename="index.html") == "/foo/index.html"141214131414def test_static_url_empty_path(app):1415 app = flask.Flask(__name__, static_folder="", static_url_path="")1416 rv = app.test_client().open("/static/index.html", method="GET")1417 assert rv.status_code == 2001418 rv.close()141914201421def test_static_url_empty_path_default(app):1422 app = flask.Flask(__name__, static_folder="")1423 rv = app.test_client().open("/static/index.html", method="GET")1424 assert rv.status_code == 2001425 rv.close()142614271428def test_static_folder_with_pathlib_path(app):1429 from pathlib import Path14301431 app = flask.Flask(__name__, static_folder=Path("static"))1432 rv = app.test_client().open("/static/index.html", method="GET")1433 assert rv.status_code == 2001434 rv.close()143514361437def test_static_folder_with_ending_slash():1438 app = flask.Flask(__name__, static_folder="static/")14391440 @app.route("/<path:path>")1441 def catch_all(path):1442 return path14431444 rv = app.test_client().get("/catch/all")1445 assert rv.data == b"catch/all"144614471448def test_static_route_with_host_matching():1449 app = flask.Flask(__name__, host_matching=True, static_host="example.com")1450 c = app.test_client()1451 rv = c.get("http://example.com/static/index.html")1452 assert rv.status_code == 2001453 rv.close()1454 with app.test_request_context():1455 rv = flask.url_for("static", filename="index.html", _external=True)1456 assert rv == "http://example.com/static/index.html"1457 # Providing static_host without host_matching=True should error.1458 with pytest.raises(Exception):1459 flask.Flask(__name__, static_host="example.com")1460 # Providing host_matching=True with static_folder1461 # but without static_host should error.1462 with pytest.raises(Exception):1463 flask.Flask(__name__, host_matching=True)1464 # Providing host_matching=True without static_host1465 # but with static_folder=None should not error.1466 flask.Flask(__name__, host_matching=True, static_folder=None)146714681469def test_request_locals():1470 assert repr(flask.g) == "<LocalProxy unbound>"1471 assert not flask.g147214731474def test_server_name_subdomain():1475 app = flask.Flask(__name__, subdomain_matching=True)1476 client = app.test_client()14771478 @app.route("/")1479 def index():1480 return "default"14811482 @app.route("/", subdomain="foo")1483 def subdomain():1484 return "subdomain"14851486 app.config["SERVER_NAME"] = "dev.local:5000"1487 rv = client.get("/")1488 assert rv.data == b"default"14891490 rv = client.get("/", "http://dev.local:5000")1491 assert rv.data == b"default"14921493 rv = client.get("/", "https://dev.local:5000")1494 assert rv.data == b"default"14951496 app.config["SERVER_NAME"] = "dev.local:443"1497 rv = client.get("/", "https://dev.local")14981499 # Werkzeug 1.0 fixes matching https scheme with 443 port1500 if rv.status_code != 404:1501 assert rv.data == b"default"15021503 app.config["SERVER_NAME"] = "dev.local"1504 rv = client.get("/", "https://dev.local")1505 assert rv.data == b"default"15061507 # suppress Werkzeug 1.0 warning about name mismatch1508 with pytest.warns(None):1509 rv = client.get("/", "http://foo.localhost")1510 assert rv.status_code == 40415111512 rv = client.get("/", "http://foo.dev.local")1513 assert rv.data == b"subdomain"151415151516def test_exception_propagation(app, client):1517 def apprunner(config_key):1518 @app.route("/")1519 def index():1520 1 // 015211522 if config_key is not None:1523 app.config[config_key] = True1524 with pytest.raises(Exception):1525 client.get("/")1526 else:1527 assert client.get("/").status_code == 50015281529 # we have to run this test in an isolated thread because if the1530 # debug flag is set to true and an exception happens the context is1531 # not torn down. This causes other tests that run after this fail1532 # when they expect no exception on the stack.1533 for config_key in "TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None:1534 t = Thread(target=apprunner, args=(config_key,))1535 t.start()1536 t.join()153715381539@pytest.mark.parametrize("debug", [True, False])1540@pytest.mark.parametrize("use_debugger", [True, False])1541@pytest.mark.parametrize("use_reloader", [True, False])1542@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1543def test_werkzeug_passthrough_errors(1544 monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1545):1546 rv = {}15471548 # Mocks werkzeug.serving.run_simple method1549 def run_simple_mock(*args, **kwargs):1550 rv["passthrough_errors"] = kwargs.get("passthrough_errors")15511552 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1553 app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1554 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)155515561557def test_max_content_length(app, client):1558 app.config["MAX_CONTENT_LENGTH"] = 6415591560 @app.before_request1561 def always_first():1562 flask.request.form["myfile"]1563 AssertionError()15641565 @app.route("/accept", methods=["POST"])1566 def accept_file():1567 flask.request.form["myfile"]1568 AssertionError()15691570 @app.errorhandler(413)1571 def catcher(error):1572 return "42"15731574 rv = client.post("/accept", data={"myfile": "foo" * 100})1575 assert rv.data == b"42"157615771578def test_url_processors(app, client):1579 @app.url_defaults1580 def add_language_code(endpoint, values):1581 if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1582 endpoint, "lang_code"1583 ):1584 values.setdefault("lang_code", flask.g.lang_code)15851586 @app.url_value_preprocessor1587 def pull_lang_code(endpoint, values):1588 flask.g.lang_code = values.pop("lang_code", None)15891590 @app.route("/<lang_code>/")1591 def index():1592 return flask.url_for("about")15931594 @app.route("/<lang_code>/about")1595 def about():1596 return flask.url_for("something_else")15971598 @app.route("/foo")1599 def something_else():1600 return flask.url_for("about", lang_code="en")16011602 assert client.get("/de/").data == b"/de/about"1603 assert client.get("/de/about").data == b"/foo"1604 assert client.get("/foo").data == b"/en/about"160516061607def test_inject_blueprint_url_defaults(app):1608 bp = flask.Blueprint("foo.bar.baz", __name__, template_folder="template")16091610 @bp.url_defaults1611 def bp_defaults(endpoint, values):1612 values["page"] = "login"16131614 @bp.route("/<page>")1615 def view(page):1616 pass16171618 app.register_blueprint(bp)16191620 values = dict()1621 app.inject_url_defaults("foo.bar.baz.view", values)1622 expected = dict(page="login")1623 assert values == expected16241625 with app.test_request_context("/somepage"):1626 url = flask.url_for("foo.bar.baz.view")1627 expected = "/login"1628 assert url == expected162916301631def test_nonascii_pathinfo(app, client):1632 @app.route(u"/киртест")1633 def index():1634 return "Hello World!"16351636 rv = client.get(u"/киртест")1637 assert rv.data == b"Hello World!"163816391640def test_debug_mode_complains_after_first_request(app, client):1641 app.debug = True16421643 @app.route("/")1644 def index():1645 return "Awesome"16461647 assert not app.got_first_request1648 assert client.get("/").data == b"Awesome"1649 with pytest.raises(AssertionError) as e:16501651 @app.route("/foo")1652 def broken():1653 return "Meh"16541655 assert "A setup function was called" in str(e.value)16561657 app.debug = False16581659 @app.route("/foo")1660 def working():1661 return "Meh"16621663 assert client.get("/foo").data == b"Meh"1664 assert app.got_first_request166516661667def test_before_first_request_functions(app, client):1668 got = []16691670 @app.before_first_request1671 def foo():1672 got.append(42)16731674 client.get("/")1675 assert got == [42]1676 client.get("/")1677 assert got == [42]1678 assert app.got_first_request167916801681def test_before_first_request_functions_concurrent(app, client):1682 got = []16831684 @app.before_first_request1685 def foo():1686 time.sleep(0.2)1687 got.append(42)16881689 def get_and_assert():1690 client.get("/")1691 assert got == [42]16921693 t = Thread(target=get_and_assert)1694 t.start()1695 get_and_assert()1696 t.join()1697 assert app.got_first_request169816991700def test_routing_redirect_debugging(app, client):1701 app.debug = True17021703 @app.route("/foo/", methods=["GET", "POST"])1704 def foo():1705 return "success"17061707 with client:1708 with pytest.raises(AssertionError) as e:1709 client.post("/foo", data={})1710 assert "http://localhost/foo/" in str(e.value)1711 assert ("Make sure to directly send your POST-request to this URL") in str(1712 e.value1713 )17141715 rv = client.get("/foo", data={}, follow_redirects=True)1716 assert rv.data == b"success"17171718 app.debug = False1719 with client:1720 rv = client.post("/foo", data={}, follow_redirects=True)1721 assert rv.data == b"success"172217231724def test_route_decorator_custom_endpoint(app, client):1725 app.debug = True17261727 @app.route("/foo/")1728 def foo():1729 return flask.request.endpoint17301731 @app.route("/bar/", endpoint="bar")1732 def for_bar():1733 return flask.request.endpoint17341735 @app.route("/bar/123", endpoint="123")1736 def for_bar_foo():1737 return flask.request.endpoint17381739 with app.test_request_context():1740 assert flask.url_for("foo") == "/foo/"1741 assert flask.url_for("bar") == "/bar/"1742 assert flask.url_for("123") == "/bar/123"17431744 assert client.get("/foo/").data == b"foo"1745 assert client.get("/bar/").data == b"bar"1746 assert client.get("/bar/123").data == b"123"174717481749def test_preserve_only_once(app, client):1750 app.debug = True17511752 @app.route("/fail")1753 def fail_func():1754 1 // 017551756 for _x in range(3):1757 with pytest.raises(ZeroDivisionError):1758 client.get("/fail")17591760 assert flask._request_ctx_stack.top is not None1761 assert flask._app_ctx_stack.top is not None1762 # implicit appctx disappears too1763 flask._request_ctx_stack.top.pop()1764 assert flask._request_ctx_stack.top is None1765 assert flask._app_ctx_stack.top is None176617671768def test_preserve_remembers_exception(app, client):1769 app.debug = True1770 errors = []17711772 @app.route("/fail")1773 def fail_func():1774 1 // 017751776 @app.route("/success")1777 def success_func():1778 return "Okay"17791780 @app.teardown_request1781 def teardown_handler(exc):1782 errors.append(exc)17831784 # After this failure we did not yet call the teardown handler1785 with pytest.raises(ZeroDivisionError):1786 client.get("/fail")1787 assert errors == []17881789 # But this request triggers it, and it's an error1790 client.get("/success")1791 assert len(errors) == 21792 assert isinstance(errors[0], ZeroDivisionError)17931794 # At this point another request does nothing.1795 client.get("/success")1796 assert len(errors) == 31797 assert errors[1] is None179817991800def test_get_method_on_g(app_ctx):1801 assert flask.g.get("x") is None1802 assert flask.g.get("x", 11) == 111803 flask.g.x = 421804 assert flask.g.get("x") == 421805 assert flask.g.x == 42180618071808def test_g_iteration_protocol(app_ctx):1809 flask.g.foo = 231810 flask.g.bar = 421811 assert "foo" in flask.g1812 assert "foos" not in flask.g1813 assert sorted(flask.g) == ["bar", "foo"]181418151816def test_subdomain_basic_support():1817 app = flask.Flask(__name__, subdomain_matching=True)1818 app.config["SERVER_NAME"] = "localhost.localdomain"1819 client = app.test_client()18201821 @app.route("/")1822 def normal_index():1823 return "normal index"18241825 @app.route("/", subdomain="test")1826 def test_index():1827 return "test index"18281829 rv = client.get("/", "http://localhost.localdomain/")1830 assert rv.data == b"normal index"18311832 rv = client.get("/", "http://test.localhost.localdomain/")1833 assert rv.data == b"test index"183418351836def test_subdomain_matching():1837 app = flask.Flask(__name__, subdomain_matching=True)1838 client = app.test_client()1839 app.config["SERVER_NAME"] = "localhost.localdomain"18401841 @app.route("/", subdomain="<user>")1842 def index(user):1843 return "index for %s" % user18441845 rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1846 assert rv.data == b"index for mitsuhiko"184718481849def test_subdomain_matching_with_ports():1850 app = flask.Flask(__name__, subdomain_matching=True)1851 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1852 client = app.test_client()18531854 @app.route("/", subdomain="<user>")1855 def index(user):1856 return "index for %s" % user18571858 rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1859 assert rv.data == b"index for mitsuhiko"186018611862@pytest.mark.parametrize("matching", (False, True))1863def test_subdomain_matching_other_name(matching):1864 app = flask.Flask(__name__, subdomain_matching=matching)1865 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1866 client = app.test_client()18671868 @app.route("/")1869 def index():1870 return "", 20418711872 # suppress Werkzeug 0.15 warning about name mismatch1873 with pytest.warns(None):1874 # ip address can't match name1875 rv = client.get("/", "http://127.0.0.1:3000/")1876 assert rv.status_code == 404 if matching else 20418771878 # allow all subdomains if matching is disabled1879 rv = client.get("/", "http://www.localhost.localdomain:3000/")1880 assert rv.status_code == 404 if matching else 204188118821883def test_multi_route_rules(app, client):1884 @app.route("/")1885 @app.route("/<test>/")1886 def index(test="a"):1887 return test18881889 rv = client.open("/")1890 assert rv.data == b"a"1891 rv = client.open("/b/")1892 assert rv.data == b"b"189318941895def test_multi_route_class_views(app, client):1896 class View(object):1897 def __init__(self, app):1898 app.add_url_rule("/", "index", self.index)1899 app.add_url_rule("/<test>/", "index", self.index)19001901 def index(self, test="a"):1902 return test19031904 _ = View(app)1905 rv = client.open("/")1906 assert rv.data == b"a"1907 rv = client.open("/b/")1908 assert rv.data == b"b"190919101911def test_run_defaults(monkeypatch, app):1912 rv = {}19131914 # Mocks werkzeug.serving.run_simple method1915 def run_simple_mock(*args, **kwargs):1916 rv["result"] = "running..."19171918 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1919 app.run()1920 assert rv["result"] == "running..."192119221923def test_run_server_port(monkeypatch, app):1924 rv = {}19251926 # Mocks werkzeug.serving.run_simple method1927 def run_simple_mock(hostname, port, application, *args, **kwargs):1928 rv["result"] = "running on %s:%s ..." % (hostname, port)19291930 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1931 hostname, port = "localhost", 80001932 app.run(hostname, port, debug=True)1933 assert rv["result"] == "running on %s:%s ..." % (hostname, port)193419351936@pytest.mark.parametrize(1937 "host,port,server_name,expect_host,expect_port",1938 (1939 (None, None, "pocoo.org:8080", "pocoo.org", 8080),1940 ("localhost", None, "pocoo.org:8080", "localhost", 8080),1941 (None, 80, "pocoo.org:8080", "pocoo.org", 80),1942 ("localhost", 80, "pocoo.org:8080", "localhost", 80),1943 ("localhost", 0, "localhost:8080", "localhost", 0),1944 (None, None, "localhost:8080", "localhost", 8080),1945 (None, None, "localhost:0", "localhost", 0),1946 ),1947)1948def test_run_from_config(1949 monkeypatch, host, port, server_name, expect_host, expect_port, app1950):1951 def run_simple_mock(hostname, port, *args, **kwargs):1952 assert hostname == expect_host1953 assert port == expect_port19541955 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1956 app.config["SERVER_NAME"] = server_name1957 app.run(host, port)195819591960def test_max_cookie_size(app, client, recwarn):1961 app.config["MAX_COOKIE_SIZE"] = 10019621963 # outside app context, default to Werkzeug static value,1964 # which is also the default config1965 response = flask.Response()1966 default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1967 assert response.max_cookie_size == default19681969 # inside app context, use app config1970 with app.app_context():1971 assert flask.Response().max_cookie_size == 10019721973 @app.route("/")1974 def index():1975 r = flask.Response("", status=204)1976 r.set_cookie("foo", "bar" * 100)1977 return r19781979 client.get("/")1980 assert len(recwarn) == 11981 w = recwarn.pop()1982 assert "cookie is too large" in str(w.message)19831984 app.config["MAX_COOKIE_SIZE"] = 019851986 client.get("/")1987 assert len(recwarn) == 0