test_basic.py
This file
Path
tests/test_basic.py
1,989 lines · 53.6 KiB · Python
Last changed by
fix 'static_url_path' defaulting for empty pathsPete Beardmorebefore adoptiona12bf29
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 added when non-uppercase 'options' in methods167 app.add_url_rule("/options", "options", options, methods=["options"])168169 assert client.get("/").data == b"GET"170 rv = client.post("/")171 assert rv.status_code == 405172 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]173 rv = client.head("/")174 assert rv.status_code == 200175 assert not rv.data # head truncates176 assert client.post("/more").data == b"POST"177 assert client.get("/more").data == b"GET"178 rv = client.delete("/more")179 assert rv.status_code == 405180 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]181 rv = client.open("/options", method="OPTIONS")182 assert rv.status_code == 200183 assert random_uuid4 in rv.data.decode("utf-8")184185186def test_werkzeug_routing(app, client):187 from werkzeug.routing import Submount, Rule188189 app.url_map.add(190 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])191 )192193 def bar():194 return "bar"195196 def index():197 return "index"198199 app.view_functions["bar"] = bar200 app.view_functions["index"] = index201202 assert client.get("/foo/").data == b"index"203 assert client.get("/foo/bar").data == b"bar"204205206def test_endpoint_decorator(app, client):207 from werkzeug.routing import Submount, Rule208209 app.url_map.add(210 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])211 )212213 @app.endpoint("bar")214 def bar():215 return "bar"216217 @app.endpoint("index")218 def index():219 return "index"220221 assert client.get("/foo/").data == b"index"222 assert client.get("/foo/bar").data == b"bar"223224225def test_session(app, client):226 @app.route("/set", methods=["POST"])227 def set():228 assert not flask.session.accessed229 assert not flask.session.modified230 flask.session["value"] = flask.request.form["value"]231 assert flask.session.accessed232 assert flask.session.modified233 return "value set"234235 @app.route("/get")236 def get():237 assert not flask.session.accessed238 assert not flask.session.modified239 v = flask.session.get("value", "None")240 assert flask.session.accessed241 assert not flask.session.modified242 return v243244 assert client.post("/set", data={"value": "42"}).data == b"value set"245 assert client.get("/get").data == b"42"246247248def test_session_using_server_name(app, client):249 app.config.update(SERVER_NAME="example.com")250251 @app.route("/")252 def index():253 flask.session["testing"] = 42254 return "Hello World"255256 rv = client.get("/", "http://example.com/")257 assert "domain=.example.com" in rv.headers["set-cookie"].lower()258 assert "httponly" in rv.headers["set-cookie"].lower()259260261def test_session_using_server_name_and_port(app, client):262 app.config.update(SERVER_NAME="example.com:8080")263264 @app.route("/")265 def index():266 flask.session["testing"] = 42267 return "Hello World"268269 rv = client.get("/", "http://example.com:8080/")270 assert "domain=.example.com" in rv.headers["set-cookie"].lower()271 assert "httponly" in rv.headers["set-cookie"].lower()272273274def test_session_using_server_name_port_and_path(app, client):275 app.config.update(SERVER_NAME="example.com:8080", APPLICATION_ROOT="/foo")276277 @app.route("/")278 def index():279 flask.session["testing"] = 42280 return "Hello World"281282 rv = client.get("/", "http://example.com:8080/foo")283 assert "domain=example.com" in rv.headers["set-cookie"].lower()284 assert "path=/foo" in rv.headers["set-cookie"].lower()285 assert "httponly" in rv.headers["set-cookie"].lower()286287288def test_session_using_application_root(app, client):289 class PrefixPathMiddleware(object):290 def __init__(self, app, prefix):291 self.app = app292 self.prefix = prefix293294 def __call__(self, environ, start_response):295 environ["SCRIPT_NAME"] = self.prefix296 return self.app(environ, start_response)297298 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, "/bar")299 app.config.update(APPLICATION_ROOT="/bar")300301 @app.route("/")302 def index():303 flask.session["testing"] = 42304 return "Hello World"305306 rv = client.get("/", "http://example.com:8080/")307 assert "path=/bar" in rv.headers["set-cookie"].lower()308309310def test_session_using_session_settings(app, client):311 app.config.update(312 SERVER_NAME="www.example.com:8080",313 APPLICATION_ROOT="/test",314 SESSION_COOKIE_DOMAIN=".example.com",315 SESSION_COOKIE_HTTPONLY=False,316 SESSION_COOKIE_SECURE=True,317 SESSION_COOKIE_SAMESITE="Lax",318 SESSION_COOKIE_PATH="/",319 )320321 @app.route("/")322 def index():323 flask.session["testing"] = 42324 return "Hello World"325326 rv = client.get("/", "http://www.example.com:8080/test/")327 cookie = rv.headers["set-cookie"].lower()328 assert "domain=.example.com" in cookie329 assert "path=/" in cookie330 assert "secure" in cookie331 assert "httponly" not in cookie332 assert "samesite" in cookie333334335def test_session_using_samesite_attribute(app, client):336 @app.route("/")337 def index():338 flask.session["testing"] = 42339 return "Hello World"340341 app.config.update(SESSION_COOKIE_SAMESITE="invalid")342343 with pytest.raises(ValueError):344 client.get("/")345346 app.config.update(SESSION_COOKIE_SAMESITE=None)347 rv = client.get("/")348 cookie = rv.headers["set-cookie"].lower()349 assert "samesite" not in cookie350351 app.config.update(SESSION_COOKIE_SAMESITE="Strict")352 rv = client.get("/")353 cookie = rv.headers["set-cookie"].lower()354 assert "samesite=strict" in cookie355356 app.config.update(SESSION_COOKIE_SAMESITE="Lax")357 rv = client.get("/")358 cookie = rv.headers["set-cookie"].lower()359 assert "samesite=lax" in cookie360361362def test_session_localhost_warning(recwarn, app, client):363 app.config.update(SERVER_NAME="localhost:5000")364365 @app.route("/")366 def index():367 flask.session["testing"] = 42368 return "testing"369370 rv = client.get("/", "http://localhost:5000/")371 assert "domain" not in rv.headers["set-cookie"].lower()372 w = recwarn.pop(UserWarning)373 assert '"localhost" is not a valid cookie domain' in str(w.message)374375376def test_session_ip_warning(recwarn, app, client):377 app.config.update(SERVER_NAME="127.0.0.1:5000")378379 @app.route("/")380 def index():381 flask.session["testing"] = 42382 return "testing"383384 rv = client.get("/", "http://127.0.0.1:5000/")385 assert "domain=127.0.0.1" in rv.headers["set-cookie"].lower()386 w = recwarn.pop(UserWarning)387 assert "cookie domain is an IP" in str(w.message)388389390def test_missing_session(app):391 app.secret_key = None392393 def expect_exception(f, *args, **kwargs):394 e = pytest.raises(RuntimeError, f, *args, **kwargs)395 assert e.value.args and "session is unavailable" in e.value.args[0]396397 with app.test_request_context():398 assert flask.session.get("missing_key") is None399 expect_exception(flask.session.__setitem__, "foo", 42)400 expect_exception(flask.session.pop, "foo")401402403def test_session_expiration(app, client):404 permanent = True405406 @app.route("/")407 def index():408 flask.session["test"] = 42409 flask.session.permanent = permanent410 return ""411412 @app.route("/test")413 def test():414 return text_type(flask.session.permanent)415416 rv = client.get("/")417 assert "set-cookie" in rv.headers418 match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])419 expires = parse_date(match.group())420 expected = datetime.utcnow() + app.permanent_session_lifetime421 assert expires.year == expected.year422 assert expires.month == expected.month423 assert expires.day == expected.day424425 rv = client.get("/test")426 assert rv.data == b"True"427428 permanent = False429 rv = client.get("/")430 assert "set-cookie" in rv.headers431 match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])432 assert match is None433434435def test_session_stored_last(app, client):436 @app.after_request437 def modify_session(response):438 flask.session["foo"] = 42439 return response440441 @app.route("/")442 def dump_session_contents():443 return repr(flask.session.get("foo"))444445 assert client.get("/").data == b"None"446 assert client.get("/").data == b"42"447448449def test_session_special_types(app, client):450 now = datetime.utcnow().replace(microsecond=0)451 the_uuid = uuid.uuid4()452453 @app.route("/")454 def dump_session_contents():455 flask.session["t"] = (1, 2, 3)456 flask.session["b"] = b"\xff"457 flask.session["m"] = flask.Markup("<html>")458 flask.session["u"] = the_uuid459 flask.session["d"] = now460 flask.session["t_tag"] = {" t": "not-a-tuple"}461 flask.session["di_t_tag"] = {" t__": "not-a-tuple"}462 flask.session["di_tag"] = {" di": "not-a-dict"}463 return "", 204464465 with client:466 client.get("/")467 s = flask.session468 assert s["t"] == (1, 2, 3)469 assert type(s["b"]) == bytes470 assert s["b"] == b"\xff"471 assert type(s["m"]) == flask.Markup472 assert s["m"] == flask.Markup("<html>")473 assert s["u"] == the_uuid474 assert s["d"] == now475 assert s["t_tag"] == {" t": "not-a-tuple"}476 assert s["di_t_tag"] == {" t__": "not-a-tuple"}477 assert s["di_tag"] == {" di": "not-a-dict"}478479480def test_session_cookie_setting(app):481 is_permanent = True482483 @app.route("/bump")484 def bump():485 rv = flask.session["foo"] = flask.session.get("foo", 0) + 1486 flask.session.permanent = is_permanent487 return str(rv)488489 @app.route("/read")490 def read():491 return str(flask.session.get("foo", 0))492493 def run_test(expect_header):494 with app.test_client() as c:495 assert c.get("/bump").data == b"1"496 assert c.get("/bump").data == b"2"497 assert c.get("/bump").data == b"3"498499 rv = c.get("/read")500 set_cookie = rv.headers.get("set-cookie")501 assert (set_cookie is not None) == expect_header502 assert rv.data == b"3"503504 is_permanent = True505 app.config["SESSION_REFRESH_EACH_REQUEST"] = True506 run_test(expect_header=True)507508 is_permanent = True509 app.config["SESSION_REFRESH_EACH_REQUEST"] = False510 run_test(expect_header=False)511512 is_permanent = False513 app.config["SESSION_REFRESH_EACH_REQUEST"] = True514 run_test(expect_header=False)515516 is_permanent = False517 app.config["SESSION_REFRESH_EACH_REQUEST"] = False518 run_test(expect_header=False)519520521def test_session_vary_cookie(app, client):522 @app.route("/set")523 def set_session():524 flask.session["test"] = "test"525 return ""526527 @app.route("/get")528 def get():529 return flask.session.get("test")530531 @app.route("/getitem")532 def getitem():533 return flask.session["test"]534535 @app.route("/setdefault")536 def setdefault():537 return flask.session.setdefault("test", "default")538539 @app.route("/vary-cookie-header-set")540 def vary_cookie_header_set():541 response = flask.Response()542 response.vary.add("Cookie")543 flask.session["test"] = "test"544 return response545546 @app.route("/vary-header-set")547 def vary_header_set():548 response = flask.Response()549 response.vary.update(("Accept-Encoding", "Accept-Language"))550 flask.session["test"] = "test"551 return response552553 @app.route("/no-vary-header")554 def no_vary_header():555 return ""556557 def expect(path, header_value="Cookie"):558 rv = client.get(path)559560 if header_value:561 # The 'Vary' key should exist in the headers only once.562 assert len(rv.headers.get_all("Vary")) == 1563 assert rv.headers["Vary"] == header_value564 else:565 assert "Vary" not in rv.headers566567 expect("/set")568 expect("/get")569 expect("/getitem")570 expect("/setdefault")571 expect("/vary-cookie-header-set")572 expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")573 expect("/no-vary-header", None)574575576def test_flashes(app, req_ctx):577 assert not flask.session.modified578 flask.flash("Zap")579 flask.session.modified = False580 flask.flash("Zip")581 assert flask.session.modified582 assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]583584585def test_extended_flashing(app):586 # Be sure app.testing=True below, else tests can fail silently.587 #588 # Specifically, if app.testing is not set to True, the AssertionErrors589 # in the view functions will cause a 500 response to the test client590 # instead of propagating exceptions.591592 @app.route("/")593 def index():594 flask.flash(u"Hello World")595 flask.flash(u"Hello World", "error")596 flask.flash(flask.Markup(u"<em>Testing</em>"), "warning")597 return ""598599 @app.route("/test/")600 def test():601 messages = flask.get_flashed_messages()602 assert list(messages) == [603 u"Hello World",604 u"Hello World",605 flask.Markup(u"<em>Testing</em>"),606 ]607 return ""608609 @app.route("/test_with_categories/")610 def test_with_categories():611 messages = flask.get_flashed_messages(with_categories=True)612 assert len(messages) == 3613 assert list(messages) == [614 ("message", u"Hello World"),615 ("error", u"Hello World"),616 ("warning", flask.Markup(u"<em>Testing</em>")),617 ]618 return ""619620 @app.route("/test_filter/")621 def test_filter():622 messages = flask.get_flashed_messages(623 category_filter=["message"], with_categories=True624 )625 assert list(messages) == [("message", u"Hello World")]626 return ""627628 @app.route("/test_filters/")629 def test_filters():630 messages = flask.get_flashed_messages(631 category_filter=["message", "warning"], with_categories=True632 )633 assert list(messages) == [634 ("message", u"Hello World"),635 ("warning", flask.Markup(u"<em>Testing</em>")),636 ]637 return ""638639 @app.route("/test_filters_without_returning_categories/")640 def test_filters2():641 messages = flask.get_flashed_messages(category_filter=["message", "warning"])642 assert len(messages) == 2643 assert messages[0] == u"Hello World"644 assert messages[1] == flask.Markup(u"<em>Testing</em>")645 return ""646647 # Create new test client on each test to clean flashed messages.648649 client = app.test_client()650 client.get("/")651 client.get("/test_with_categories/")652653 client = app.test_client()654 client.get("/")655 client.get("/test_filter/")656657 client = app.test_client()658 client.get("/")659 client.get("/test_filters/")660661 client = app.test_client()662 client.get("/")663 client.get("/test_filters_without_returning_categories/")664665666def test_request_processing(app, client):667 evts = []668669 @app.before_request670 def before_request():671 evts.append("before")672673 @app.after_request674 def after_request(response):675 response.data += b"|after"676 evts.append("after")677 return response678679 @app.route("/")680 def index():681 assert "before" in evts682 assert "after" not in evts683 return "request"684685 assert "after" not in evts686 rv = client.get("/").data687 assert "after" in evts688 assert rv == b"request|after"689690691def test_request_preprocessing_early_return(app, client):692 evts = []693694 @app.before_request695 def before_request1():696 evts.append(1)697698 @app.before_request699 def before_request2():700 evts.append(2)701 return "hello"702703 @app.before_request704 def before_request3():705 evts.append(3)706 return "bye"707708 @app.route("/")709 def index():710 evts.append("index")711 return "damnit"712713 rv = client.get("/").data.strip()714 assert rv == b"hello"715 assert evts == [1, 2]716717718def test_after_request_processing(app, client):719 @app.route("/")720 def index():721 @flask.after_this_request722 def foo(response):723 response.headers["X-Foo"] = "a header"724 return response725726 return "Test"727728 resp = client.get("/")729 assert resp.status_code == 200730 assert resp.headers["X-Foo"] == "a header"731732733def test_teardown_request_handler(app, client):734 called = []735736 @app.teardown_request737 def teardown_request(exc):738 called.append(True)739 return "Ignored"740741 @app.route("/")742 def root():743 return "Response"744745 rv = client.get("/")746 assert rv.status_code == 200747 assert b"Response" in rv.data748 assert len(called) == 1749750751def test_teardown_request_handler_debug_mode(app, client):752 called = []753754 @app.teardown_request755 def teardown_request(exc):756 called.append(True)757 return "Ignored"758759 @app.route("/")760 def root():761 return "Response"762763 rv = client.get("/")764 assert rv.status_code == 200765 assert b"Response" in rv.data766 assert len(called) == 1767768769def test_teardown_request_handler_error(app, client):770 called = []771 app.testing = False772773 @app.teardown_request774 def teardown_request1(exc):775 assert type(exc) == ZeroDivisionError776 called.append(True)777 # This raises a new error and blows away sys.exc_info(), so we can778 # test that all teardown_requests get passed the same original779 # exception.780 try:781 raise TypeError()782 except:783 pass784785 @app.teardown_request786 def teardown_request2(exc):787 assert type(exc) == ZeroDivisionError788 called.append(True)789 # This raises a new error and blows away sys.exc_info(), so we can790 # test that all teardown_requests get passed the same original791 # exception.792 try:793 raise TypeError()794 except:795 pass796797 @app.route("/")798 def fails():799 1 // 0800801 rv = client.get("/")802 assert rv.status_code == 500803 assert b"Internal Server Error" in rv.data804 assert len(called) == 2805806807def test_before_after_request_order(app, client):808 called = []809810 @app.before_request811 def before1():812 called.append(1)813814 @app.before_request815 def before2():816 called.append(2)817818 @app.after_request819 def after1(response):820 called.append(4)821 return response822823 @app.after_request824 def after2(response):825 called.append(3)826 return response827828 @app.teardown_request829 def finish1(exc):830 called.append(6)831832 @app.teardown_request833 def finish2(exc):834 called.append(5)835836 @app.route("/")837 def index():838 return "42"839840 rv = client.get("/")841 assert rv.data == b"42"842 assert called == [1, 2, 3, 4, 5, 6]843844845def test_error_handling(app, client):846 app.testing = False847848 @app.errorhandler(404)849 def not_found(e):850 return "not found", 404851852 @app.errorhandler(500)853 def internal_server_error(e):854 return "internal server error", 500855856 @app.errorhandler(Forbidden)857 def forbidden(e):858 return "forbidden", 403859860 @app.route("/")861 def index():862 flask.abort(404)863864 @app.route("/error")865 def error():866 1 // 0867868 @app.route("/forbidden")869 def error2():870 flask.abort(403)871872 rv = client.get("/")873 assert rv.status_code == 404874 assert rv.data == b"not found"875 rv = client.get("/error")876 assert rv.status_code == 500877 assert b"internal server error" == rv.data878 rv = client.get("/forbidden")879 assert rv.status_code == 403880 assert b"forbidden" == rv.data881882883def test_error_handler_unknown_code(app):884 with pytest.raises(KeyError) as exc_info:885 app.register_error_handler(999, lambda e: ("999", 999))886887 assert "Use a subclass" in exc_info.value.args[0]888889890def test_error_handling_processing(app, client):891 app.testing = False892893 @app.errorhandler(500)894 def internal_server_error(e):895 return "internal server error", 500896897 @app.route("/")898 def broken_func():899 1 // 0900901 @app.after_request902 def after_request(resp):903 resp.mimetype = "text/x-special"904 return resp905906 resp = client.get("/")907 assert resp.mimetype == "text/x-special"908 assert resp.data == b"internal server error"909910911def test_baseexception_error_handling(app, client):912 app.testing = False913914 @app.route("/")915 def broken_func():916 raise KeyboardInterrupt()917918 with pytest.raises(KeyboardInterrupt):919 client.get("/")920921 ctx = flask._request_ctx_stack.top922 assert ctx.preserved923 assert type(ctx._preserved_exc) is KeyboardInterrupt924925926def test_before_request_and_routing_errors(app, client):927 @app.before_request928 def attach_something():929 flask.g.something = "value"930931 @app.errorhandler(404)932 def return_something(error):933 return flask.g.something, 404934935 rv = client.get("/")936 assert rv.status_code == 404937 assert rv.data == b"value"938939940def test_user_error_handling(app, client):941 class MyException(Exception):942 pass943944 @app.errorhandler(MyException)945 def handle_my_exception(e):946 assert isinstance(e, MyException)947 return "42"948949 @app.route("/")950 def index():951 raise MyException()952953 assert client.get("/").data == b"42"954955956def test_http_error_subclass_handling(app, client):957 class ForbiddenSubclass(Forbidden):958 pass959960 @app.errorhandler(ForbiddenSubclass)961 def handle_forbidden_subclass(e):962 assert isinstance(e, ForbiddenSubclass)963 return "banana"964965 @app.errorhandler(403)966 def handle_forbidden_subclass(e):967 assert not isinstance(e, ForbiddenSubclass)968 assert isinstance(e, Forbidden)969 return "apple"970971 @app.route("/1")972 def index1():973 raise ForbiddenSubclass()974975 @app.route("/2")976 def index2():977 flask.abort(403)978979 @app.route("/3")980 def index3():981 raise Forbidden()982983 assert client.get("/1").data == b"banana"984 assert client.get("/2").data == b"apple"985 assert client.get("/3").data == b"apple"986987988def test_errorhandler_precedence(app, client):989 class E1(Exception):990 pass991992 class E2(Exception):993 pass994995 class E3(E1, E2):996 pass997998 @app.errorhandler(E2)999 def handle_e2(e):1000 return "E2"10011002 @app.errorhandler(Exception)1003 def handle_exception(e):1004 return "Exception"10051006 @app.route("/E1")1007 def raise_e1():1008 raise E110091010 @app.route("/E3")1011 def raise_e3():1012 raise E310131014 rv = client.get("/E1")1015 assert rv.data == b"Exception"10161017 rv = client.get("/E3")1018 assert rv.data == b"E2"101910201021def test_trapping_of_bad_request_key_errors(app, client):1022 @app.route("/key")1023 def fail():1024 flask.request.form["missing_key"]10251026 @app.route("/abort")1027 def allow_abort():1028 flask.abort(400)10291030 rv = client.get("/key")1031 assert rv.status_code == 4001032 assert b"missing_key" not in rv.data1033 rv = client.get("/abort")1034 assert rv.status_code == 40010351036 app.debug = True1037 with pytest.raises(KeyError) as e:1038 client.get("/key")1039 assert e.errisinstance(BadRequest)1040 assert "missing_key" in e.value.get_description()1041 rv = client.get("/abort")1042 assert rv.status_code == 40010431044 app.debug = False1045 app.config["TRAP_BAD_REQUEST_ERRORS"] = True1046 with pytest.raises(KeyError):1047 client.get("/key")1048 with pytest.raises(BadRequest):1049 client.get("/abort")105010511052def test_trapping_of_all_http_exceptions(app, client):1053 app.config["TRAP_HTTP_EXCEPTIONS"] = True10541055 @app.route("/fail")1056 def fail():1057 flask.abort(404)10581059 with pytest.raises(NotFound):1060 client.get("/fail")106110621063def test_error_handler_after_processor_error(app, client):1064 app.testing = False10651066 @app.before_request1067 def before_request():1068 if trigger == "before":1069 1 // 010701071 @app.after_request1072 def after_request(response):1073 if trigger == "after":1074 1 // 01075 return response10761077 @app.route("/")1078 def index():1079 return "Foo"10801081 @app.errorhandler(500)1082 def internal_server_error(e):1083 return "Hello Server Error", 50010841085 for trigger in "before", "after":1086 rv = client.get("/")1087 assert rv.status_code == 5001088 assert rv.data == b"Hello Server Error"108910901091def test_enctype_debug_helper(app, client):1092 from flask.debughelpers import DebugFilesKeyError10931094 app.debug = True10951096 @app.route("/fail", methods=["POST"])1097 def index():1098 return flask.request.files["foo"].filename10991100 # with statement is important because we leave an exception on the1101 # stack otherwise and we want to ensure that this is not the case1102 # to not negatively affect other tests.1103 with client:1104 with pytest.raises(DebugFilesKeyError) as e:1105 client.post("/fail", data={"foo": "index.txt"})1106 assert "no file contents were transmitted" in str(e.value)1107 assert 'This was submitted: "index.txt"' in str(e.value)110811091110def test_response_types(app, client):1111 @app.route("/text")1112 def from_text():1113 return u"Hällo Wörld"11141115 @app.route("/bytes")1116 def from_bytes():1117 return u"Hällo Wörld".encode("utf-8")11181119 @app.route("/full_tuple")1120 def from_full_tuple():1121 return (1122 "Meh",1123 400,1124 {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1125 )11261127 @app.route("/text_headers")1128 def from_text_headers():1129 return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}11301131 @app.route("/text_status")1132 def from_text_status():1133 return "Hi, status!", 40011341135 @app.route("/response_headers")1136 def from_response_headers():1137 return (1138 flask.Response("Hello world", 404, {"X-Foo": "Baz"}),1139 {"X-Foo": "Bar", "X-Bar": "Foo"},1140 )11411142 @app.route("/response_status")1143 def from_response_status():1144 return app.response_class("Hello world", 400), 50011451146 @app.route("/wsgi")1147 def from_wsgi():1148 return NotFound()11491150 @app.route('/dict')1151 def from_dict():1152 return {"foo": "bar"}, 20111531154 assert client.get('/text').data == u'Hällo Wörld'.encode('utf-8')1155 assert client.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')11561157 rv = client.get("/full_tuple")1158 assert rv.data == b"Meh"1159 assert rv.headers["X-Foo"] == "Testing"1160 assert rv.status_code == 4001161 assert rv.mimetype == "text/plain"11621163 rv = client.get("/text_headers")1164 assert rv.data == b"Hello"1165 assert rv.headers["X-Foo"] == "Test"1166 assert rv.status_code == 2001167 assert rv.mimetype == "text/plain"11681169 rv = client.get("/text_status")1170 assert rv.data == b"Hi, status!"1171 assert rv.status_code == 4001172 assert rv.mimetype == "text/html"11731174 rv = client.get("/response_headers")1175 assert rv.data == b"Hello world"1176 assert rv.headers.getlist("X-Foo") == ["Baz", "Bar"]1177 assert rv.headers["X-Bar"] == "Foo"1178 assert rv.status_code == 40411791180 rv = client.get("/response_status")1181 assert rv.data == b"Hello world"1182 assert rv.status_code == 50011831184 rv = client.get("/wsgi")1185 assert b"Not Found" in rv.data1186 assert rv.status_code == 40411871188 rv = client.get('/dict')1189 assert rv.json == {"foo": "bar"}1190 assert rv.status_code == 201119111921193def test_response_type_errors():1194 app = flask.Flask(__name__)1195 app.testing = True11961197 @app.route("/none")1198 def from_none():1199 pass12001201 @app.route("/small_tuple")1202 def from_small_tuple():1203 return ("Hello",)12041205 @app.route("/large_tuple")1206 def from_large_tuple():1207 return "Hello", 234, {"X-Foo": "Bar"}, "???"12081209 @app.route("/bad_type")1210 def from_bad_type():1211 return True12121213 @app.route("/bad_wsgi")1214 def from_bad_wsgi():1215 return lambda: None12161217 c = app.test_client()12181219 with pytest.raises(TypeError) as e:1220 c.get("/none")1221 assert "returned None" in str(e)12221223 with pytest.raises(TypeError) as e:1224 c.get("/small_tuple")1225 assert "tuple must have the form" in str(e)12261227 pytest.raises(TypeError, c.get, "/large_tuple")12281229 with pytest.raises(TypeError) as e:1230 c.get("/bad_type")1231 assert "it was a bool" in str(e)12321233 pytest.raises(TypeError, c.get, "/bad_wsgi")123412351236def test_make_response(app, req_ctx):1237 rv = flask.make_response()1238 assert rv.status_code == 2001239 assert rv.data == b""1240 assert rv.mimetype == "text/html"12411242 rv = flask.make_response("Awesome")1243 assert rv.status_code == 2001244 assert rv.data == b"Awesome"1245 assert rv.mimetype == "text/html"12461247 rv = flask.make_response("W00t", 404)1248 assert rv.status_code == 4041249 assert rv.data == b"W00t"1250 assert rv.mimetype == "text/html"125112521253def test_make_response_with_response_instance(app, req_ctx):1254 rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1255 assert rv.status_code == 4001256 assert rv.data == b'{"msg":"W00t"}\n'1257 assert rv.mimetype == "application/json"12581259 rv = flask.make_response(flask.Response(""), 400)1260 assert rv.status_code == 4001261 assert rv.data == b""1262 assert rv.mimetype == "text/html"12631264 rv = flask.make_response(1265 flask.Response("", headers={"Content-Type": "text/html"}),1266 400,1267 [("X-Foo", "bar")],1268 )1269 assert rv.status_code == 4001270 assert rv.headers["Content-Type"] == "text/html"1271 assert rv.headers["X-Foo"] == "bar"127212731274def test_jsonify_no_prettyprint(app, req_ctx):1275 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1276 compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1277 uncompressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}12781279 rv = flask.make_response(flask.jsonify(uncompressed_msg), 200)1280 assert rv.data == compressed_msg128112821283def test_jsonify_prettyprint(app, req_ctx):1284 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1285 compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1286 pretty_response = (1287 b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'1288 )12891290 rv = flask.make_response(flask.jsonify(compressed_msg), 200)1291 assert rv.data == pretty_response129212931294def test_jsonify_mimetype(app, req_ctx):1295 app.config.update({"JSONIFY_MIMETYPE": "application/vnd.api+json"})1296 msg = {"msg": {"submsg": "W00t"}}1297 rv = flask.make_response(flask.jsonify(msg), 200)1298 assert rv.mimetype == "application/vnd.api+json"129913001301@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")1302def test_json_dump_dataclass(app, req_ctx):1303 from dataclasses import make_dataclass1304 Data = make_dataclass("Data", [("name", str)])1305 value = flask.json.dumps(Data("Flask"), app=app)1306 value = flask.json.loads(value, app=app)1307 assert value == {"name": "Flask"}13081309def test_jsonify_args_and_kwargs_check(app, req_ctx):1310 with pytest.raises(TypeError) as e:1311 flask.jsonify("fake args", kwargs="fake")1312 assert "behavior undefined" in str(e.value)131313141315def test_url_generation(app, req_ctx):1316 @app.route("/hello/<name>", methods=["POST"])1317 def hello():1318 pass13191320 assert flask.url_for("hello", name="test x") == "/hello/test%20x"1321 assert (1322 flask.url_for("hello", name="test x", _external=True)1323 == "http://localhost/hello/test%20x"1324 )132513261327def test_build_error_handler(app):1328 # Test base case, a URL which results in a BuildError.1329 with app.test_request_context():1330 pytest.raises(BuildError, flask.url_for, "spam")13311332 # Verify the error is re-raised if not the current exception.1333 try:1334 with app.test_request_context():1335 flask.url_for("spam")1336 except BuildError as err:1337 error = err1338 try:1339 raise RuntimeError("Test case where BuildError is not current.")1340 except RuntimeError:1341 pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})13421343 # Test a custom handler.1344 def handler(error, endpoint, values):1345 # Just a test.1346 return "/test_handler/"13471348 app.url_build_error_handlers.append(handler)1349 with app.test_request_context():1350 assert flask.url_for("spam") == "/test_handler/"135113521353def test_build_error_handler_reraise(app):1354 # Test a custom handler which reraises the BuildError1355 def handler_raises_build_error(error, endpoint, values):1356 raise error13571358 app.url_build_error_handlers.append(handler_raises_build_error)13591360 with app.test_request_context():1361 pytest.raises(BuildError, flask.url_for, "not.existing")136213631364def test_url_for_passes_special_values_to_build_error_handler(app):1365 @app.url_build_error_handlers.append1366 def handler(error, endpoint, values):1367 assert values == {1368 "_external": False,1369 "_anchor": None,1370 "_method": None,1371 "_scheme": None,1372 }1373 return "handled"13741375 with app.test_request_context():1376 flask.url_for("/")137713781379def test_custom_converters(app, client):1380 from werkzeug.routing import BaseConverter13811382 class ListConverter(BaseConverter):1383 def to_python(self, value):1384 return value.split(",")13851386 def to_url(self, value):1387 base_to_url = super(ListConverter, self).to_url1388 return ",".join(base_to_url(x) for x in value)13891390 app.url_map.converters["list"] = ListConverter13911392 @app.route("/<list:args>")1393 def index(args):1394 return "|".join(args)13951396 assert client.get("/1,2,3").data == b"1|2|3"139713981399def test_static_files(app, client):1400 rv = client.get("/static/index.html")1401 assert rv.status_code == 2001402 assert rv.data.strip() == b"<h1>Hello World!</h1>"1403 with app.test_request_context():1404 assert flask.url_for("static", filename="index.html") == "/static/index.html"1405 rv.close()140614071408def test_static_url_path():1409 app = flask.Flask(__name__, static_url_path="/foo")1410 app.testing = True1411 rv = app.test_client().get("/foo/index.html")1412 assert rv.status_code == 2001413 rv.close()14141415 with app.test_request_context():1416 assert flask.url_for("static", filename="index.html") == "/foo/index.html"141714181419def test_static_url_path_with_ending_slash():1420 app = flask.Flask(__name__, static_url_path="/foo/")1421 app.testing = True1422 rv = app.test_client().get("/foo/index.html")1423 assert rv.status_code == 2001424 rv.close()14251426 with app.test_request_context():1427 assert flask.url_for("static", filename="index.html") == "/foo/index.html"142814291430def test_static_url_null_path(app):1431 app = flask.Flask(__name__, static_folder='', static_url_path='')1432 rv = app.test_client().open('/static/index.html', method='GET')1433 assert rv.status_code == 2001434 rv.close()143514361437def test_static_url_null_path_defaulting(app):1438 app = flask.Flask(__name__, static_folder='')1439 rv = app.test_client().open('/static/index.html', method='GET')1440 assert rv.status_code == 2001441 rv.close()144214431444def test_static_route_with_host_matching():1445 app = flask.Flask(__name__, host_matching=True, static_host="example.com")1446 c = app.test_client()1447 rv = c.get("http://example.com/static/index.html")1448 assert rv.status_code == 2001449 rv.close()1450 with app.test_request_context():1451 rv = flask.url_for("static", filename="index.html", _external=True)1452 assert rv == "http://example.com/static/index.html"1453 # Providing static_host without host_matching=True should error.1454 with pytest.raises(Exception):1455 flask.Flask(__name__, static_host="example.com")1456 # Providing host_matching=True with static_folder but without static_host should error.1457 with pytest.raises(Exception):1458 flask.Flask(__name__, host_matching=True)1459 # Providing host_matching=True without static_host but with static_folder=None should not error.1460 flask.Flask(__name__, host_matching=True, static_folder=None)146114621463def test_request_locals():1464 assert repr(flask.g) == "<LocalProxy unbound>"1465 assert not flask.g146614671468def test_test_app_proper_environ():1469 app = flask.Flask(__name__, subdomain_matching=True)1470 app.config.update(SERVER_NAME="localhost.localdomain:5000")1471 client = app.test_client()14721473 @app.route("/")1474 def index():1475 return "Foo"14761477 @app.route("/", subdomain="foo")1478 def subdomain():1479 return "Foo SubDomain"14801481 rv = client.get("/")1482 assert rv.data == b"Foo"14831484 rv = client.get("/", "http://localhost.localdomain:5000")1485 assert rv.data == b"Foo"14861487 rv = client.get("/", "https://localhost.localdomain:5000")1488 assert rv.data == b"Foo"14891490 app.config.update(SERVER_NAME="localhost.localdomain")1491 rv = client.get("/", "https://localhost.localdomain")1492 assert rv.data == b"Foo"14931494 try:1495 app.config.update(SERVER_NAME="localhost.localdomain:443")1496 rv = client.get("/", "https://localhost.localdomain")1497 # Werkzeug 0.81498 assert rv.status_code == 4041499 except ValueError as e:1500 # Werkzeug 0.71501 assert str(e) == (1502 "the server name provided "1503 "('localhost.localdomain:443') does not match the "1504 "server name from the WSGI environment ('localhost.localdomain')"1505 )15061507 try:1508 app.config.update(SERVER_NAME="localhost.localdomain")1509 rv = client.get("/", "http://foo.localhost")1510 # Werkzeug 0.81511 assert rv.status_code == 4041512 except ValueError as e:1513 # Werkzeug 0.71514 assert str(e) == (1515 "the server name provided "1516 "('localhost.localdomain') does not match the "1517 "server name from the WSGI environment ('foo.localhost')"1518 )15191520 rv = client.get("/", "http://foo.localhost.localdomain")1521 assert rv.data == b"Foo SubDomain"152215231524def test_exception_propagation(app, client):1525 def apprunner(config_key):1526 @app.route("/")1527 def index():1528 1 // 015291530 if config_key is not None:1531 app.config[config_key] = True1532 with pytest.raises(Exception):1533 client.get("/")1534 else:1535 assert client.get("/").status_code == 50015361537 # we have to run this test in an isolated thread because if the1538 # debug flag is set to true and an exception happens the context is1539 # not torn down. This causes other tests that run after this fail1540 # when they expect no exception on the stack.1541 for config_key in "TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None:1542 t = Thread(target=apprunner, args=(config_key,))1543 t.start()1544 t.join()154515461547@pytest.mark.parametrize("debug", [True, False])1548@pytest.mark.parametrize("use_debugger", [True, False])1549@pytest.mark.parametrize("use_reloader", [True, False])1550@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1551def test_werkzeug_passthrough_errors(1552 monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1553):1554 rv = {}15551556 # Mocks werkzeug.serving.run_simple method1557 def run_simple_mock(*args, **kwargs):1558 rv["passthrough_errors"] = kwargs.get("passthrough_errors")15591560 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1561 app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1562 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)156315641565def test_max_content_length(app, client):1566 app.config["MAX_CONTENT_LENGTH"] = 6415671568 @app.before_request1569 def always_first():1570 flask.request.form["myfile"]1571 assert False15721573 @app.route("/accept", methods=["POST"])1574 def accept_file():1575 flask.request.form["myfile"]1576 assert False15771578 @app.errorhandler(413)1579 def catcher(error):1580 return "42"15811582 rv = client.post("/accept", data={"myfile": "foo" * 100})1583 assert rv.data == b"42"158415851586def test_url_processors(app, client):1587 @app.url_defaults1588 def add_language_code(endpoint, values):1589 if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1590 endpoint, "lang_code"1591 ):1592 values.setdefault("lang_code", flask.g.lang_code)15931594 @app.url_value_preprocessor1595 def pull_lang_code(endpoint, values):1596 flask.g.lang_code = values.pop("lang_code", None)15971598 @app.route("/<lang_code>/")1599 def index():1600 return flask.url_for("about")16011602 @app.route("/<lang_code>/about")1603 def about():1604 return flask.url_for("something_else")16051606 @app.route("/foo")1607 def something_else():1608 return flask.url_for("about", lang_code="en")16091610 assert client.get("/de/").data == b"/de/about"1611 assert client.get("/de/about").data == b"/foo"1612 assert client.get("/foo").data == b"/en/about"161316141615def test_inject_blueprint_url_defaults(app):1616 bp = flask.Blueprint("foo.bar.baz", __name__, template_folder="template")16171618 @bp.url_defaults1619 def bp_defaults(endpoint, values):1620 values["page"] = "login"16211622 @bp.route("/<page>")1623 def view(page):1624 pass16251626 app.register_blueprint(bp)16271628 values = dict()1629 app.inject_url_defaults("foo.bar.baz.view", values)1630 expected = dict(page="login")1631 assert values == expected16321633 with app.test_request_context("/somepage"):1634 url = flask.url_for("foo.bar.baz.view")1635 expected = "/login"1636 assert url == expected163716381639def test_nonascii_pathinfo(app, client):1640 @app.route(u"/киртест")1641 def index():1642 return "Hello World!"16431644 rv = client.get(u"/киртест")1645 assert rv.data == b"Hello World!"164616471648def test_debug_mode_complains_after_first_request(app, client):1649 app.debug = True16501651 @app.route("/")1652 def index():1653 return "Awesome"16541655 assert not app.got_first_request1656 assert client.get("/").data == b"Awesome"1657 with pytest.raises(AssertionError) as e:16581659 @app.route("/foo")1660 def broken():1661 return "Meh"16621663 assert "A setup function was called" in str(e)16641665 app.debug = False16661667 @app.route("/foo")1668 def working():1669 return "Meh"16701671 assert client.get("/foo").data == b"Meh"1672 assert app.got_first_request167316741675def test_before_first_request_functions(app, client):1676 got = []16771678 @app.before_first_request1679 def foo():1680 got.append(42)16811682 client.get("/")1683 assert got == [42]1684 client.get("/")1685 assert got == [42]1686 assert app.got_first_request168716881689def test_before_first_request_functions_concurrent(app, client):1690 got = []16911692 @app.before_first_request1693 def foo():1694 time.sleep(0.2)1695 got.append(42)16961697 def get_and_assert():1698 client.get("/")1699 assert got == [42]17001701 t = Thread(target=get_and_assert)1702 t.start()1703 get_and_assert()1704 t.join()1705 assert app.got_first_request170617071708def test_routing_redirect_debugging(app, client):1709 app.debug = True17101711 @app.route("/foo/", methods=["GET", "POST"])1712 def foo():1713 return "success"17141715 with client:1716 with pytest.raises(AssertionError) as e:1717 client.post("/foo", data={})1718 assert "http://localhost/foo/" in str(e)1719 assert ("Make sure to directly send " "your POST-request to this URL") in str(e)17201721 rv = client.get("/foo", data={}, follow_redirects=True)1722 assert rv.data == b"success"17231724 app.debug = False1725 with client:1726 rv = client.post("/foo", data={}, follow_redirects=True)1727 assert rv.data == b"success"172817291730def test_route_decorator_custom_endpoint(app, client):1731 app.debug = True17321733 @app.route("/foo/")1734 def foo():1735 return flask.request.endpoint17361737 @app.route("/bar/", endpoint="bar")1738 def for_bar():1739 return flask.request.endpoint17401741 @app.route("/bar/123", endpoint="123")1742 def for_bar_foo():1743 return flask.request.endpoint17441745 with app.test_request_context():1746 assert flask.url_for("foo") == "/foo/"1747 assert flask.url_for("bar") == "/bar/"1748 assert flask.url_for("123") == "/bar/123"17491750 assert client.get("/foo/").data == b"foo"1751 assert client.get("/bar/").data == b"bar"1752 assert client.get("/bar/123").data == b"123"175317541755def test_preserve_only_once(app, client):1756 app.debug = True17571758 @app.route("/fail")1759 def fail_func():1760 1 // 017611762 for x in range(3):1763 with pytest.raises(ZeroDivisionError):1764 client.get("/fail")17651766 assert flask._request_ctx_stack.top is not None1767 assert flask._app_ctx_stack.top is not None1768 # implicit appctx disappears too1769 flask._request_ctx_stack.top.pop()1770 assert flask._request_ctx_stack.top is None1771 assert flask._app_ctx_stack.top is None177217731774def test_preserve_remembers_exception(app, client):1775 app.debug = True1776 errors = []17771778 @app.route("/fail")1779 def fail_func():1780 1 // 017811782 @app.route("/success")1783 def success_func():1784 return "Okay"17851786 @app.teardown_request1787 def teardown_handler(exc):1788 errors.append(exc)17891790 # After this failure we did not yet call the teardown handler1791 with pytest.raises(ZeroDivisionError):1792 client.get("/fail")1793 assert errors == []17941795 # But this request triggers it, and it's an error1796 client.get("/success")1797 assert len(errors) == 21798 assert isinstance(errors[0], ZeroDivisionError)17991800 # At this point another request does nothing.1801 client.get("/success")1802 assert len(errors) == 31803 assert errors[1] is None180418051806def test_get_method_on_g(app_ctx):1807 assert flask.g.get("x") is None1808 assert flask.g.get("x", 11) == 111809 flask.g.x = 421810 assert flask.g.get("x") == 421811 assert flask.g.x == 42181218131814def test_g_iteration_protocol(app_ctx):1815 flask.g.foo = 231816 flask.g.bar = 421817 assert "foo" in flask.g1818 assert "foos" not in flask.g1819 assert sorted(flask.g) == ["bar", "foo"]182018211822def test_subdomain_basic_support():1823 app = flask.Flask(__name__, subdomain_matching=True)1824 app.config["SERVER_NAME"] = "localhost.localdomain"1825 client = app.test_client()18261827 @app.route("/")1828 def normal_index():1829 return "normal index"18301831 @app.route("/", subdomain="test")1832 def test_index():1833 return "test index"18341835 rv = client.get("/", "http://localhost.localdomain/")1836 assert rv.data == b"normal index"18371838 rv = client.get("/", "http://test.localhost.localdomain/")1839 assert rv.data == b"test index"184018411842def test_subdomain_matching():1843 app = flask.Flask(__name__, subdomain_matching=True)1844 client = app.test_client()1845 app.config["SERVER_NAME"] = "localhost.localdomain"18461847 @app.route("/", subdomain="<user>")1848 def index(user):1849 return "index for %s" % user18501851 rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1852 assert rv.data == b"index for mitsuhiko"185318541855def test_subdomain_matching_with_ports():1856 app = flask.Flask(__name__, subdomain_matching=True)1857 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1858 client = app.test_client()18591860 @app.route("/", subdomain="<user>")1861 def index(user):1862 return "index for %s" % user18631864 rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1865 assert rv.data == b"index for mitsuhiko"186618671868@pytest.mark.parametrize("matching", (False, True))1869def test_subdomain_matching_other_name(matching):1870 app = flask.Flask(__name__, subdomain_matching=matching)1871 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1872 client = app.test_client()18731874 @app.route("/")1875 def index():1876 return "", 20418771878 # ip address can't match name1879 rv = client.get("/", "http://127.0.0.1:3000/")1880 assert rv.status_code == 404 if matching else 20418811882 # allow all subdomains if matching is disabled1883 rv = client.get("/", "http://www.localhost.localdomain:3000/")1884 assert rv.status_code == 404 if matching else 204188518861887def test_multi_route_rules(app, client):1888 @app.route("/")1889 @app.route("/<test>/")1890 def index(test="a"):1891 return test18921893 rv = client.open("/")1894 assert rv.data == b"a"1895 rv = client.open("/b/")1896 assert rv.data == b"b"189718981899def test_multi_route_class_views(app, client):1900 class View(object):1901 def __init__(self, app):1902 app.add_url_rule("/", "index", self.index)1903 app.add_url_rule("/<test>/", "index", self.index)19041905 def index(self, test="a"):1906 return test19071908 _ = View(app)1909 rv = client.open("/")1910 assert rv.data == b"a"1911 rv = client.open("/b/")1912 assert rv.data == b"b"191319141915def test_run_defaults(monkeypatch, app):1916 rv = {}19171918 # Mocks werkzeug.serving.run_simple method1919 def run_simple_mock(*args, **kwargs):1920 rv["result"] = "running..."19211922 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1923 app.run()1924 assert rv["result"] == "running..."192519261927def test_run_server_port(monkeypatch, app):1928 rv = {}19291930 # Mocks werkzeug.serving.run_simple method1931 def run_simple_mock(hostname, port, application, *args, **kwargs):1932 rv["result"] = "running on %s:%s ..." % (hostname, port)19331934 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1935 hostname, port = "localhost", 80001936 app.run(hostname, port, debug=True)1937 assert rv["result"] == "running on %s:%s ..." % (hostname, port)193819391940@pytest.mark.parametrize(1941 "host,port,server_name,expect_host,expect_port",1942 (1943 (None, None, "pocoo.org:8080", "pocoo.org", 8080),1944 ("localhost", None, "pocoo.org:8080", "localhost", 8080),1945 (None, 80, "pocoo.org:8080", "pocoo.org", 80),1946 ("localhost", 80, "pocoo.org:8080", "localhost", 80),1947 ("localhost", 0, "localhost:8080", "localhost", 0),1948 (None, None, "localhost:8080", "localhost", 8080),1949 (None, None, "localhost:0", "localhost", 0),1950 ),1951)1952def test_run_from_config(monkeypatch, host, port, server_name, expect_host, expect_port, app):1953 def run_simple_mock(hostname, port, *args, **kwargs):1954 assert hostname == expect_host1955 assert port == expect_port19561957 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1958 app.config["SERVER_NAME"] = server_name1959 app.run(host, port)196019611962def test_max_cookie_size(app, client, recwarn):1963 app.config["MAX_COOKIE_SIZE"] = 10019641965 # outside app context, default to Werkzeug static value,1966 # which is also the default config1967 response = flask.Response()1968 default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1969 assert response.max_cookie_size == default19701971 # inside app context, use app config1972 with app.app_context():1973 assert flask.Response().max_cookie_size == 10019741975 @app.route("/")1976 def index():1977 r = flask.Response("", status=204)1978 r.set_cookie("foo", "bar" * 100)1979 return r19801981 client.get("/")1982 assert len(recwarn) == 11983 w = recwarn.pop()1984 assert "cookie is too large" in str(w.message)19851986 app.config["MAX_COOKIE_SIZE"] = 019871988 client.get("/")1989 assert len(recwarn) == 0