test_basic.py
This file
Path
tests/test_basic.py
1,944 lines · 52.0 KiB · Python
Last changed by
Merge pull request #3183 from singingwolfboy/pre-commitDavid Baumgoldbefore adoption1dda032
History of this fileTake it
1# -*- coding: utf-8 -*-2"""3 tests.basic4 ~~~~~~~~~~~~~~~~~~~~~56 The basic functionality.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112import re13import time14import uuid15from datetime import datetime16from threading import Thread1718import pytest19import werkzeug.serving20from werkzeug.exceptions import BadRequest, Forbidden, NotFound21from werkzeug.http import parse_date22from werkzeug.routing import BuildError2324import flask25from flask._compat import text_type262728def test_options_work(app, client):29 @app.route("/", methods=["GET", "POST"])30 def index():31 return "Hello World"3233 rv = client.open("/", method="OPTIONS")34 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]35 assert rv.data == b""363738def test_options_on_multiple_rules(app, client):39 @app.route("/", methods=["GET", "POST"])40 def index():41 return "Hello World"4243 @app.route("/", methods=["PUT"])44 def index_put():45 return "Aha!"4647 rv = client.open("/", method="OPTIONS")48 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST", "PUT"]495051def test_provide_automatic_options_attr():52 app = flask.Flask(__name__)5354 def index():55 return "Hello World!"5657 index.provide_automatic_options = False58 app.route("/")(index)59 rv = app.test_client().open("/", method="OPTIONS")60 assert rv.status_code == 4056162 app = flask.Flask(__name__)6364 def index2():65 return "Hello World!"6667 index2.provide_automatic_options = True68 app.route("/", methods=["OPTIONS"])(index2)69 rv = app.test_client().open("/", method="OPTIONS")70 assert sorted(rv.allow) == ["OPTIONS"]717273def test_provide_automatic_options_kwarg(app, client):74 def index():75 return flask.request.method7677 def more():78 return flask.request.method7980 app.add_url_rule("/", view_func=index, provide_automatic_options=False)81 app.add_url_rule(82 "/more",83 view_func=more,84 methods=["GET", "POST"],85 provide_automatic_options=False,86 )87 assert client.get("/").data == b"GET"8889 rv = client.post("/")90 assert rv.status_code == 40591 assert sorted(rv.allow) == ["GET", "HEAD"]9293 # Older versions of Werkzeug.test.Client don't have an options method94 if hasattr(client, "options"):95 rv = client.options("/")96 else:97 rv = client.open("/", method="OPTIONS")9899 assert rv.status_code == 405100101 rv = client.head("/")102 assert rv.status_code == 200103 assert not rv.data # head truncates104 assert client.post("/more").data == b"POST"105 assert client.get("/more").data == b"GET"106107 rv = client.delete("/more")108 assert rv.status_code == 405109 assert sorted(rv.allow) == ["GET", "HEAD", "POST"]110111 if hasattr(client, "options"):112 rv = client.options("/more")113 else:114 rv = client.open("/more", method="OPTIONS")115116 assert rv.status_code == 405117118119def test_request_dispatching(app, client):120 @app.route("/")121 def index():122 return flask.request.method123124 @app.route("/more", methods=["GET", "POST"])125 def more():126 return flask.request.method127128 assert client.get("/").data == b"GET"129 rv = client.post("/")130 assert rv.status_code == 405131 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]132 rv = client.head("/")133 assert rv.status_code == 200134 assert not rv.data # head truncates135 assert client.post("/more").data == b"POST"136 assert client.get("/more").data == b"GET"137 rv = client.delete("/more")138 assert rv.status_code == 405139 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]140141142def test_disallow_string_for_allowed_methods(app):143 with pytest.raises(TypeError):144145 @app.route("/", methods="GET POST")146 def index():147 return "Hey"148149150def test_url_mapping(app, client):151 random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"152153 def index():154 return flask.request.method155156 def more():157 return flask.request.method158159 def options():160 return random_uuid4161162 app.add_url_rule("/", "index", index)163 app.add_url_rule("/more", "more", more, methods=["GET", "POST"])164165 # Issue 1288: Test that automatic options are not added when non-uppercase 'options' in methods166 app.add_url_rule("/options", "options", options, methods=["options"])167168 assert client.get("/").data == b"GET"169 rv = client.post("/")170 assert rv.status_code == 405171 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]172 rv = client.head("/")173 assert rv.status_code == 200174 assert not rv.data # head truncates175 assert client.post("/more").data == b"POST"176 assert client.get("/more").data == b"GET"177 rv = client.delete("/more")178 assert rv.status_code == 405179 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]180 rv = client.open("/options", method="OPTIONS")181 assert rv.status_code == 200182 assert random_uuid4 in rv.data.decode("utf-8")183184185def test_werkzeug_routing(app, client):186 from werkzeug.routing import Submount, Rule187188 app.url_map.add(189 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])190 )191192 def bar():193 return "bar"194195 def index():196 return "index"197198 app.view_functions["bar"] = bar199 app.view_functions["index"] = index200201 assert client.get("/foo/").data == b"index"202 assert client.get("/foo/bar").data == b"bar"203204205def test_endpoint_decorator(app, client):206 from werkzeug.routing import Submount, Rule207208 app.url_map.add(209 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])210 )211212 @app.endpoint("bar")213 def bar():214 return "bar"215216 @app.endpoint("index")217 def index():218 return "index"219220 assert client.get("/foo/").data == b"index"221 assert client.get("/foo/bar").data == b"bar"222223224def test_session(app, client):225 @app.route("/set", methods=["POST"])226 def set():227 assert not flask.session.accessed228 assert not flask.session.modified229 flask.session["value"] = flask.request.form["value"]230 assert flask.session.accessed231 assert flask.session.modified232 return "value set"233234 @app.route("/get")235 def get():236 assert not flask.session.accessed237 assert not flask.session.modified238 v = flask.session.get("value", "None")239 assert flask.session.accessed240 assert not flask.session.modified241 return v242243 assert client.post("/set", data={"value": "42"}).data == b"value set"244 assert client.get("/get").data == b"42"245246247def test_session_using_server_name(app, client):248 app.config.update(SERVER_NAME="example.com")249250 @app.route("/")251 def index():252 flask.session["testing"] = 42253 return "Hello World"254255 rv = client.get("/", "http://example.com/")256 assert "domain=.example.com" in rv.headers["set-cookie"].lower()257 assert "httponly" in rv.headers["set-cookie"].lower()258259260def test_session_using_server_name_and_port(app, client):261 app.config.update(SERVER_NAME="example.com:8080")262263 @app.route("/")264 def index():265 flask.session["testing"] = 42266 return "Hello World"267268 rv = client.get("/", "http://example.com:8080/")269 assert "domain=.example.com" in rv.headers["set-cookie"].lower()270 assert "httponly" in rv.headers["set-cookie"].lower()271272273def test_session_using_server_name_port_and_path(app, client):274 app.config.update(SERVER_NAME="example.com:8080", APPLICATION_ROOT="/foo")275276 @app.route("/")277 def index():278 flask.session["testing"] = 42279 return "Hello World"280281 rv = client.get("/", "http://example.com:8080/foo")282 assert "domain=example.com" in rv.headers["set-cookie"].lower()283 assert "path=/foo" in rv.headers["set-cookie"].lower()284 assert "httponly" in rv.headers["set-cookie"].lower()285286287def test_session_using_application_root(app, client):288 class PrefixPathMiddleware(object):289 def __init__(self, app, prefix):290 self.app = app291 self.prefix = prefix292293 def __call__(self, environ, start_response):294 environ["SCRIPT_NAME"] = self.prefix295 return self.app(environ, start_response)296297 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, "/bar")298 app.config.update(APPLICATION_ROOT="/bar")299300 @app.route("/")301 def index():302 flask.session["testing"] = 42303 return "Hello World"304305 rv = client.get("/", "http://example.com:8080/")306 assert "path=/bar" in rv.headers["set-cookie"].lower()307308309def test_session_using_session_settings(app, client):310 app.config.update(311 SERVER_NAME="www.example.com:8080",312 APPLICATION_ROOT="/test",313 SESSION_COOKIE_DOMAIN=".example.com",314 SESSION_COOKIE_HTTPONLY=False,315 SESSION_COOKIE_SECURE=True,316 SESSION_COOKIE_SAMESITE="Lax",317 SESSION_COOKIE_PATH="/",318 )319320 @app.route("/")321 def index():322 flask.session["testing"] = 42323 return "Hello World"324325 rv = client.get("/", "http://www.example.com:8080/test/")326 cookie = rv.headers["set-cookie"].lower()327 assert "domain=.example.com" in cookie328 assert "path=/" in cookie329 assert "secure" in cookie330 assert "httponly" not in cookie331 assert "samesite" in cookie332333334def test_session_using_samesite_attribute(app, client):335 @app.route("/")336 def index():337 flask.session["testing"] = 42338 return "Hello World"339340 app.config.update(SESSION_COOKIE_SAMESITE="invalid")341342 with pytest.raises(ValueError):343 client.get("/")344345 app.config.update(SESSION_COOKIE_SAMESITE=None)346 rv = client.get("/")347 cookie = rv.headers["set-cookie"].lower()348 assert "samesite" not in cookie349350 app.config.update(SESSION_COOKIE_SAMESITE="Strict")351 rv = client.get("/")352 cookie = rv.headers["set-cookie"].lower()353 assert "samesite=strict" in cookie354355 app.config.update(SESSION_COOKIE_SAMESITE="Lax")356 rv = client.get("/")357 cookie = rv.headers["set-cookie"].lower()358 assert "samesite=lax" in cookie359360361def test_session_localhost_warning(recwarn, app, client):362 app.config.update(SERVER_NAME="localhost:5000")363364 @app.route("/")365 def index():366 flask.session["testing"] = 42367 return "testing"368369 rv = client.get("/", "http://localhost:5000/")370 assert "domain" not in rv.headers["set-cookie"].lower()371 w = recwarn.pop(UserWarning)372 assert '"localhost" is not a valid cookie domain' in str(w.message)373374375def test_session_ip_warning(recwarn, app, client):376 app.config.update(SERVER_NAME="127.0.0.1:5000")377378 @app.route("/")379 def index():380 flask.session["testing"] = 42381 return "testing"382383 rv = client.get("/", "http://127.0.0.1:5000/")384 assert "domain=127.0.0.1" in rv.headers["set-cookie"].lower()385 w = recwarn.pop(UserWarning)386 assert "cookie domain is an IP" in str(w.message)387388389def test_missing_session(app):390 app.secret_key = None391392 def expect_exception(f, *args, **kwargs):393 e = pytest.raises(RuntimeError, f, *args, **kwargs)394 assert e.value.args and "session is unavailable" in e.value.args[0]395396 with app.test_request_context():397 assert flask.session.get("missing_key") is None398 expect_exception(flask.session.__setitem__, "foo", 42)399 expect_exception(flask.session.pop, "foo")400401402def test_session_expiration(app, client):403 permanent = True404405 @app.route("/")406 def index():407 flask.session["test"] = 42408 flask.session.permanent = permanent409 return ""410411 @app.route("/test")412 def test():413 return text_type(flask.session.permanent)414415 rv = client.get("/")416 assert "set-cookie" in rv.headers417 match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])418 expires = parse_date(match.group())419 expected = datetime.utcnow() + app.permanent_session_lifetime420 assert expires.year == expected.year421 assert expires.month == expected.month422 assert expires.day == expected.day423424 rv = client.get("/test")425 assert rv.data == b"True"426427 permanent = False428 rv = client.get("/")429 assert "set-cookie" in rv.headers430 match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])431 assert match is None432433434def test_session_stored_last(app, client):435 @app.after_request436 def modify_session(response):437 flask.session["foo"] = 42438 return response439440 @app.route("/")441 def dump_session_contents():442 return repr(flask.session.get("foo"))443444 assert client.get("/").data == b"None"445 assert client.get("/").data == b"42"446447448def test_session_special_types(app, client):449 now = datetime.utcnow().replace(microsecond=0)450 the_uuid = uuid.uuid4()451452 @app.route("/")453 def dump_session_contents():454 flask.session["t"] = (1, 2, 3)455 flask.session["b"] = b"\xff"456 flask.session["m"] = flask.Markup("<html>")457 flask.session["u"] = the_uuid458 flask.session["d"] = now459 flask.session["t_tag"] = {" t": "not-a-tuple"}460 flask.session["di_t_tag"] = {" t__": "not-a-tuple"}461 flask.session["di_tag"] = {" di": "not-a-dict"}462 return "", 204463464 with client:465 client.get("/")466 s = flask.session467 assert s["t"] == (1, 2, 3)468 assert type(s["b"]) == bytes469 assert s["b"] == b"\xff"470 assert type(s["m"]) == flask.Markup471 assert s["m"] == flask.Markup("<html>")472 assert s["u"] == the_uuid473 assert s["d"] == now474 assert s["t_tag"] == {" t": "not-a-tuple"}475 assert s["di_t_tag"] == {" t__": "not-a-tuple"}476 assert s["di_tag"] == {" di": "not-a-dict"}477478479def test_session_cookie_setting(app):480 is_permanent = True481482 @app.route("/bump")483 def bump():484 rv = flask.session["foo"] = flask.session.get("foo", 0) + 1485 flask.session.permanent = is_permanent486 return str(rv)487488 @app.route("/read")489 def read():490 return str(flask.session.get("foo", 0))491492 def run_test(expect_header):493 with app.test_client() as c:494 assert c.get("/bump").data == b"1"495 assert c.get("/bump").data == b"2"496 assert c.get("/bump").data == b"3"497498 rv = c.get("/read")499 set_cookie = rv.headers.get("set-cookie")500 assert (set_cookie is not None) == expect_header501 assert rv.data == b"3"502503 is_permanent = True504 app.config["SESSION_REFRESH_EACH_REQUEST"] = True505 run_test(expect_header=True)506507 is_permanent = True508 app.config["SESSION_REFRESH_EACH_REQUEST"] = False509 run_test(expect_header=False)510511 is_permanent = False512 app.config["SESSION_REFRESH_EACH_REQUEST"] = True513 run_test(expect_header=False)514515 is_permanent = False516 app.config["SESSION_REFRESH_EACH_REQUEST"] = False517 run_test(expect_header=False)518519520def test_session_vary_cookie(app, client):521 @app.route("/set")522 def set_session():523 flask.session["test"] = "test"524 return ""525526 @app.route("/get")527 def get():528 return flask.session.get("test")529530 @app.route("/getitem")531 def getitem():532 return flask.session["test"]533534 @app.route("/setdefault")535 def setdefault():536 return flask.session.setdefault("test", "default")537538 @app.route("/vary-cookie-header-set")539 def vary_cookie_header_set():540 response = flask.Response()541 response.vary.add("Cookie")542 flask.session["test"] = "test"543 return response544545 @app.route("/vary-header-set")546 def vary_header_set():547 response = flask.Response()548 response.vary.update(("Accept-Encoding", "Accept-Language"))549 flask.session["test"] = "test"550 return response551552 @app.route("/no-vary-header")553 def no_vary_header():554 return ""555556 def expect(path, header_value="Cookie"):557 rv = client.get(path)558559 if header_value:560 # The 'Vary' key should exist in the headers only once.561 assert len(rv.headers.get_all("Vary")) == 1562 assert rv.headers["Vary"] == header_value563 else:564 assert "Vary" not in rv.headers565566 expect("/set")567 expect("/get")568 expect("/getitem")569 expect("/setdefault")570 expect("/vary-cookie-header-set")571 expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")572 expect("/no-vary-header", None)573574575def test_flashes(app, req_ctx):576 assert not flask.session.modified577 flask.flash("Zap")578 flask.session.modified = False579 flask.flash("Zip")580 assert flask.session.modified581 assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]582583584def test_extended_flashing(app):585 # Be sure app.testing=True below, else tests can fail silently.586 #587 # Specifically, if app.testing is not set to True, the AssertionErrors588 # in the view functions will cause a 500 response to the test client589 # instead of propagating exceptions.590591 @app.route("/")592 def index():593 flask.flash(u"Hello World")594 flask.flash(u"Hello World", "error")595 flask.flash(flask.Markup(u"<em>Testing</em>"), "warning")596 return ""597598 @app.route("/test/")599 def test():600 messages = flask.get_flashed_messages()601 assert list(messages) == [602 u"Hello World",603 u"Hello World",604 flask.Markup(u"<em>Testing</em>"),605 ]606 return ""607608 @app.route("/test_with_categories/")609 def test_with_categories():610 messages = flask.get_flashed_messages(with_categories=True)611 assert len(messages) == 3612 assert list(messages) == [613 ("message", u"Hello World"),614 ("error", u"Hello World"),615 ("warning", flask.Markup(u"<em>Testing</em>")),616 ]617 return ""618619 @app.route("/test_filter/")620 def test_filter():621 messages = flask.get_flashed_messages(622 category_filter=["message"], with_categories=True623 )624 assert list(messages) == [("message", u"Hello World")]625 return ""626627 @app.route("/test_filters/")628 def test_filters():629 messages = flask.get_flashed_messages(630 category_filter=["message", "warning"], with_categories=True631 )632 assert list(messages) == [633 ("message", u"Hello World"),634 ("warning", flask.Markup(u"<em>Testing</em>")),635 ]636 return ""637638 @app.route("/test_filters_without_returning_categories/")639 def test_filters2():640 messages = flask.get_flashed_messages(category_filter=["message", "warning"])641 assert len(messages) == 2642 assert messages[0] == u"Hello World"643 assert messages[1] == flask.Markup(u"<em>Testing</em>")644 return ""645646 # Create new test client on each test to clean flashed messages.647648 client = app.test_client()649 client.get("/")650 client.get("/test_with_categories/")651652 client = app.test_client()653 client.get("/")654 client.get("/test_filter/")655656 client = app.test_client()657 client.get("/")658 client.get("/test_filters/")659660 client = app.test_client()661 client.get("/")662 client.get("/test_filters_without_returning_categories/")663664665def test_request_processing(app, client):666 evts = []667668 @app.before_request669 def before_request():670 evts.append("before")671672 @app.after_request673 def after_request(response):674 response.data += b"|after"675 evts.append("after")676 return response677678 @app.route("/")679 def index():680 assert "before" in evts681 assert "after" not in evts682 return "request"683684 assert "after" not in evts685 rv = client.get("/").data686 assert "after" in evts687 assert rv == b"request|after"688689690def test_request_preprocessing_early_return(app, client):691 evts = []692693 @app.before_request694 def before_request1():695 evts.append(1)696697 @app.before_request698 def before_request2():699 evts.append(2)700 return "hello"701702 @app.before_request703 def before_request3():704 evts.append(3)705 return "bye"706707 @app.route("/")708 def index():709 evts.append("index")710 return "damnit"711712 rv = client.get("/").data.strip()713 assert rv == b"hello"714 assert evts == [1, 2]715716717def test_after_request_processing(app, client):718 @app.route("/")719 def index():720 @flask.after_this_request721 def foo(response):722 response.headers["X-Foo"] = "a header"723 return response724725 return "Test"726727 resp = client.get("/")728 assert resp.status_code == 200729 assert resp.headers["X-Foo"] == "a header"730731732def test_teardown_request_handler(app, client):733 called = []734735 @app.teardown_request736 def teardown_request(exc):737 called.append(True)738 return "Ignored"739740 @app.route("/")741 def root():742 return "Response"743744 rv = client.get("/")745 assert rv.status_code == 200746 assert b"Response" in rv.data747 assert len(called) == 1748749750def test_teardown_request_handler_debug_mode(app, client):751 called = []752753 @app.teardown_request754 def teardown_request(exc):755 called.append(True)756 return "Ignored"757758 @app.route("/")759 def root():760 return "Response"761762 rv = client.get("/")763 assert rv.status_code == 200764 assert b"Response" in rv.data765 assert len(called) == 1766767768def test_teardown_request_handler_error(app, client):769 called = []770 app.testing = False771772 @app.teardown_request773 def teardown_request1(exc):774 assert type(exc) == ZeroDivisionError775 called.append(True)776 # This raises a new error and blows away sys.exc_info(), so we can777 # test that all teardown_requests get passed the same original778 # exception.779 try:780 raise TypeError()781 except:782 pass783784 @app.teardown_request785 def teardown_request2(exc):786 assert type(exc) == ZeroDivisionError787 called.append(True)788 # This raises a new error and blows away sys.exc_info(), so we can789 # test that all teardown_requests get passed the same original790 # exception.791 try:792 raise TypeError()793 except:794 pass795796 @app.route("/")797 def fails():798 1 // 0799800 rv = client.get("/")801 assert rv.status_code == 500802 assert b"Internal Server Error" in rv.data803 assert len(called) == 2804805806def test_before_after_request_order(app, client):807 called = []808809 @app.before_request810 def before1():811 called.append(1)812813 @app.before_request814 def before2():815 called.append(2)816817 @app.after_request818 def after1(response):819 called.append(4)820 return response821822 @app.after_request823 def after2(response):824 called.append(3)825 return response826827 @app.teardown_request828 def finish1(exc):829 called.append(6)830831 @app.teardown_request832 def finish2(exc):833 called.append(5)834835 @app.route("/")836 def index():837 return "42"838839 rv = client.get("/")840 assert rv.data == b"42"841 assert called == [1, 2, 3, 4, 5, 6]842843844def test_error_handling(app, client):845 app.testing = False846847 @app.errorhandler(404)848 def not_found(e):849 return "not found", 404850851 @app.errorhandler(500)852 def internal_server_error(e):853 return "internal server error", 500854855 @app.errorhandler(Forbidden)856 def forbidden(e):857 return "forbidden", 403858859 @app.route("/")860 def index():861 flask.abort(404)862863 @app.route("/error")864 def error():865 1 // 0866867 @app.route("/forbidden")868 def error2():869 flask.abort(403)870871 rv = client.get("/")872 assert rv.status_code == 404873 assert rv.data == b"not found"874 rv = client.get("/error")875 assert rv.status_code == 500876 assert b"internal server error" == rv.data877 rv = client.get("/forbidden")878 assert rv.status_code == 403879 assert b"forbidden" == rv.data880881882def test_error_handler_unknown_code(app):883 with pytest.raises(KeyError) as exc_info:884 app.register_error_handler(999, lambda e: ("999", 999))885886 assert "Use a subclass" in exc_info.value.args[0]887888889def test_error_handling_processing(app, client):890 app.testing = False891892 @app.errorhandler(500)893 def internal_server_error(e):894 return "internal server error", 500895896 @app.route("/")897 def broken_func():898 1 // 0899900 @app.after_request901 def after_request(resp):902 resp.mimetype = "text/x-special"903 return resp904905 resp = client.get("/")906 assert resp.mimetype == "text/x-special"907 assert resp.data == b"internal server error"908909910def test_baseexception_error_handling(app, client):911 app.testing = False912913 @app.route("/")914 def broken_func():915 raise KeyboardInterrupt()916917 with pytest.raises(KeyboardInterrupt):918 client.get("/")919920 ctx = flask._request_ctx_stack.top921 assert ctx.preserved922 assert type(ctx._preserved_exc) is KeyboardInterrupt923924925def test_before_request_and_routing_errors(app, client):926 @app.before_request927 def attach_something():928 flask.g.something = "value"929930 @app.errorhandler(404)931 def return_something(error):932 return flask.g.something, 404933934 rv = client.get("/")935 assert rv.status_code == 404936 assert rv.data == b"value"937938939def test_user_error_handling(app, client):940 class MyException(Exception):941 pass942943 @app.errorhandler(MyException)944 def handle_my_exception(e):945 assert isinstance(e, MyException)946 return "42"947948 @app.route("/")949 def index():950 raise MyException()951952 assert client.get("/").data == b"42"953954955def test_http_error_subclass_handling(app, client):956 class ForbiddenSubclass(Forbidden):957 pass958959 @app.errorhandler(ForbiddenSubclass)960 def handle_forbidden_subclass(e):961 assert isinstance(e, ForbiddenSubclass)962 return "banana"963964 @app.errorhandler(403)965 def handle_forbidden_subclass(e):966 assert not isinstance(e, ForbiddenSubclass)967 assert isinstance(e, Forbidden)968 return "apple"969970 @app.route("/1")971 def index1():972 raise ForbiddenSubclass()973974 @app.route("/2")975 def index2():976 flask.abort(403)977978 @app.route("/3")979 def index3():980 raise Forbidden()981982 assert client.get("/1").data == b"banana"983 assert client.get("/2").data == b"apple"984 assert client.get("/3").data == b"apple"985986987def test_errorhandler_precedence(app, client):988 class E1(Exception):989 pass990991 class E2(Exception):992 pass993994 class E3(E1, E2):995 pass996997 @app.errorhandler(E2)998 def handle_e2(e):999 return "E2"10001001 @app.errorhandler(Exception)1002 def handle_exception(e):1003 return "Exception"10041005 @app.route("/E1")1006 def raise_e1():1007 raise E110081009 @app.route("/E3")1010 def raise_e3():1011 raise E310121013 rv = client.get("/E1")1014 assert rv.data == b"Exception"10151016 rv = client.get("/E3")1017 assert rv.data == b"E2"101810191020def test_trapping_of_bad_request_key_errors(app, client):1021 @app.route("/key")1022 def fail():1023 flask.request.form["missing_key"]10241025 @app.route("/abort")1026 def allow_abort():1027 flask.abort(400)10281029 rv = client.get("/key")1030 assert rv.status_code == 4001031 assert b"missing_key" not in rv.data1032 rv = client.get("/abort")1033 assert rv.status_code == 40010341035 app.debug = True1036 with pytest.raises(KeyError) as e:1037 client.get("/key")1038 assert e.errisinstance(BadRequest)1039 assert "missing_key" in e.value.get_description()1040 rv = client.get("/abort")1041 assert rv.status_code == 40010421043 app.debug = False1044 app.config["TRAP_BAD_REQUEST_ERRORS"] = True1045 with pytest.raises(KeyError):1046 client.get("/key")1047 with pytest.raises(BadRequest):1048 client.get("/abort")104910501051def test_trapping_of_all_http_exceptions(app, client):1052 app.config["TRAP_HTTP_EXCEPTIONS"] = True10531054 @app.route("/fail")1055 def fail():1056 flask.abort(404)10571058 with pytest.raises(NotFound):1059 client.get("/fail")106010611062def test_error_handler_after_processor_error(app, client):1063 app.testing = False10641065 @app.before_request1066 def before_request():1067 if trigger == "before":1068 1 // 010691070 @app.after_request1071 def after_request(response):1072 if trigger == "after":1073 1 // 01074 return response10751076 @app.route("/")1077 def index():1078 return "Foo"10791080 @app.errorhandler(500)1081 def internal_server_error(e):1082 return "Hello Server Error", 50010831084 for trigger in "before", "after":1085 rv = client.get("/")1086 assert rv.status_code == 5001087 assert rv.data == b"Hello Server Error"108810891090def test_enctype_debug_helper(app, client):1091 from flask.debughelpers import DebugFilesKeyError10921093 app.debug = True10941095 @app.route("/fail", methods=["POST"])1096 def index():1097 return flask.request.files["foo"].filename10981099 # with statement is important because we leave an exception on the1100 # stack otherwise and we want to ensure that this is not the case1101 # to not negatively affect other tests.1102 with client:1103 with pytest.raises(DebugFilesKeyError) as e:1104 client.post("/fail", data={"foo": "index.txt"})1105 assert "no file contents were transmitted" in str(e.value)1106 assert 'This was submitted: "index.txt"' in str(e.value)110711081109def test_response_types(app, client):1110 @app.route("/text")1111 def from_text():1112 return u"Hällo Wörld"11131114 @app.route("/bytes")1115 def from_bytes():1116 return u"Hällo Wörld".encode("utf-8")11171118 @app.route("/full_tuple")1119 def from_full_tuple():1120 return (1121 "Meh",1122 400,1123 {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1124 )11251126 @app.route("/text_headers")1127 def from_text_headers():1128 return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}11291130 @app.route("/text_status")1131 def from_text_status():1132 return "Hi, status!", 40011331134 @app.route("/response_headers")1135 def from_response_headers():1136 return (1137 flask.Response("Hello world", 404, {"X-Foo": "Baz"}),1138 {"X-Foo": "Bar", "X-Bar": "Foo"},1139 )11401141 @app.route("/response_status")1142 def from_response_status():1143 return app.response_class("Hello world", 400), 50011441145 @app.route("/wsgi")1146 def from_wsgi():1147 return NotFound()11481149 assert client.get("/text").data == u"Hällo Wörld".encode("utf-8")1150 assert client.get("/bytes").data == u"Hällo Wörld".encode("utf-8")11511152 rv = client.get("/full_tuple")1153 assert rv.data == b"Meh"1154 assert rv.headers["X-Foo"] == "Testing"1155 assert rv.status_code == 4001156 assert rv.mimetype == "text/plain"11571158 rv = client.get("/text_headers")1159 assert rv.data == b"Hello"1160 assert rv.headers["X-Foo"] == "Test"1161 assert rv.status_code == 2001162 assert rv.mimetype == "text/plain"11631164 rv = client.get("/text_status")1165 assert rv.data == b"Hi, status!"1166 assert rv.status_code == 4001167 assert rv.mimetype == "text/html"11681169 rv = client.get("/response_headers")1170 assert rv.data == b"Hello world"1171 assert rv.headers.getlist("X-Foo") == ["Baz", "Bar"]1172 assert rv.headers["X-Bar"] == "Foo"1173 assert rv.status_code == 40411741175 rv = client.get("/response_status")1176 assert rv.data == b"Hello world"1177 assert rv.status_code == 50011781179 rv = client.get("/wsgi")1180 assert b"Not Found" in rv.data1181 assert rv.status_code == 404118211831184def test_response_type_errors():1185 app = flask.Flask(__name__)1186 app.testing = True11871188 @app.route("/none")1189 def from_none():1190 pass11911192 @app.route("/small_tuple")1193 def from_small_tuple():1194 return ("Hello",)11951196 @app.route("/large_tuple")1197 def from_large_tuple():1198 return "Hello", 234, {"X-Foo": "Bar"}, "???"11991200 @app.route("/bad_type")1201 def from_bad_type():1202 return True12031204 @app.route("/bad_wsgi")1205 def from_bad_wsgi():1206 return lambda: None12071208 c = app.test_client()12091210 with pytest.raises(TypeError) as e:1211 c.get("/none")1212 assert "returned None" in str(e)12131214 with pytest.raises(TypeError) as e:1215 c.get("/small_tuple")1216 assert "tuple must have the form" in str(e)12171218 pytest.raises(TypeError, c.get, "/large_tuple")12191220 with pytest.raises(TypeError) as e:1221 c.get("/bad_type")1222 assert "it was a bool" in str(e)12231224 pytest.raises(TypeError, c.get, "/bad_wsgi")122512261227def test_make_response(app, req_ctx):1228 rv = flask.make_response()1229 assert rv.status_code == 2001230 assert rv.data == b""1231 assert rv.mimetype == "text/html"12321233 rv = flask.make_response("Awesome")1234 assert rv.status_code == 2001235 assert rv.data == b"Awesome"1236 assert rv.mimetype == "text/html"12371238 rv = flask.make_response("W00t", 404)1239 assert rv.status_code == 4041240 assert rv.data == b"W00t"1241 assert rv.mimetype == "text/html"124212431244def test_make_response_with_response_instance(app, req_ctx):1245 rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1246 assert rv.status_code == 4001247 assert rv.data == b'{"msg":"W00t"}\n'1248 assert rv.mimetype == "application/json"12491250 rv = flask.make_response(flask.Response(""), 400)1251 assert rv.status_code == 4001252 assert rv.data == b""1253 assert rv.mimetype == "text/html"12541255 rv = flask.make_response(1256 flask.Response("", headers={"Content-Type": "text/html"}),1257 400,1258 [("X-Foo", "bar")],1259 )1260 assert rv.status_code == 4001261 assert rv.headers["Content-Type"] == "text/html"1262 assert rv.headers["X-Foo"] == "bar"126312641265def test_jsonify_no_prettyprint(app, req_ctx):1266 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1267 compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1268 uncompressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}12691270 rv = flask.make_response(flask.jsonify(uncompressed_msg), 200)1271 assert rv.data == compressed_msg127212731274def test_jsonify_prettyprint(app, req_ctx):1275 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1276 compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1277 pretty_response = (1278 b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'1279 )12801281 rv = flask.make_response(flask.jsonify(compressed_msg), 200)1282 assert rv.data == pretty_response128312841285def test_jsonify_mimetype(app, req_ctx):1286 app.config.update({"JSONIFY_MIMETYPE": "application/vnd.api+json"})1287 msg = {"msg": {"submsg": "W00t"}}1288 rv = flask.make_response(flask.jsonify(msg), 200)1289 assert rv.mimetype == "application/vnd.api+json"129012911292def test_jsonify_args_and_kwargs_check(app, req_ctx):1293 with pytest.raises(TypeError) as e:1294 flask.jsonify("fake args", kwargs="fake")1295 assert "behavior undefined" in str(e.value)129612971298def test_url_generation(app, req_ctx):1299 @app.route("/hello/<name>", methods=["POST"])1300 def hello():1301 pass13021303 assert flask.url_for("hello", name="test x") == "/hello/test%20x"1304 assert (1305 flask.url_for("hello", name="test x", _external=True)1306 == "http://localhost/hello/test%20x"1307 )130813091310def test_build_error_handler(app):1311 # Test base case, a URL which results in a BuildError.1312 with app.test_request_context():1313 pytest.raises(BuildError, flask.url_for, "spam")13141315 # Verify the error is re-raised if not the current exception.1316 try:1317 with app.test_request_context():1318 flask.url_for("spam")1319 except BuildError as err:1320 error = err1321 try:1322 raise RuntimeError("Test case where BuildError is not current.")1323 except RuntimeError:1324 pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})13251326 # Test a custom handler.1327 def handler(error, endpoint, values):1328 # Just a test.1329 return "/test_handler/"13301331 app.url_build_error_handlers.append(handler)1332 with app.test_request_context():1333 assert flask.url_for("spam") == "/test_handler/"133413351336def test_build_error_handler_reraise(app):1337 # Test a custom handler which reraises the BuildError1338 def handler_raises_build_error(error, endpoint, values):1339 raise error13401341 app.url_build_error_handlers.append(handler_raises_build_error)13421343 with app.test_request_context():1344 pytest.raises(BuildError, flask.url_for, "not.existing")134513461347def test_url_for_passes_special_values_to_build_error_handler(app):1348 @app.url_build_error_handlers.append1349 def handler(error, endpoint, values):1350 assert values == {1351 "_external": False,1352 "_anchor": None,1353 "_method": None,1354 "_scheme": None,1355 }1356 return "handled"13571358 with app.test_request_context():1359 flask.url_for("/")136013611362def test_custom_converters(app, client):1363 from werkzeug.routing import BaseConverter13641365 class ListConverter(BaseConverter):1366 def to_python(self, value):1367 return value.split(",")13681369 def to_url(self, value):1370 base_to_url = super(ListConverter, self).to_url1371 return ",".join(base_to_url(x) for x in value)13721373 app.url_map.converters["list"] = ListConverter13741375 @app.route("/<list:args>")1376 def index(args):1377 return "|".join(args)13781379 assert client.get("/1,2,3").data == b"1|2|3"138013811382def test_static_files(app, client):1383 rv = client.get("/static/index.html")1384 assert rv.status_code == 2001385 assert rv.data.strip() == b"<h1>Hello World!</h1>"1386 with app.test_request_context():1387 assert flask.url_for("static", filename="index.html") == "/static/index.html"1388 rv.close()138913901391def test_static_url_path():1392 app = flask.Flask(__name__, static_url_path="/foo")1393 app.testing = True1394 rv = app.test_client().get("/foo/index.html")1395 assert rv.status_code == 2001396 rv.close()13971398 with app.test_request_context():1399 assert flask.url_for("static", filename="index.html") == "/foo/index.html"140014011402def test_static_route_with_host_matching():1403 app = flask.Flask(__name__, host_matching=True, static_host="example.com")1404 c = app.test_client()1405 rv = c.get("http://example.com/static/index.html")1406 assert rv.status_code == 2001407 rv.close()1408 with app.test_request_context():1409 rv = flask.url_for("static", filename="index.html", _external=True)1410 assert rv == "http://example.com/static/index.html"1411 # Providing static_host without host_matching=True should error.1412 with pytest.raises(Exception):1413 flask.Flask(__name__, static_host="example.com")1414 # Providing host_matching=True with static_folder but without static_host should error.1415 with pytest.raises(Exception):1416 flask.Flask(__name__, host_matching=True)1417 # Providing host_matching=True without static_host but with static_folder=None should not error.1418 flask.Flask(__name__, host_matching=True, static_folder=None)141914201421def test_request_locals():1422 assert repr(flask.g) == "<LocalProxy unbound>"1423 assert not flask.g142414251426def test_test_app_proper_environ():1427 app = flask.Flask(__name__, subdomain_matching=True)1428 app.config.update(SERVER_NAME="localhost.localdomain:5000")1429 client = app.test_client()14301431 @app.route("/")1432 def index():1433 return "Foo"14341435 @app.route("/", subdomain="foo")1436 def subdomain():1437 return "Foo SubDomain"14381439 rv = client.get("/")1440 assert rv.data == b"Foo"14411442 rv = client.get("/", "http://localhost.localdomain:5000")1443 assert rv.data == b"Foo"14441445 rv = client.get("/", "https://localhost.localdomain:5000")1446 assert rv.data == b"Foo"14471448 app.config.update(SERVER_NAME="localhost.localdomain")1449 rv = client.get("/", "https://localhost.localdomain")1450 assert rv.data == b"Foo"14511452 try:1453 app.config.update(SERVER_NAME="localhost.localdomain:443")1454 rv = client.get("/", "https://localhost.localdomain")1455 # Werkzeug 0.81456 assert rv.status_code == 4041457 except ValueError as e:1458 # Werkzeug 0.71459 assert str(e) == (1460 "the server name provided "1461 "('localhost.localdomain:443') does not match the "1462 "server name from the WSGI environment ('localhost.localdomain')"1463 )14641465 try:1466 app.config.update(SERVER_NAME="localhost.localdomain")1467 rv = client.get("/", "http://foo.localhost")1468 # Werkzeug 0.81469 assert rv.status_code == 4041470 except ValueError as e:1471 # Werkzeug 0.71472 assert str(e) == (1473 "the server name provided "1474 "('localhost.localdomain') does not match the "1475 "server name from the WSGI environment ('foo.localhost')"1476 )14771478 rv = client.get("/", "http://foo.localhost.localdomain")1479 assert rv.data == b"Foo SubDomain"148014811482def test_exception_propagation(app, client):1483 def apprunner(config_key):1484 @app.route("/")1485 def index():1486 1 // 014871488 if config_key is not None:1489 app.config[config_key] = True1490 with pytest.raises(Exception):1491 client.get("/")1492 else:1493 assert client.get("/").status_code == 50014941495 # we have to run this test in an isolated thread because if the1496 # debug flag is set to true and an exception happens the context is1497 # not torn down. This causes other tests that run after this fail1498 # when they expect no exception on the stack.1499 for config_key in "TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None:1500 t = Thread(target=apprunner, args=(config_key,))1501 t.start()1502 t.join()150315041505@pytest.mark.parametrize("debug", [True, False])1506@pytest.mark.parametrize("use_debugger", [True, False])1507@pytest.mark.parametrize("use_reloader", [True, False])1508@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1509def test_werkzeug_passthrough_errors(1510 monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1511):1512 rv = {}15131514 # Mocks werkzeug.serving.run_simple method1515 def run_simple_mock(*args, **kwargs):1516 rv["passthrough_errors"] = kwargs.get("passthrough_errors")15171518 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1519 app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1520 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)152115221523def test_max_content_length(app, client):1524 app.config["MAX_CONTENT_LENGTH"] = 6415251526 @app.before_request1527 def always_first():1528 flask.request.form["myfile"]1529 assert False15301531 @app.route("/accept", methods=["POST"])1532 def accept_file():1533 flask.request.form["myfile"]1534 assert False15351536 @app.errorhandler(413)1537 def catcher(error):1538 return "42"15391540 rv = client.post("/accept", data={"myfile": "foo" * 100})1541 assert rv.data == b"42"154215431544def test_url_processors(app, client):1545 @app.url_defaults1546 def add_language_code(endpoint, values):1547 if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1548 endpoint, "lang_code"1549 ):1550 values.setdefault("lang_code", flask.g.lang_code)15511552 @app.url_value_preprocessor1553 def pull_lang_code(endpoint, values):1554 flask.g.lang_code = values.pop("lang_code", None)15551556 @app.route("/<lang_code>/")1557 def index():1558 return flask.url_for("about")15591560 @app.route("/<lang_code>/about")1561 def about():1562 return flask.url_for("something_else")15631564 @app.route("/foo")1565 def something_else():1566 return flask.url_for("about", lang_code="en")15671568 assert client.get("/de/").data == b"/de/about"1569 assert client.get("/de/about").data == b"/foo"1570 assert client.get("/foo").data == b"/en/about"157115721573def test_inject_blueprint_url_defaults(app):1574 bp = flask.Blueprint("foo.bar.baz", __name__, template_folder="template")15751576 @bp.url_defaults1577 def bp_defaults(endpoint, values):1578 values["page"] = "login"15791580 @bp.route("/<page>")1581 def view(page):1582 pass15831584 app.register_blueprint(bp)15851586 values = dict()1587 app.inject_url_defaults("foo.bar.baz.view", values)1588 expected = dict(page="login")1589 assert values == expected15901591 with app.test_request_context("/somepage"):1592 url = flask.url_for("foo.bar.baz.view")1593 expected = "/login"1594 assert url == expected159515961597def test_nonascii_pathinfo(app, client):1598 @app.route(u"/киртест")1599 def index():1600 return "Hello World!"16011602 rv = client.get(u"/киртест")1603 assert rv.data == b"Hello World!"160416051606def test_debug_mode_complains_after_first_request(app, client):1607 app.debug = True16081609 @app.route("/")1610 def index():1611 return "Awesome"16121613 assert not app.got_first_request1614 assert client.get("/").data == b"Awesome"1615 with pytest.raises(AssertionError) as e:16161617 @app.route("/foo")1618 def broken():1619 return "Meh"16201621 assert "A setup function was called" in str(e)16221623 app.debug = False16241625 @app.route("/foo")1626 def working():1627 return "Meh"16281629 assert client.get("/foo").data == b"Meh"1630 assert app.got_first_request163116321633def test_before_first_request_functions(app, client):1634 got = []16351636 @app.before_first_request1637 def foo():1638 got.append(42)16391640 client.get("/")1641 assert got == [42]1642 client.get("/")1643 assert got == [42]1644 assert app.got_first_request164516461647def test_before_first_request_functions_concurrent(app, client):1648 got = []16491650 @app.before_first_request1651 def foo():1652 time.sleep(0.2)1653 got.append(42)16541655 def get_and_assert():1656 client.get("/")1657 assert got == [42]16581659 t = Thread(target=get_and_assert)1660 t.start()1661 get_and_assert()1662 t.join()1663 assert app.got_first_request166416651666def test_routing_redirect_debugging(app, client):1667 app.debug = True16681669 @app.route("/foo/", methods=["GET", "POST"])1670 def foo():1671 return "success"16721673 with client:1674 with pytest.raises(AssertionError) as e:1675 client.post("/foo", data={})1676 assert "http://localhost/foo/" in str(e)1677 assert ("Make sure to directly send " "your POST-request to this URL") in str(e)16781679 rv = client.get("/foo", data={}, follow_redirects=True)1680 assert rv.data == b"success"16811682 app.debug = False1683 with client:1684 rv = client.post("/foo", data={}, follow_redirects=True)1685 assert rv.data == b"success"168616871688def test_route_decorator_custom_endpoint(app, client):1689 app.debug = True16901691 @app.route("/foo/")1692 def foo():1693 return flask.request.endpoint16941695 @app.route("/bar/", endpoint="bar")1696 def for_bar():1697 return flask.request.endpoint16981699 @app.route("/bar/123", endpoint="123")1700 def for_bar_foo():1701 return flask.request.endpoint17021703 with app.test_request_context():1704 assert flask.url_for("foo") == "/foo/"1705 assert flask.url_for("bar") == "/bar/"1706 assert flask.url_for("123") == "/bar/123"17071708 assert client.get("/foo/").data == b"foo"1709 assert client.get("/bar/").data == b"bar"1710 assert client.get("/bar/123").data == b"123"171117121713def test_preserve_only_once(app, client):1714 app.debug = True17151716 @app.route("/fail")1717 def fail_func():1718 1 // 017191720 for x in range(3):1721 with pytest.raises(ZeroDivisionError):1722 client.get("/fail")17231724 assert flask._request_ctx_stack.top is not None1725 assert flask._app_ctx_stack.top is not None1726 # implicit appctx disappears too1727 flask._request_ctx_stack.top.pop()1728 assert flask._request_ctx_stack.top is None1729 assert flask._app_ctx_stack.top is None173017311732def test_preserve_remembers_exception(app, client):1733 app.debug = True1734 errors = []17351736 @app.route("/fail")1737 def fail_func():1738 1 // 017391740 @app.route("/success")1741 def success_func():1742 return "Okay"17431744 @app.teardown_request1745 def teardown_handler(exc):1746 errors.append(exc)17471748 # After this failure we did not yet call the teardown handler1749 with pytest.raises(ZeroDivisionError):1750 client.get("/fail")1751 assert errors == []17521753 # But this request triggers it, and it's an error1754 client.get("/success")1755 assert len(errors) == 21756 assert isinstance(errors[0], ZeroDivisionError)17571758 # At this point another request does nothing.1759 client.get("/success")1760 assert len(errors) == 31761 assert errors[1] is None176217631764def test_get_method_on_g(app_ctx):1765 assert flask.g.get("x") is None1766 assert flask.g.get("x", 11) == 111767 flask.g.x = 421768 assert flask.g.get("x") == 421769 assert flask.g.x == 42177017711772def test_g_iteration_protocol(app_ctx):1773 flask.g.foo = 231774 flask.g.bar = 421775 assert "foo" in flask.g1776 assert "foos" not in flask.g1777 assert sorted(flask.g) == ["bar", "foo"]177817791780def test_subdomain_basic_support():1781 app = flask.Flask(__name__, subdomain_matching=True)1782 app.config["SERVER_NAME"] = "localhost.localdomain"1783 client = app.test_client()17841785 @app.route("/")1786 def normal_index():1787 return "normal index"17881789 @app.route("/", subdomain="test")1790 def test_index():1791 return "test index"17921793 rv = client.get("/", "http://localhost.localdomain/")1794 assert rv.data == b"normal index"17951796 rv = client.get("/", "http://test.localhost.localdomain/")1797 assert rv.data == b"test index"179817991800def test_subdomain_matching():1801 app = flask.Flask(__name__, subdomain_matching=True)1802 client = app.test_client()1803 app.config["SERVER_NAME"] = "localhost.localdomain"18041805 @app.route("/", subdomain="<user>")1806 def index(user):1807 return "index for %s" % user18081809 rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1810 assert rv.data == b"index for mitsuhiko"181118121813def test_subdomain_matching_with_ports():1814 app = flask.Flask(__name__, subdomain_matching=True)1815 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1816 client = app.test_client()18171818 @app.route("/", subdomain="<user>")1819 def index(user):1820 return "index for %s" % user18211822 rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1823 assert rv.data == b"index for mitsuhiko"182418251826@pytest.mark.parametrize("matching", (False, True))1827def test_subdomain_matching_other_name(matching):1828 app = flask.Flask(__name__, subdomain_matching=matching)1829 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1830 client = app.test_client()18311832 @app.route("/")1833 def index():1834 return "", 20418351836 # ip address can't match name1837 rv = client.get("/", "http://127.0.0.1:3000/")1838 assert rv.status_code == 404 if matching else 20418391840 # allow all subdomains if matching is disabled1841 rv = client.get("/", "http://www.localhost.localdomain:3000/")1842 assert rv.status_code == 404 if matching else 204184318441845def test_multi_route_rules(app, client):1846 @app.route("/")1847 @app.route("/<test>/")1848 def index(test="a"):1849 return test18501851 rv = client.open("/")1852 assert rv.data == b"a"1853 rv = client.open("/b/")1854 assert rv.data == b"b"185518561857def test_multi_route_class_views(app, client):1858 class View(object):1859 def __init__(self, app):1860 app.add_url_rule("/", "index", self.index)1861 app.add_url_rule("/<test>/", "index", self.index)18621863 def index(self, test="a"):1864 return test18651866 _ = View(app)1867 rv = client.open("/")1868 assert rv.data == b"a"1869 rv = client.open("/b/")1870 assert rv.data == b"b"187118721873def test_run_defaults(monkeypatch, app):1874 rv = {}18751876 # Mocks werkzeug.serving.run_simple method1877 def run_simple_mock(*args, **kwargs):1878 rv["result"] = "running..."18791880 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1881 app.run()1882 assert rv["result"] == "running..."188318841885def test_run_server_port(monkeypatch, app):1886 rv = {}18871888 # Mocks werkzeug.serving.run_simple method1889 def run_simple_mock(hostname, port, application, *args, **kwargs):1890 rv["result"] = "running on %s:%s ..." % (hostname, port)18911892 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1893 hostname, port = "localhost", 80001894 app.run(hostname, port, debug=True)1895 assert rv["result"] == "running on %s:%s ..." % (hostname, port)189618971898@pytest.mark.parametrize(1899 "host,port,expect_host,expect_port",1900 (1901 (None, None, "pocoo.org", 8080),1902 ("localhost", None, "localhost", 8080),1903 (None, 80, "pocoo.org", 80),1904 ("localhost", 80, "localhost", 80),1905 ),1906)1907def test_run_from_config(monkeypatch, host, port, expect_host, expect_port, app):1908 def run_simple_mock(hostname, port, *args, **kwargs):1909 assert hostname == expect_host1910 assert port == expect_port19111912 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1913 app.config["SERVER_NAME"] = "pocoo.org:8080"1914 app.run(host, port)191519161917def test_max_cookie_size(app, client, recwarn):1918 app.config["MAX_COOKIE_SIZE"] = 10019191920 # outside app context, default to Werkzeug static value,1921 # which is also the default config1922 response = flask.Response()1923 default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1924 assert response.max_cookie_size == default19251926 # inside app context, use app config1927 with app.app_context():1928 assert flask.Response().max_cookie_size == 10019291930 @app.route("/")1931 def index():1932 r = flask.Response("", status=204)1933 r.set_cookie("foo", "bar" * 100)1934 return r19351936 client.get("/")1937 assert len(recwarn) == 11938 w = recwarn.pop()1939 assert "cookie is too large" in str(w.message)19401941 app.config["MAX_COOKIE_SIZE"] = 019421943 client.get("/")1944 assert len(recwarn) == 0