test_basic.py
This file
Path
tests/test_basic.py
2,000 lines · 53.7 KiB · Python
Last changed by
Merge pull request #3241 from jon-stumpf/jss-updatesDavid Lordbefore adoption48d0e86
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 sys14import time15import uuid16from datetime import datetime17from threading import Thread1819import pytest20import werkzeug.serving21from werkzeug.exceptions import BadRequest, Forbidden, NotFound22from werkzeug.http import parse_date23from werkzeug.routing import BuildError2425import flask26from flask._compat import text_type272829def test_options_work(app, client):30 @app.route("/", methods=["GET", "POST"])31 def index():32 return "Hello World"3334 rv = client.open("/", method="OPTIONS")35 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]36 assert rv.data == b""373839def test_options_on_multiple_rules(app, client):40 @app.route("/", methods=["GET", "POST"])41 def index():42 return "Hello World"4344 @app.route("/", methods=["PUT"])45 def index_put():46 return "Aha!"4748 rv = client.open("/", method="OPTIONS")49 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST", "PUT"]505152def test_provide_automatic_options_attr():53 app = flask.Flask(__name__)5455 def index():56 return "Hello World!"5758 index.provide_automatic_options = False59 app.route("/")(index)60 rv = app.test_client().open("/", method="OPTIONS")61 assert rv.status_code == 4056263 app = flask.Flask(__name__)6465 def index2():66 return "Hello World!"6768 index2.provide_automatic_options = True69 app.route("/", methods=["OPTIONS"])(index2)70 rv = app.test_client().open("/", method="OPTIONS")71 assert sorted(rv.allow) == ["OPTIONS"]727374def test_provide_automatic_options_kwarg(app, client):75 def index():76 return flask.request.method7778 def more():79 return flask.request.method8081 app.add_url_rule("/", view_func=index, provide_automatic_options=False)82 app.add_url_rule(83 "/more",84 view_func=more,85 methods=["GET", "POST"],86 provide_automatic_options=False,87 )88 assert client.get("/").data == b"GET"8990 rv = client.post("/")91 assert rv.status_code == 40592 assert sorted(rv.allow) == ["GET", "HEAD"]9394 # Older versions of Werkzeug.test.Client don't have an options method95 if hasattr(client, "options"):96 rv = client.options("/")97 else:98 rv = client.open("/", method="OPTIONS")99100 assert rv.status_code == 405101102 rv = client.head("/")103 assert rv.status_code == 200104 assert not rv.data # head truncates105 assert client.post("/more").data == b"POST"106 assert client.get("/more").data == b"GET"107108 rv = client.delete("/more")109 assert rv.status_code == 405110 assert sorted(rv.allow) == ["GET", "HEAD", "POST"]111112 if hasattr(client, "options"):113 rv = client.options("/more")114 else:115 rv = client.open("/more", method="OPTIONS")116117 assert rv.status_code == 405118119120def test_request_dispatching(app, client):121 @app.route("/")122 def index():123 return flask.request.method124125 @app.route("/more", methods=["GET", "POST"])126 def more():127 return flask.request.method128129 assert client.get("/").data == b"GET"130 rv = client.post("/")131 assert rv.status_code == 405132 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]133 rv = client.head("/")134 assert rv.status_code == 200135 assert not rv.data # head truncates136 assert client.post("/more").data == b"POST"137 assert client.get("/more").data == b"GET"138 rv = client.delete("/more")139 assert rv.status_code == 405140 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]141142143def test_disallow_string_for_allowed_methods(app):144 with pytest.raises(TypeError):145146 @app.route("/", methods="GET POST")147 def index():148 return "Hey"149150151def test_url_mapping(app, client):152 random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"153154 def index():155 return flask.request.method156157 def more():158 return flask.request.method159160 def options():161 return random_uuid4162163 app.add_url_rule("/", "index", index)164 app.add_url_rule("/more", "more", more, methods=["GET", "POST"])165166 # Issue 1288: Test that automatic options are not added167 # when non-uppercase 'options' in methods168 app.add_url_rule("/options", "options", options, methods=["options"])169170 assert client.get("/").data == b"GET"171 rv = client.post("/")172 assert rv.status_code == 405173 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]174 rv = client.head("/")175 assert rv.status_code == 200176 assert not rv.data # head truncates177 assert client.post("/more").data == b"POST"178 assert client.get("/more").data == b"GET"179 rv = client.delete("/more")180 assert rv.status_code == 405181 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]182 rv = client.open("/options", method="OPTIONS")183 assert rv.status_code == 200184 assert random_uuid4 in rv.data.decode("utf-8")185186187def test_werkzeug_routing(app, client):188 from werkzeug.routing import Submount, Rule189190 app.url_map.add(191 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])192 )193194 def bar():195 return "bar"196197 def index():198 return "index"199200 app.view_functions["bar"] = bar201 app.view_functions["index"] = index202203 assert client.get("/foo/").data == b"index"204 assert client.get("/foo/bar").data == b"bar"205206207def test_endpoint_decorator(app, client):208 from werkzeug.routing import Submount, Rule209210 app.url_map.add(211 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])212 )213214 @app.endpoint("bar")215 def bar():216 return "bar"217218 @app.endpoint("index")219 def index():220 return "index"221222 assert client.get("/foo/").data == b"index"223 assert client.get("/foo/bar").data == b"bar"224225226def test_session(app, client):227 @app.route("/set", methods=["POST"])228 def set():229 assert not flask.session.accessed230 assert not flask.session.modified231 flask.session["value"] = flask.request.form["value"]232 assert flask.session.accessed233 assert flask.session.modified234 return "value set"235236 @app.route("/get")237 def get():238 assert not flask.session.accessed239 assert not flask.session.modified240 v = flask.session.get("value", "None")241 assert flask.session.accessed242 assert not flask.session.modified243 return v244245 assert client.post("/set", data={"value": "42"}).data == b"value set"246 assert client.get("/get").data == b"42"247248249def test_session_using_server_name(app, client):250 app.config.update(SERVER_NAME="example.com")251252 @app.route("/")253 def index():254 flask.session["testing"] = 42255 return "Hello World"256257 rv = client.get("/", "http://example.com/")258 assert "domain=.example.com" in rv.headers["set-cookie"].lower()259 assert "httponly" in rv.headers["set-cookie"].lower()260261262def test_session_using_server_name_and_port(app, client):263 app.config.update(SERVER_NAME="example.com:8080")264265 @app.route("/")266 def index():267 flask.session["testing"] = 42268 return "Hello World"269270 rv = client.get("/", "http://example.com:8080/")271 assert "domain=.example.com" in rv.headers["set-cookie"].lower()272 assert "httponly" in rv.headers["set-cookie"].lower()273274275def test_session_using_server_name_port_and_path(app, client):276 app.config.update(SERVER_NAME="example.com:8080", APPLICATION_ROOT="/foo")277278 @app.route("/")279 def index():280 flask.session["testing"] = 42281 return "Hello World"282283 rv = client.get("/", "http://example.com:8080/foo")284 assert "domain=example.com" in rv.headers["set-cookie"].lower()285 assert "path=/foo" in rv.headers["set-cookie"].lower()286 assert "httponly" in rv.headers["set-cookie"].lower()287288289def test_session_using_application_root(app, client):290 class PrefixPathMiddleware(object):291 def __init__(self, app, prefix):292 self.app = app293 self.prefix = prefix294295 def __call__(self, environ, start_response):296 environ["SCRIPT_NAME"] = self.prefix297 return self.app(environ, start_response)298299 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, "/bar")300 app.config.update(APPLICATION_ROOT="/bar")301302 @app.route("/")303 def index():304 flask.session["testing"] = 42305 return "Hello World"306307 rv = client.get("/", "http://example.com:8080/")308 assert "path=/bar" in rv.headers["set-cookie"].lower()309310311def test_session_using_session_settings(app, client):312 app.config.update(313 SERVER_NAME="www.example.com:8080",314 APPLICATION_ROOT="/test",315 SESSION_COOKIE_DOMAIN=".example.com",316 SESSION_COOKIE_HTTPONLY=False,317 SESSION_COOKIE_SECURE=True,318 SESSION_COOKIE_SAMESITE="Lax",319 SESSION_COOKIE_PATH="/",320 )321322 @app.route("/")323 def index():324 flask.session["testing"] = 42325 return "Hello World"326327 rv = client.get("/", "http://www.example.com:8080/test/")328 cookie = rv.headers["set-cookie"].lower()329 assert "domain=.example.com" in cookie330 assert "path=/" in cookie331 assert "secure" in cookie332 assert "httponly" not in cookie333 assert "samesite" in cookie334335336def test_session_using_samesite_attribute(app, client):337 @app.route("/")338 def index():339 flask.session["testing"] = 42340 return "Hello World"341342 app.config.update(SESSION_COOKIE_SAMESITE="invalid")343344 with pytest.raises(ValueError):345 client.get("/")346347 app.config.update(SESSION_COOKIE_SAMESITE=None)348 rv = client.get("/")349 cookie = rv.headers["set-cookie"].lower()350 assert "samesite" not in cookie351352 app.config.update(SESSION_COOKIE_SAMESITE="Strict")353 rv = client.get("/")354 cookie = rv.headers["set-cookie"].lower()355 assert "samesite=strict" in cookie356357 app.config.update(SESSION_COOKIE_SAMESITE="Lax")358 rv = client.get("/")359 cookie = rv.headers["set-cookie"].lower()360 assert "samesite=lax" in cookie361362363def test_session_localhost_warning(recwarn, app, client):364 app.config.update(SERVER_NAME="localhost:5000")365366 @app.route("/")367 def index():368 flask.session["testing"] = 42369 return "testing"370371 rv = client.get("/", "http://localhost:5000/")372 assert "domain" not in rv.headers["set-cookie"].lower()373 w = recwarn.pop(UserWarning)374 assert '"localhost" is not a valid cookie domain' in str(w.message)375376377def test_session_ip_warning(recwarn, app, client):378 app.config.update(SERVER_NAME="127.0.0.1:5000")379380 @app.route("/")381 def index():382 flask.session["testing"] = 42383 return "testing"384385 rv = client.get("/", "http://127.0.0.1:5000/")386 assert "domain=127.0.0.1" in rv.headers["set-cookie"].lower()387 w = recwarn.pop(UserWarning)388 assert "cookie domain is an IP" in str(w.message)389390391def test_missing_session(app):392 app.secret_key = None393394 def expect_exception(f, *args, **kwargs):395 e = pytest.raises(RuntimeError, f, *args, **kwargs)396 assert e.value.args and "session is unavailable" in e.value.args[0]397398 with app.test_request_context():399 assert flask.session.get("missing_key") is None400 expect_exception(flask.session.__setitem__, "foo", 42)401 expect_exception(flask.session.pop, "foo")402403404def test_session_expiration(app, client):405 permanent = True406407 @app.route("/")408 def index():409 flask.session["test"] = 42410 flask.session.permanent = permanent411 return ""412413 @app.route("/test")414 def test():415 return text_type(flask.session.permanent)416417 rv = client.get("/")418 assert "set-cookie" in rv.headers419 match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])420 expires = parse_date(match.group())421 expected = datetime.utcnow() + app.permanent_session_lifetime422 assert expires.year == expected.year423 assert expires.month == expected.month424 assert expires.day == expected.day425426 rv = client.get("/test")427 assert rv.data == b"True"428429 permanent = False430 rv = client.get("/")431 assert "set-cookie" in rv.headers432 match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])433 assert match is None434435436def test_session_stored_last(app, client):437 @app.after_request438 def modify_session(response):439 flask.session["foo"] = 42440 return response441442 @app.route("/")443 def dump_session_contents():444 return repr(flask.session.get("foo"))445446 assert client.get("/").data == b"None"447 assert client.get("/").data == b"42"448449450def test_session_special_types(app, client):451 now = datetime.utcnow().replace(microsecond=0)452 the_uuid = uuid.uuid4()453454 @app.route("/")455 def dump_session_contents():456 flask.session["t"] = (1, 2, 3)457 flask.session["b"] = b"\xff"458 flask.session["m"] = flask.Markup("<html>")459 flask.session["u"] = the_uuid460 flask.session["d"] = now461 flask.session["t_tag"] = {" t": "not-a-tuple"}462 flask.session["di_t_tag"] = {" t__": "not-a-tuple"}463 flask.session["di_tag"] = {" di": "not-a-dict"}464 return "", 204465466 with client:467 client.get("/")468 s = flask.session469 assert s["t"] == (1, 2, 3)470 assert type(s["b"]) == bytes471 assert s["b"] == b"\xff"472 assert type(s["m"]) == flask.Markup473 assert s["m"] == flask.Markup("<html>")474 assert s["u"] == the_uuid475 assert s["d"] == now476 assert s["t_tag"] == {" t": "not-a-tuple"}477 assert s["di_t_tag"] == {" t__": "not-a-tuple"}478 assert s["di_tag"] == {" di": "not-a-dict"}479480481def test_session_cookie_setting(app):482 is_permanent = True483484 @app.route("/bump")485 def bump():486 rv = flask.session["foo"] = flask.session.get("foo", 0) + 1487 flask.session.permanent = is_permanent488 return str(rv)489490 @app.route("/read")491 def read():492 return str(flask.session.get("foo", 0))493494 def run_test(expect_header):495 with app.test_client() as c:496 assert c.get("/bump").data == b"1"497 assert c.get("/bump").data == b"2"498 assert c.get("/bump").data == b"3"499500 rv = c.get("/read")501 set_cookie = rv.headers.get("set-cookie")502 assert (set_cookie is not None) == expect_header503 assert rv.data == b"3"504505 is_permanent = True506 app.config["SESSION_REFRESH_EACH_REQUEST"] = True507 run_test(expect_header=True)508509 is_permanent = True510 app.config["SESSION_REFRESH_EACH_REQUEST"] = False511 run_test(expect_header=False)512513 is_permanent = False514 app.config["SESSION_REFRESH_EACH_REQUEST"] = True515 run_test(expect_header=False)516517 is_permanent = False518 app.config["SESSION_REFRESH_EACH_REQUEST"] = False519 run_test(expect_header=False)520521522def test_session_vary_cookie(app, client):523 @app.route("/set")524 def set_session():525 flask.session["test"] = "test"526 return ""527528 @app.route("/get")529 def get():530 return flask.session.get("test")531532 @app.route("/getitem")533 def getitem():534 return flask.session["test"]535536 @app.route("/setdefault")537 def setdefault():538 return flask.session.setdefault("test", "default")539540 @app.route("/vary-cookie-header-set")541 def vary_cookie_header_set():542 response = flask.Response()543 response.vary.add("Cookie")544 flask.session["test"] = "test"545 return response546547 @app.route("/vary-header-set")548 def vary_header_set():549 response = flask.Response()550 response.vary.update(("Accept-Encoding", "Accept-Language"))551 flask.session["test"] = "test"552 return response553554 @app.route("/no-vary-header")555 def no_vary_header():556 return ""557558 def expect(path, header_value="Cookie"):559 rv = client.get(path)560561 if header_value:562 # The 'Vary' key should exist in the headers only once.563 assert len(rv.headers.get_all("Vary")) == 1564 assert rv.headers["Vary"] == header_value565 else:566 assert "Vary" not in rv.headers567568 expect("/set")569 expect("/get")570 expect("/getitem")571 expect("/setdefault")572 expect("/vary-cookie-header-set")573 expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")574 expect("/no-vary-header", None)575576577def test_flashes(app, req_ctx):578 assert not flask.session.modified579 flask.flash("Zap")580 flask.session.modified = False581 flask.flash("Zip")582 assert flask.session.modified583 assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]584585586def test_extended_flashing(app):587 # Be sure app.testing=True below, else tests can fail silently.588 #589 # Specifically, if app.testing is not set to True, the AssertionErrors590 # in the view functions will cause a 500 response to the test client591 # instead of propagating exceptions.592593 @app.route("/")594 def index():595 flask.flash(u"Hello World")596 flask.flash(u"Hello World", "error")597 flask.flash(flask.Markup(u"<em>Testing</em>"), "warning")598 return ""599600 @app.route("/test/")601 def test():602 messages = flask.get_flashed_messages()603 assert list(messages) == [604 u"Hello World",605 u"Hello World",606 flask.Markup(u"<em>Testing</em>"),607 ]608 return ""609610 @app.route("/test_with_categories/")611 def test_with_categories():612 messages = flask.get_flashed_messages(with_categories=True)613 assert len(messages) == 3614 assert list(messages) == [615 ("message", u"Hello World"),616 ("error", u"Hello World"),617 ("warning", flask.Markup(u"<em>Testing</em>")),618 ]619 return ""620621 @app.route("/test_filter/")622 def test_filter():623 messages = flask.get_flashed_messages(624 category_filter=["message"], with_categories=True625 )626 assert list(messages) == [("message", u"Hello World")]627 return ""628629 @app.route("/test_filters/")630 def test_filters():631 messages = flask.get_flashed_messages(632 category_filter=["message", "warning"], with_categories=True633 )634 assert list(messages) == [635 ("message", u"Hello World"),636 ("warning", flask.Markup(u"<em>Testing</em>")),637 ]638 return ""639640 @app.route("/test_filters_without_returning_categories/")641 def test_filters2():642 messages = flask.get_flashed_messages(category_filter=["message", "warning"])643 assert len(messages) == 2644 assert messages[0] == u"Hello World"645 assert messages[1] == flask.Markup(u"<em>Testing</em>")646 return ""647648 # Create new test client on each test to clean flashed messages.649650 client = app.test_client()651 client.get("/")652 client.get("/test_with_categories/")653654 client = app.test_client()655 client.get("/")656 client.get("/test_filter/")657658 client = app.test_client()659 client.get("/")660 client.get("/test_filters/")661662 client = app.test_client()663 client.get("/")664 client.get("/test_filters_without_returning_categories/")665666667def test_request_processing(app, client):668 evts = []669670 @app.before_request671 def before_request():672 evts.append("before")673674 @app.after_request675 def after_request(response):676 response.data += b"|after"677 evts.append("after")678 return response679680 @app.route("/")681 def index():682 assert "before" in evts683 assert "after" not in evts684 return "request"685686 assert "after" not in evts687 rv = client.get("/").data688 assert "after" in evts689 assert rv == b"request|after"690691692def test_request_preprocessing_early_return(app, client):693 evts = []694695 @app.before_request696 def before_request1():697 evts.append(1)698699 @app.before_request700 def before_request2():701 evts.append(2)702 return "hello"703704 @app.before_request705 def before_request3():706 evts.append(3)707 return "bye"708709 @app.route("/")710 def index():711 evts.append("index")712 return "damnit"713714 rv = client.get("/").data.strip()715 assert rv == b"hello"716 assert evts == [1, 2]717718719def test_after_request_processing(app, client):720 @app.route("/")721 def index():722 @flask.after_this_request723 def foo(response):724 response.headers["X-Foo"] = "a header"725 return response726727 return "Test"728729 resp = client.get("/")730 assert resp.status_code == 200731 assert resp.headers["X-Foo"] == "a header"732733734def test_teardown_request_handler(app, client):735 called = []736737 @app.teardown_request738 def teardown_request(exc):739 called.append(True)740 return "Ignored"741742 @app.route("/")743 def root():744 return "Response"745746 rv = client.get("/")747 assert rv.status_code == 200748 assert b"Response" in rv.data749 assert len(called) == 1750751752def test_teardown_request_handler_debug_mode(app, client):753 called = []754755 @app.teardown_request756 def teardown_request(exc):757 called.append(True)758 return "Ignored"759760 @app.route("/")761 def root():762 return "Response"763764 rv = client.get("/")765 assert rv.status_code == 200766 assert b"Response" in rv.data767 assert len(called) == 1768769770def test_teardown_request_handler_error(app, client):771 called = []772 app.testing = False773774 @app.teardown_request775 def teardown_request1(exc):776 assert type(exc) == ZeroDivisionError777 called.append(True)778 # This raises a new error and blows away sys.exc_info(), so we can779 # test that all teardown_requests get passed the same original780 # exception.781 try:782 raise TypeError()783 except Exception:784 pass785786 @app.teardown_request787 def teardown_request2(exc):788 assert type(exc) == ZeroDivisionError789 called.append(True)790 # This raises a new error and blows away sys.exc_info(), so we can791 # test that all teardown_requests get passed the same original792 # exception.793 try:794 raise TypeError()795 except Exception:796 pass797798 @app.route("/")799 def fails():800 1 // 0801802 rv = client.get("/")803 assert rv.status_code == 500804 assert b"Internal Server Error" in rv.data805 assert len(called) == 2806807808def test_before_after_request_order(app, client):809 called = []810811 @app.before_request812 def before1():813 called.append(1)814815 @app.before_request816 def before2():817 called.append(2)818819 @app.after_request820 def after1(response):821 called.append(4)822 return response823824 @app.after_request825 def after2(response):826 called.append(3)827 return response828829 @app.teardown_request830 def finish1(exc):831 called.append(6)832833 @app.teardown_request834 def finish2(exc):835 called.append(5)836837 @app.route("/")838 def index():839 return "42"840841 rv = client.get("/")842 assert rv.data == b"42"843 assert called == [1, 2, 3, 4, 5, 6]844845846def test_error_handling(app, client):847 app.testing = False848849 @app.errorhandler(404)850 def not_found(e):851 return "not found", 404852853 @app.errorhandler(500)854 def internal_server_error(e):855 return "internal server error", 500856857 @app.errorhandler(Forbidden)858 def forbidden(e):859 return "forbidden", 403860861 @app.route("/")862 def index():863 flask.abort(404)864865 @app.route("/error")866 def error():867 1 // 0868869 @app.route("/forbidden")870 def error2():871 flask.abort(403)872873 rv = client.get("/")874 assert rv.status_code == 404875 assert rv.data == b"not found"876 rv = client.get("/error")877 assert rv.status_code == 500878 assert b"internal server error" == rv.data879 rv = client.get("/forbidden")880 assert rv.status_code == 403881 assert b"forbidden" == rv.data882883884def test_error_handler_unknown_code(app):885 with pytest.raises(KeyError) as exc_info:886 app.register_error_handler(999, lambda e: ("999", 999))887888 assert "Use a subclass" in exc_info.value.args[0]889890891def test_error_handling_processing(app, client):892 app.testing = False893894 @app.errorhandler(500)895 def internal_server_error(e):896 return "internal server error", 500897898 @app.route("/")899 def broken_func():900 1 // 0901902 @app.after_request903 def after_request(resp):904 resp.mimetype = "text/x-special"905 return resp906907 resp = client.get("/")908 assert resp.mimetype == "text/x-special"909 assert resp.data == b"internal server error"910911912def test_baseexception_error_handling(app, client):913 app.testing = False914915 @app.route("/")916 def broken_func():917 raise KeyboardInterrupt()918919 with pytest.raises(KeyboardInterrupt):920 client.get("/")921922 ctx = flask._request_ctx_stack.top923 assert ctx.preserved924 assert type(ctx._preserved_exc) is KeyboardInterrupt925926927def test_before_request_and_routing_errors(app, client):928 @app.before_request929 def attach_something():930 flask.g.something = "value"931932 @app.errorhandler(404)933 def return_something(error):934 return flask.g.something, 404935936 rv = client.get("/")937 assert rv.status_code == 404938 assert rv.data == b"value"939940941def test_user_error_handling(app, client):942 class MyException(Exception):943 pass944945 @app.errorhandler(MyException)946 def handle_my_exception(e):947 assert isinstance(e, MyException)948 return "42"949950 @app.route("/")951 def index():952 raise MyException()953954 assert client.get("/").data == b"42"955956957def test_http_error_subclass_handling(app, client):958 class ForbiddenSubclass(Forbidden):959 pass960961 @app.errorhandler(ForbiddenSubclass)962 def handle_forbidden_subclass(e):963 assert isinstance(e, ForbiddenSubclass)964 return "banana"965966 @app.errorhandler(403)967 def handle_403(e):968 assert not isinstance(e, ForbiddenSubclass)969 assert isinstance(e, Forbidden)970 return "apple"971972 @app.route("/1")973 def index1():974 raise ForbiddenSubclass()975976 @app.route("/2")977 def index2():978 flask.abort(403)979980 @app.route("/3")981 def index3():982 raise Forbidden()983984 assert client.get("/1").data == b"banana"985 assert client.get("/2").data == b"apple"986 assert client.get("/3").data == b"apple"987988989def test_errorhandler_precedence(app, client):990 class E1(Exception):991 pass992993 class E2(Exception):994 pass995996 class E3(E1, E2):997 pass998999 @app.errorhandler(E2)1000 def handle_e2(e):1001 return "E2"10021003 @app.errorhandler(Exception)1004 def handle_exception(e):1005 return "Exception"10061007 @app.route("/E1")1008 def raise_e1():1009 raise E110101011 @app.route("/E3")1012 def raise_e3():1013 raise E310141015 rv = client.get("/E1")1016 assert rv.data == b"Exception"10171018 rv = client.get("/E3")1019 assert rv.data == b"E2"102010211022def test_trapping_of_bad_request_key_errors(app, client):1023 @app.route("/key")1024 def fail():1025 flask.request.form["missing_key"]10261027 @app.route("/abort")1028 def allow_abort():1029 flask.abort(400)10301031 rv = client.get("/key")1032 assert rv.status_code == 4001033 assert b"missing_key" not in rv.data1034 rv = client.get("/abort")1035 assert rv.status_code == 40010361037 app.debug = True1038 with pytest.raises(KeyError) as e:1039 client.get("/key")1040 assert e.errisinstance(BadRequest)1041 assert "missing_key" in e.value.get_description()1042 rv = client.get("/abort")1043 assert rv.status_code == 40010441045 app.debug = False1046 app.config["TRAP_BAD_REQUEST_ERRORS"] = True1047 with pytest.raises(KeyError):1048 client.get("/key")1049 with pytest.raises(BadRequest):1050 client.get("/abort")105110521053def test_trapping_of_all_http_exceptions(app, client):1054 app.config["TRAP_HTTP_EXCEPTIONS"] = True10551056 @app.route("/fail")1057 def fail():1058 flask.abort(404)10591060 with pytest.raises(NotFound):1061 client.get("/fail")106210631064def test_error_handler_after_processor_error(app, client):1065 app.testing = False10661067 @app.before_request1068 def before_request():1069 if _trigger == "before":1070 1 // 010711072 @app.after_request1073 def after_request(response):1074 if _trigger == "after":1075 1 // 01076 return response10771078 @app.route("/")1079 def index():1080 return "Foo"10811082 @app.errorhandler(500)1083 def internal_server_error(e):1084 return "Hello Server Error", 50010851086 for _trigger in "before", "after":1087 rv = client.get("/")1088 assert rv.status_code == 5001089 assert rv.data == b"Hello Server Error"109010911092def test_enctype_debug_helper(app, client):1093 from flask.debughelpers import DebugFilesKeyError10941095 app.debug = True10961097 @app.route("/fail", methods=["POST"])1098 def index():1099 return flask.request.files["foo"].filename11001101 # with statement is important because we leave an exception on the1102 # stack otherwise and we want to ensure that this is not the case1103 # to not negatively affect other tests.1104 with client:1105 with pytest.raises(DebugFilesKeyError) as e:1106 client.post("/fail", data={"foo": "index.txt"})1107 assert "no file contents were transmitted" in str(e.value)1108 assert 'This was submitted: "index.txt"' in str(e.value)110911101111def test_response_types(app, client):1112 @app.route("/text")1113 def from_text():1114 return u"Hällo Wörld"11151116 @app.route("/bytes")1117 def from_bytes():1118 return u"Hällo Wörld".encode("utf-8")11191120 @app.route("/full_tuple")1121 def from_full_tuple():1122 return (1123 "Meh",1124 400,1125 {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1126 )11271128 @app.route("/text_headers")1129 def from_text_headers():1130 return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}11311132 @app.route("/text_status")1133 def from_text_status():1134 return "Hi, status!", 40011351136 @app.route("/response_headers")1137 def from_response_headers():1138 return (1139 flask.Response("Hello world", 404, {"X-Foo": "Baz"}),1140 {"X-Foo": "Bar", "X-Bar": "Foo"},1141 )11421143 @app.route("/response_status")1144 def from_response_status():1145 return app.response_class("Hello world", 400), 50011461147 @app.route("/wsgi")1148 def from_wsgi():1149 return NotFound()11501151 @app.route("/dict")1152 def from_dict():1153 return {"foo": "bar"}, 20111541155 assert client.get("/text").data == u"Hällo Wörld".encode("utf-8")1156 assert client.get("/bytes").data == u"Hällo Wörld".encode("utf-8")11571158 rv = client.get("/full_tuple")1159 assert rv.data == b"Meh"1160 assert rv.headers["X-Foo"] == "Testing"1161 assert rv.status_code == 4001162 assert rv.mimetype == "text/plain"11631164 rv = client.get("/text_headers")1165 assert rv.data == b"Hello"1166 assert rv.headers["X-Foo"] == "Test"1167 assert rv.status_code == 2001168 assert rv.mimetype == "text/plain"11691170 rv = client.get("/text_status")1171 assert rv.data == b"Hi, status!"1172 assert rv.status_code == 4001173 assert rv.mimetype == "text/html"11741175 rv = client.get("/response_headers")1176 assert rv.data == b"Hello world"1177 assert rv.headers.getlist("X-Foo") == ["Baz", "Bar"]1178 assert rv.headers["X-Bar"] == "Foo"1179 assert rv.status_code == 40411801181 rv = client.get("/response_status")1182 assert rv.data == b"Hello world"1183 assert rv.status_code == 50011841185 rv = client.get("/wsgi")1186 assert b"Not Found" in rv.data1187 assert rv.status_code == 40411881189 rv = client.get("/dict")1190 assert rv.json == {"foo": "bar"}1191 assert rv.status_code == 201119211931194def test_response_type_errors():1195 app = flask.Flask(__name__)1196 app.testing = True11971198 @app.route("/none")1199 def from_none():1200 pass12011202 @app.route("/small_tuple")1203 def from_small_tuple():1204 return ("Hello",)12051206 @app.route("/large_tuple")1207 def from_large_tuple():1208 return "Hello", 234, {"X-Foo": "Bar"}, "???"12091210 @app.route("/bad_type")1211 def from_bad_type():1212 return True12131214 @app.route("/bad_wsgi")1215 def from_bad_wsgi():1216 return lambda: None12171218 c = app.test_client()12191220 with pytest.raises(TypeError) as e:1221 c.get("/none")12221223 assert "returned None" in str(e)12241225 with pytest.raises(TypeError) as e:1226 c.get("/small_tuple")12271228 assert "tuple must have the form" in str(e)12291230 pytest.raises(TypeError, c.get, "/large_tuple")12311232 with pytest.raises(TypeError) as e:1233 c.get("/bad_type")12341235 assert "object is not callable" not in str(e)1236 assert "it was a bool" in str(e)12371238 pytest.raises(TypeError, c.get, "/bad_wsgi")123912401241def test_make_response(app, req_ctx):1242 rv = flask.make_response()1243 assert rv.status_code == 2001244 assert rv.data == b""1245 assert rv.mimetype == "text/html"12461247 rv = flask.make_response("Awesome")1248 assert rv.status_code == 2001249 assert rv.data == b"Awesome"1250 assert rv.mimetype == "text/html"12511252 rv = flask.make_response("W00t", 404)1253 assert rv.status_code == 4041254 assert rv.data == b"W00t"1255 assert rv.mimetype == "text/html"125612571258def test_make_response_with_response_instance(app, req_ctx):1259 rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1260 assert rv.status_code == 4001261 assert rv.data == b'{"msg":"W00t"}\n'1262 assert rv.mimetype == "application/json"12631264 rv = flask.make_response(flask.Response(""), 400)1265 assert rv.status_code == 4001266 assert rv.data == b""1267 assert rv.mimetype == "text/html"12681269 rv = flask.make_response(1270 flask.Response("", headers={"Content-Type": "text/html"}),1271 400,1272 [("X-Foo", "bar")],1273 )1274 assert rv.status_code == 4001275 assert rv.headers["Content-Type"] == "text/html"1276 assert rv.headers["X-Foo"] == "bar"127712781279def test_jsonify_no_prettyprint(app, req_ctx):1280 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1281 compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1282 uncompressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}12831284 rv = flask.make_response(flask.jsonify(uncompressed_msg), 200)1285 assert rv.data == compressed_msg128612871288def test_jsonify_prettyprint(app, req_ctx):1289 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1290 compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1291 pretty_response = (1292 b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'1293 )12941295 rv = flask.make_response(flask.jsonify(compressed_msg), 200)1296 assert rv.data == pretty_response129712981299def test_jsonify_mimetype(app, req_ctx):1300 app.config.update({"JSONIFY_MIMETYPE": "application/vnd.api+json"})1301 msg = {"msg": {"submsg": "W00t"}}1302 rv = flask.make_response(flask.jsonify(msg), 200)1303 assert rv.mimetype == "application/vnd.api+json"130413051306@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")1307def test_json_dump_dataclass(app, req_ctx):1308 from dataclasses import make_dataclass13091310 Data = make_dataclass("Data", [("name", str)])1311 value = flask.json.dumps(Data("Flask"), app=app)1312 value = flask.json.loads(value, app=app)1313 assert value == {"name": "Flask"}131413151316def test_jsonify_args_and_kwargs_check(app, req_ctx):1317 with pytest.raises(TypeError) as e:1318 flask.jsonify("fake args", kwargs="fake")1319 assert "behavior undefined" in str(e.value)132013211322def test_url_generation(app, req_ctx):1323 @app.route("/hello/<name>", methods=["POST"])1324 def hello():1325 pass13261327 assert flask.url_for("hello", name="test x") == "/hello/test%20x"1328 assert (1329 flask.url_for("hello", name="test x", _external=True)1330 == "http://localhost/hello/test%20x"1331 )133213331334def test_build_error_handler(app):1335 # Test base case, a URL which results in a BuildError.1336 with app.test_request_context():1337 pytest.raises(BuildError, flask.url_for, "spam")13381339 # Verify the error is re-raised if not the current exception.1340 try:1341 with app.test_request_context():1342 flask.url_for("spam")1343 except BuildError as err:1344 error = err1345 try:1346 raise RuntimeError("Test case where BuildError is not current.")1347 except RuntimeError:1348 pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})13491350 # Test a custom handler.1351 def handler(error, endpoint, values):1352 # Just a test.1353 return "/test_handler/"13541355 app.url_build_error_handlers.append(handler)1356 with app.test_request_context():1357 assert flask.url_for("spam") == "/test_handler/"135813591360def test_build_error_handler_reraise(app):1361 # Test a custom handler which reraises the BuildError1362 def handler_raises_build_error(error, endpoint, values):1363 raise error13641365 app.url_build_error_handlers.append(handler_raises_build_error)13661367 with app.test_request_context():1368 pytest.raises(BuildError, flask.url_for, "not.existing")136913701371def test_url_for_passes_special_values_to_build_error_handler(app):1372 @app.url_build_error_handlers.append1373 def handler(error, endpoint, values):1374 assert values == {1375 "_external": False,1376 "_anchor": None,1377 "_method": None,1378 "_scheme": None,1379 }1380 return "handled"13811382 with app.test_request_context():1383 flask.url_for("/")138413851386def test_custom_converters(app, client):1387 from werkzeug.routing import BaseConverter13881389 class ListConverter(BaseConverter):1390 def to_python(self, value):1391 return value.split(",")13921393 def to_url(self, value):1394 base_to_url = super(ListConverter, self).to_url1395 return ",".join(base_to_url(x) for x in value)13961397 app.url_map.converters["list"] = ListConverter13981399 @app.route("/<list:args>")1400 def index(args):1401 return "|".join(args)14021403 assert client.get("/1,2,3").data == b"1|2|3"140414051406def test_static_files(app, client):1407 rv = client.get("/static/index.html")1408 assert rv.status_code == 2001409 assert rv.data.strip() == b"<h1>Hello World!</h1>"1410 with app.test_request_context():1411 assert flask.url_for("static", filename="index.html") == "/static/index.html"1412 rv.close()141314141415def test_static_url_path():1416 app = flask.Flask(__name__, static_url_path="/foo")1417 app.testing = True1418 rv = app.test_client().get("/foo/index.html")1419 assert rv.status_code == 2001420 rv.close()14211422 with app.test_request_context():1423 assert flask.url_for("static", filename="index.html") == "/foo/index.html"142414251426def test_static_url_path_with_ending_slash():1427 app = flask.Flask(__name__, static_url_path="/foo/")1428 app.testing = True1429 rv = app.test_client().get("/foo/index.html")1430 assert rv.status_code == 2001431 rv.close()14321433 with app.test_request_context():1434 assert flask.url_for("static", filename="index.html") == "/foo/index.html"143514361437def test_static_url_empty_path(app):1438 app = flask.Flask(__name__, static_folder="", static_url_path="")1439 rv = app.test_client().open("/static/index.html", method="GET")1440 assert rv.status_code == 2001441 rv.close()144214431444def test_static_url_empty_path_default(app):1445 app = flask.Flask(__name__, static_folder="")1446 rv = app.test_client().open("/static/index.html", method="GET")1447 assert rv.status_code == 2001448 rv.close()144914501451def test_static_route_with_host_matching():1452 app = flask.Flask(__name__, host_matching=True, static_host="example.com")1453 c = app.test_client()1454 rv = c.get("http://example.com/static/index.html")1455 assert rv.status_code == 2001456 rv.close()1457 with app.test_request_context():1458 rv = flask.url_for("static", filename="index.html", _external=True)1459 assert rv == "http://example.com/static/index.html"1460 # Providing static_host without host_matching=True should error.1461 with pytest.raises(Exception):1462 flask.Flask(__name__, static_host="example.com")1463 # Providing host_matching=True with static_folder1464 # but without static_host should error.1465 with pytest.raises(Exception):1466 flask.Flask(__name__, host_matching=True)1467 # Providing host_matching=True without static_host1468 # but with static_folder=None should not error.1469 flask.Flask(__name__, host_matching=True, static_folder=None)147014711472def test_request_locals():1473 assert repr(flask.g) == "<LocalProxy unbound>"1474 assert not flask.g147514761477def test_test_app_proper_environ():1478 app = flask.Flask(__name__, subdomain_matching=True)1479 app.config.update(SERVER_NAME="localhost.localdomain:5000")1480 client = app.test_client()14811482 @app.route("/")1483 def index():1484 return "Foo"14851486 @app.route("/", subdomain="foo")1487 def subdomain():1488 return "Foo SubDomain"14891490 rv = client.get("/")1491 assert rv.data == b"Foo"14921493 rv = client.get("/", "http://localhost.localdomain:5000")1494 assert rv.data == b"Foo"14951496 rv = client.get("/", "https://localhost.localdomain:5000")1497 assert rv.data == b"Foo"14981499 app.config.update(SERVER_NAME="localhost.localdomain")1500 rv = client.get("/", "https://localhost.localdomain")1501 assert rv.data == b"Foo"15021503 try:1504 app.config.update(SERVER_NAME="localhost.localdomain:443")1505 rv = client.get("/", "https://localhost.localdomain")1506 # Werkzeug 0.81507 assert rv.status_code == 4041508 except ValueError as e:1509 # Werkzeug 0.71510 assert str(e) == (1511 "the server name provided "1512 "('localhost.localdomain:443') does not match the "1513 "server name from the WSGI environment ('localhost.localdomain')"1514 )15151516 try:1517 app.config.update(SERVER_NAME="localhost.localdomain")1518 rv = client.get("/", "http://foo.localhost")1519 # Werkzeug 0.81520 assert rv.status_code == 4041521 except ValueError as e:1522 # Werkzeug 0.71523 assert str(e) == (1524 "the server name provided "1525 "('localhost.localdomain') does not match the "1526 "server name from the WSGI environment ('foo.localhost')"1527 )15281529 rv = client.get("/", "http://foo.localhost.localdomain")1530 assert rv.data == b"Foo SubDomain"153115321533def test_exception_propagation(app, client):1534 def apprunner(config_key):1535 @app.route("/")1536 def index():1537 1 // 015381539 if config_key is not None:1540 app.config[config_key] = True1541 with pytest.raises(Exception):1542 client.get("/")1543 else:1544 assert client.get("/").status_code == 50015451546 # we have to run this test in an isolated thread because if the1547 # debug flag is set to true and an exception happens the context is1548 # not torn down. This causes other tests that run after this fail1549 # when they expect no exception on the stack.1550 for config_key in "TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None:1551 t = Thread(target=apprunner, args=(config_key,))1552 t.start()1553 t.join()155415551556@pytest.mark.parametrize("debug", [True, False])1557@pytest.mark.parametrize("use_debugger", [True, False])1558@pytest.mark.parametrize("use_reloader", [True, False])1559@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1560def test_werkzeug_passthrough_errors(1561 monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1562):1563 rv = {}15641565 # Mocks werkzeug.serving.run_simple method1566 def run_simple_mock(*args, **kwargs):1567 rv["passthrough_errors"] = kwargs.get("passthrough_errors")15681569 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1570 app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1571 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)157215731574def test_max_content_length(app, client):1575 app.config["MAX_CONTENT_LENGTH"] = 6415761577 @app.before_request1578 def always_first():1579 flask.request.form["myfile"]1580 AssertionError()15811582 @app.route("/accept", methods=["POST"])1583 def accept_file():1584 flask.request.form["myfile"]1585 AssertionError()15861587 @app.errorhandler(413)1588 def catcher(error):1589 return "42"15901591 rv = client.post("/accept", data={"myfile": "foo" * 100})1592 assert rv.data == b"42"159315941595def test_url_processors(app, client):1596 @app.url_defaults1597 def add_language_code(endpoint, values):1598 if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1599 endpoint, "lang_code"1600 ):1601 values.setdefault("lang_code", flask.g.lang_code)16021603 @app.url_value_preprocessor1604 def pull_lang_code(endpoint, values):1605 flask.g.lang_code = values.pop("lang_code", None)16061607 @app.route("/<lang_code>/")1608 def index():1609 return flask.url_for("about")16101611 @app.route("/<lang_code>/about")1612 def about():1613 return flask.url_for("something_else")16141615 @app.route("/foo")1616 def something_else():1617 return flask.url_for("about", lang_code="en")16181619 assert client.get("/de/").data == b"/de/about"1620 assert client.get("/de/about").data == b"/foo"1621 assert client.get("/foo").data == b"/en/about"162216231624def test_inject_blueprint_url_defaults(app):1625 bp = flask.Blueprint("foo.bar.baz", __name__, template_folder="template")16261627 @bp.url_defaults1628 def bp_defaults(endpoint, values):1629 values["page"] = "login"16301631 @bp.route("/<page>")1632 def view(page):1633 pass16341635 app.register_blueprint(bp)16361637 values = dict()1638 app.inject_url_defaults("foo.bar.baz.view", values)1639 expected = dict(page="login")1640 assert values == expected16411642 with app.test_request_context("/somepage"):1643 url = flask.url_for("foo.bar.baz.view")1644 expected = "/login"1645 assert url == expected164616471648def test_nonascii_pathinfo(app, client):1649 @app.route(u"/киртест")1650 def index():1651 return "Hello World!"16521653 rv = client.get(u"/киртест")1654 assert rv.data == b"Hello World!"165516561657def test_debug_mode_complains_after_first_request(app, client):1658 app.debug = True16591660 @app.route("/")1661 def index():1662 return "Awesome"16631664 assert not app.got_first_request1665 assert client.get("/").data == b"Awesome"1666 with pytest.raises(AssertionError) as e:16671668 @app.route("/foo")1669 def broken():1670 return "Meh"16711672 assert "A setup function was called" in str(e)16731674 app.debug = False16751676 @app.route("/foo")1677 def working():1678 return "Meh"16791680 assert client.get("/foo").data == b"Meh"1681 assert app.got_first_request168216831684def test_before_first_request_functions(app, client):1685 got = []16861687 @app.before_first_request1688 def foo():1689 got.append(42)16901691 client.get("/")1692 assert got == [42]1693 client.get("/")1694 assert got == [42]1695 assert app.got_first_request169616971698def test_before_first_request_functions_concurrent(app, client):1699 got = []17001701 @app.before_first_request1702 def foo():1703 time.sleep(0.2)1704 got.append(42)17051706 def get_and_assert():1707 client.get("/")1708 assert got == [42]17091710 t = Thread(target=get_and_assert)1711 t.start()1712 get_and_assert()1713 t.join()1714 assert app.got_first_request171517161717def test_routing_redirect_debugging(app, client):1718 app.debug = True17191720 @app.route("/foo/", methods=["GET", "POST"])1721 def foo():1722 return "success"17231724 with client:1725 with pytest.raises(AssertionError) as e:1726 client.post("/foo", data={})1727 assert "http://localhost/foo/" in str(e)1728 assert ("Make sure to directly send " "your POST-request to this URL") in str(e)17291730 rv = client.get("/foo", data={}, follow_redirects=True)1731 assert rv.data == b"success"17321733 app.debug = False1734 with client:1735 rv = client.post("/foo", data={}, follow_redirects=True)1736 assert rv.data == b"success"173717381739def test_route_decorator_custom_endpoint(app, client):1740 app.debug = True17411742 @app.route("/foo/")1743 def foo():1744 return flask.request.endpoint17451746 @app.route("/bar/", endpoint="bar")1747 def for_bar():1748 return flask.request.endpoint17491750 @app.route("/bar/123", endpoint="123")1751 def for_bar_foo():1752 return flask.request.endpoint17531754 with app.test_request_context():1755 assert flask.url_for("foo") == "/foo/"1756 assert flask.url_for("bar") == "/bar/"1757 assert flask.url_for("123") == "/bar/123"17581759 assert client.get("/foo/").data == b"foo"1760 assert client.get("/bar/").data == b"bar"1761 assert client.get("/bar/123").data == b"123"176217631764def test_preserve_only_once(app, client):1765 app.debug = True17661767 @app.route("/fail")1768 def fail_func():1769 1 // 017701771 for _x in range(3):1772 with pytest.raises(ZeroDivisionError):1773 client.get("/fail")17741775 assert flask._request_ctx_stack.top is not None1776 assert flask._app_ctx_stack.top is not None1777 # implicit appctx disappears too1778 flask._request_ctx_stack.top.pop()1779 assert flask._request_ctx_stack.top is None1780 assert flask._app_ctx_stack.top is None178117821783def test_preserve_remembers_exception(app, client):1784 app.debug = True1785 errors = []17861787 @app.route("/fail")1788 def fail_func():1789 1 // 017901791 @app.route("/success")1792 def success_func():1793 return "Okay"17941795 @app.teardown_request1796 def teardown_handler(exc):1797 errors.append(exc)17981799 # After this failure we did not yet call the teardown handler1800 with pytest.raises(ZeroDivisionError):1801 client.get("/fail")1802 assert errors == []18031804 # But this request triggers it, and it's an error1805 client.get("/success")1806 assert len(errors) == 21807 assert isinstance(errors[0], ZeroDivisionError)18081809 # At this point another request does nothing.1810 client.get("/success")1811 assert len(errors) == 31812 assert errors[1] is None181318141815def test_get_method_on_g(app_ctx):1816 assert flask.g.get("x") is None1817 assert flask.g.get("x", 11) == 111818 flask.g.x = 421819 assert flask.g.get("x") == 421820 assert flask.g.x == 42182118221823def test_g_iteration_protocol(app_ctx):1824 flask.g.foo = 231825 flask.g.bar = 421826 assert "foo" in flask.g1827 assert "foos" not in flask.g1828 assert sorted(flask.g) == ["bar", "foo"]182918301831def test_subdomain_basic_support():1832 app = flask.Flask(__name__, subdomain_matching=True)1833 app.config["SERVER_NAME"] = "localhost.localdomain"1834 client = app.test_client()18351836 @app.route("/")1837 def normal_index():1838 return "normal index"18391840 @app.route("/", subdomain="test")1841 def test_index():1842 return "test index"18431844 rv = client.get("/", "http://localhost.localdomain/")1845 assert rv.data == b"normal index"18461847 rv = client.get("/", "http://test.localhost.localdomain/")1848 assert rv.data == b"test index"184918501851def test_subdomain_matching():1852 app = flask.Flask(__name__, subdomain_matching=True)1853 client = app.test_client()1854 app.config["SERVER_NAME"] = "localhost.localdomain"18551856 @app.route("/", subdomain="<user>")1857 def index(user):1858 return "index for %s" % user18591860 rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1861 assert rv.data == b"index for mitsuhiko"186218631864def test_subdomain_matching_with_ports():1865 app = flask.Flask(__name__, subdomain_matching=True)1866 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1867 client = app.test_client()18681869 @app.route("/", subdomain="<user>")1870 def index(user):1871 return "index for %s" % user18721873 rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1874 assert rv.data == b"index for mitsuhiko"187518761877@pytest.mark.parametrize("matching", (False, True))1878def test_subdomain_matching_other_name(matching):1879 app = flask.Flask(__name__, subdomain_matching=matching)1880 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1881 client = app.test_client()18821883 @app.route("/")1884 def index():1885 return "", 20418861887 # ip address can't match name1888 rv = client.get("/", "http://127.0.0.1:3000/")1889 assert rv.status_code == 404 if matching else 20418901891 # allow all subdomains if matching is disabled1892 rv = client.get("/", "http://www.localhost.localdomain:3000/")1893 assert rv.status_code == 404 if matching else 204189418951896def test_multi_route_rules(app, client):1897 @app.route("/")1898 @app.route("/<test>/")1899 def index(test="a"):1900 return test19011902 rv = client.open("/")1903 assert rv.data == b"a"1904 rv = client.open("/b/")1905 assert rv.data == b"b"190619071908def test_multi_route_class_views(app, client):1909 class View(object):1910 def __init__(self, app):1911 app.add_url_rule("/", "index", self.index)1912 app.add_url_rule("/<test>/", "index", self.index)19131914 def index(self, test="a"):1915 return test19161917 _ = View(app)1918 rv = client.open("/")1919 assert rv.data == b"a"1920 rv = client.open("/b/")1921 assert rv.data == b"b"192219231924def test_run_defaults(monkeypatch, app):1925 rv = {}19261927 # Mocks werkzeug.serving.run_simple method1928 def run_simple_mock(*args, **kwargs):1929 rv["result"] = "running..."19301931 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1932 app.run()1933 assert rv["result"] == "running..."193419351936def test_run_server_port(monkeypatch, app):1937 rv = {}19381939 # Mocks werkzeug.serving.run_simple method1940 def run_simple_mock(hostname, port, application, *args, **kwargs):1941 rv["result"] = "running on %s:%s ..." % (hostname, port)19421943 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1944 hostname, port = "localhost", 80001945 app.run(hostname, port, debug=True)1946 assert rv["result"] == "running on %s:%s ..." % (hostname, port)194719481949@pytest.mark.parametrize(1950 "host,port,server_name,expect_host,expect_port",1951 (1952 (None, None, "pocoo.org:8080", "pocoo.org", 8080),1953 ("localhost", None, "pocoo.org:8080", "localhost", 8080),1954 (None, 80, "pocoo.org:8080", "pocoo.org", 80),1955 ("localhost", 80, "pocoo.org:8080", "localhost", 80),1956 ("localhost", 0, "localhost:8080", "localhost", 0),1957 (None, None, "localhost:8080", "localhost", 8080),1958 (None, None, "localhost:0", "localhost", 0),1959 ),1960)1961def test_run_from_config(1962 monkeypatch, host, port, server_name, expect_host, expect_port, app1963):1964 def run_simple_mock(hostname, port, *args, **kwargs):1965 assert hostname == expect_host1966 assert port == expect_port19671968 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1969 app.config["SERVER_NAME"] = server_name1970 app.run(host, port)197119721973def test_max_cookie_size(app, client, recwarn):1974 app.config["MAX_COOKIE_SIZE"] = 10019751976 # outside app context, default to Werkzeug static value,1977 # which is also the default config1978 response = flask.Response()1979 default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1980 assert response.max_cookie_size == default19811982 # inside app context, use app config1983 with app.app_context():1984 assert flask.Response().max_cookie_size == 10019851986 @app.route("/")1987 def index():1988 r = flask.Response("", status=204)1989 r.set_cookie("foo", "bar" * 100)1990 return r19911992 client.get("/")1993 assert len(recwarn) == 11994 w = recwarn.pop()1995 assert "cookie is too large" in str(w.message)19961997 app.config["MAX_COOKIE_SIZE"] = 019981999 client.get("/")2000 assert len(recwarn) == 0