Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

2,036 lines · 54.7 KiB · Python

Last changed by

Merge pull request #4555 from pallets/pytest_raises_cleanupDavid Lordbefore adoptiona0bb10b

History of this file

Take it

The walk stopped after 200 commits: lines older than bbb273b point at it.

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 1–4why, one step back
1import gc
2import re3import time4import uuid

Merge branch '2.0.x'David Lordbefore adoptione37e871

line 5why, one step back
5import warnings

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 6–17why, one step back
6import weakref
7from datetime import datetime8from platform import python_implementation9from threading import Thread1011import pytest12import werkzeug.serving13from werkzeug.exceptions import BadRequest14from werkzeug.exceptions import Forbidden15from werkzeug.exceptions import NotFound16from werkzeug.http import parse_date17from werkzeug.routing import BuildError

Merge pull request #4492 from pallets/debug-messagesDavid Lordbefore adoptionce7b884

line 18why, one step back
18from werkzeug.routing import RequestRedirect

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 19–51why, one step back
19
20import flask212223require_cpython_gc = pytest.mark.skipif(24 python_implementation() != "CPython",25 reason="Requires CPython GC behavior",26)272829def 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"]5051

Merge pull request #3907 from pgjones/sugarDavid Lordbefore adoption5fea7ca

lines 52–68why, one step back
52@pytest.mark.parametrize("method", ["get", "post", "put", "delete", "patch"])
53def test_method_route(app, client, method):54 method_route = getattr(app, method)55 client_method = getattr(client, method)5657 @method_route("/")58 def hello():59 return "Hello"6061 assert client_method("/").data == b"Hello"626364def test_method_route_no_methods(app):65 with pytest.raises(TypeError):66 app.get("/", methods=["GET", "POST"])6768

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 69–152why, one step back
69def test_provide_automatic_options_attr():
70 app = flask.Flask(__name__)7172 def index():73 return "Hello World!"7475 index.provide_automatic_options = False76 app.route("/")(index)77 rv = app.test_client().open("/", method="OPTIONS")78 assert rv.status_code == 4057980 app = flask.Flask(__name__)8182 def index2():83 return "Hello World!"8485 index2.provide_automatic_options = True86 app.route("/", methods=["OPTIONS"])(index2)87 rv = app.test_client().open("/", method="OPTIONS")88 assert sorted(rv.allow) == ["OPTIONS"]899091def test_provide_automatic_options_kwarg(app, client):92 def index():93 return flask.request.method9495 def more():96 return flask.request.method9798 app.add_url_rule("/", view_func=index, provide_automatic_options=False)99 app.add_url_rule(100 "/more",101 view_func=more,102 methods=["GET", "POST"],103 provide_automatic_options=False,104 )105 assert client.get("/").data == b"GET"106107 rv = client.post("/")108 assert rv.status_code == 405109 assert sorted(rv.allow) == ["GET", "HEAD"]110111 rv = client.open("/", method="OPTIONS")112 assert rv.status_code == 405113114 rv = client.head("/")115 assert rv.status_code == 200116 assert not rv.data # head truncates117 assert client.post("/more").data == b"POST"118 assert client.get("/more").data == b"GET"119120 rv = client.delete("/more")121 assert rv.status_code == 405122 assert sorted(rv.allow) == ["GET", "HEAD", "POST"]123124 rv = client.open("/more", method="OPTIONS")125 assert rv.status_code == 405126127128def test_request_dispatching(app, client):129 @app.route("/")130 def index():131 return flask.request.method132133 @app.route("/more", methods=["GET", "POST"])134 def more():135 return flask.request.method136137 assert client.get("/").data == b"GET"138 rv = client.post("/")139 assert rv.status_code == 405140 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]141 rv = client.head("/")142 assert rv.status_code == 200143 assert not rv.data # head truncates144 assert client.post("/more").data == b"POST"145 assert client.get("/more").data == b"GET"146 rv = client.delete("/more")147 assert rv.status_code == 405148 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]149150151def test_disallow_string_for_allowed_methods(app):152 with pytest.raises(TypeError):

Merge pull request #4555 from pallets/pytest_raises_cleanupDavid Lordbefore adoptiona0bb10b

line 153why, one step back
153 app.add_url_rule("/", methods="GET POST", endpoint="test")

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 154–936why, one step back
154
155156def test_url_mapping(app, client):157 random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"158159 def index():160 return flask.request.method161162 def more():163 return flask.request.method164165 def options():166 return random_uuid4167168 app.add_url_rule("/", "index", index)169 app.add_url_rule("/more", "more", more, methods=["GET", "POST"])170171 # Issue 1288: Test that automatic options are not added172 # when non-uppercase 'options' in methods173 app.add_url_rule("/options", "options", options, methods=["options"])174175 assert client.get("/").data == b"GET"176 rv = client.post("/")177 assert rv.status_code == 405178 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]179 rv = client.head("/")180 assert rv.status_code == 200181 assert not rv.data # head truncates182 assert client.post("/more").data == b"POST"183 assert client.get("/more").data == b"GET"184 rv = client.delete("/more")185 assert rv.status_code == 405186 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]187 rv = client.open("/options", method="OPTIONS")188 assert rv.status_code == 200189 assert random_uuid4 in rv.data.decode("utf-8")190191192def test_werkzeug_routing(app, client):193 from werkzeug.routing import Submount, Rule194195 app.url_map.add(196 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])197 )198199 def bar():200 return "bar"201202 def index():203 return "index"204205 app.view_functions["bar"] = bar206 app.view_functions["index"] = index207208 assert client.get("/foo/").data == b"index"209 assert client.get("/foo/bar").data == b"bar"210211212def test_endpoint_decorator(app, client):213 from werkzeug.routing import Submount, Rule214215 app.url_map.add(216 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])217 )218219 @app.endpoint("bar")220 def bar():221 return "bar"222223 @app.endpoint("index")224 def index():225 return "index"226227 assert client.get("/foo/").data == b"index"228 assert client.get("/foo/bar").data == b"bar"229230231def test_session(app, client):232 @app.route("/set", methods=["POST"])233 def set():234 assert not flask.session.accessed235 assert not flask.session.modified236 flask.session["value"] = flask.request.form["value"]237 assert flask.session.accessed238 assert flask.session.modified239 return "value set"240241 @app.route("/get")242 def get():243 assert not flask.session.accessed244 assert not flask.session.modified245 v = flask.session.get("value", "None")246 assert flask.session.accessed247 assert not flask.session.modified248 return v249250 assert client.post("/set", data={"value": "42"}).data == b"value set"251 assert client.get("/get").data == b"42"252253254def test_session_using_server_name(app, client):255 app.config.update(SERVER_NAME="example.com")256257 @app.route("/")258 def index():259 flask.session["testing"] = 42260 return "Hello World"261262 rv = client.get("/", "http://example.com/")263 assert "domain=.example.com" in rv.headers["set-cookie"].lower()264 assert "httponly" in rv.headers["set-cookie"].lower()265266267def test_session_using_server_name_and_port(app, client):268 app.config.update(SERVER_NAME="example.com:8080")269270 @app.route("/")271 def index():272 flask.session["testing"] = 42273 return "Hello World"274275 rv = client.get("/", "http://example.com:8080/")276 assert "domain=.example.com" in rv.headers["set-cookie"].lower()277 assert "httponly" in rv.headers["set-cookie"].lower()278279280def test_session_using_server_name_port_and_path(app, client):281 app.config.update(SERVER_NAME="example.com:8080", APPLICATION_ROOT="/foo")282283 @app.route("/")284 def index():285 flask.session["testing"] = 42286 return "Hello World"287288 rv = client.get("/", "http://example.com:8080/foo")289 assert "domain=example.com" in rv.headers["set-cookie"].lower()290 assert "path=/foo" in rv.headers["set-cookie"].lower()291 assert "httponly" in rv.headers["set-cookie"].lower()292293294def test_session_using_application_root(app, client):295 class PrefixPathMiddleware:296 def __init__(self, app, prefix):297 self.app = app298 self.prefix = prefix299300 def __call__(self, environ, start_response):301 environ["SCRIPT_NAME"] = self.prefix302 return self.app(environ, start_response)303304 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, "/bar")305 app.config.update(APPLICATION_ROOT="/bar")306307 @app.route("/")308 def index():309 flask.session["testing"] = 42310 return "Hello World"311312 rv = client.get("/", "http://example.com:8080/")313 assert "path=/bar" in rv.headers["set-cookie"].lower()314315316def test_session_using_session_settings(app, client):317 app.config.update(318 SERVER_NAME="www.example.com:8080",319 APPLICATION_ROOT="/test",320 SESSION_COOKIE_DOMAIN=".example.com",321 SESSION_COOKIE_HTTPONLY=False,322 SESSION_COOKIE_SECURE=True,323 SESSION_COOKIE_SAMESITE="Lax",324 SESSION_COOKIE_PATH="/",325 )326327 @app.route("/")328 def index():329 flask.session["testing"] = 42330 return "Hello World"331332 rv = client.get("/", "http://www.example.com:8080/test/")333 cookie = rv.headers["set-cookie"].lower()334 assert "domain=.example.com" in cookie335 assert "path=/" in cookie336 assert "secure" in cookie337 assert "httponly" not in cookie338 assert "samesite" in cookie339340 @app.route("/clear")341 def clear():342 flask.session.pop("testing", None)343 return "Goodbye World"344345 rv = client.get("/clear", "http://www.example.com:8080/test/")346 cookie = rv.headers["set-cookie"].lower()347 assert "session=;" in cookie348 assert "domain=.example.com" in cookie349 assert "path=/" in cookie350 assert "secure" in cookie351 assert "samesite" in cookie352353354def test_session_using_samesite_attribute(app, client):355 @app.route("/")356 def index():357 flask.session["testing"] = 42358 return "Hello World"359360 app.config.update(SESSION_COOKIE_SAMESITE="invalid")361362 with pytest.raises(ValueError):363 client.get("/")364365 app.config.update(SESSION_COOKIE_SAMESITE=None)366 rv = client.get("/")367 cookie = rv.headers["set-cookie"].lower()368 assert "samesite" not in cookie369370 app.config.update(SESSION_COOKIE_SAMESITE="Strict")371 rv = client.get("/")372 cookie = rv.headers["set-cookie"].lower()373 assert "samesite=strict" in cookie374375 app.config.update(SESSION_COOKIE_SAMESITE="Lax")376 rv = client.get("/")377 cookie = rv.headers["set-cookie"].lower()378 assert "samesite=lax" in cookie379380381def test_session_localhost_warning(recwarn, app, client):382 app.config.update(SERVER_NAME="localhost:5000")383384 @app.route("/")385 def index():386 flask.session["testing"] = 42387 return "testing"388389 rv = client.get("/", "http://localhost:5000/")390 assert "domain" not in rv.headers["set-cookie"].lower()391 w = recwarn.pop(UserWarning)392 assert "'localhost' is not a valid cookie domain" in str(w.message)393394395def test_session_ip_warning(recwarn, app, client):396 app.config.update(SERVER_NAME="127.0.0.1:5000")397398 @app.route("/")399 def index():400 flask.session["testing"] = 42401 return "testing"402403 rv = client.get("/", "http://127.0.0.1:5000/")404 assert "domain=127.0.0.1" in rv.headers["set-cookie"].lower()405 w = recwarn.pop(UserWarning)406 assert "cookie domain is an IP" in str(w.message)407408409def test_missing_session(app):410 app.secret_key = None411412 def expect_exception(f, *args, **kwargs):413 e = pytest.raises(RuntimeError, f, *args, **kwargs)414 assert e.value.args and "session is unavailable" in e.value.args[0]415416 with app.test_request_context():417 assert flask.session.get("missing_key") is None418 expect_exception(flask.session.__setitem__, "foo", 42)419 expect_exception(flask.session.pop, "foo")420421422def test_session_expiration(app, client):423 permanent = True424425 @app.route("/")426 def index():427 flask.session["test"] = 42428 flask.session.permanent = permanent429 return ""430431 @app.route("/test")432 def test():433 return str(flask.session.permanent)434435 rv = client.get("/")436 assert "set-cookie" in rv.headers437 match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])438 expires = parse_date(match.group())439 expected = datetime.utcnow() + app.permanent_session_lifetime440 assert expires.year == expected.year441 assert expires.month == expected.month442 assert expires.day == expected.day443444 rv = client.get("/test")445 assert rv.data == b"True"446447 permanent = False448 rv = client.get("/")449 assert "set-cookie" in rv.headers450 match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])451 assert match is None452453454def test_session_stored_last(app, client):455 @app.after_request456 def modify_session(response):457 flask.session["foo"] = 42458 return response459460 @app.route("/")461 def dump_session_contents():462 return repr(flask.session.get("foo"))463464 assert client.get("/").data == b"None"465 assert client.get("/").data == b"42"466467468def test_session_special_types(app, client):469 now = datetime.utcnow().replace(microsecond=0)470 the_uuid = uuid.uuid4()471472 @app.route("/")473 def dump_session_contents():474 flask.session["t"] = (1, 2, 3)475 flask.session["b"] = b"\xff"476 flask.session["m"] = flask.Markup("<html>")477 flask.session["u"] = the_uuid478 flask.session["d"] = now479 flask.session["t_tag"] = {" t": "not-a-tuple"}480 flask.session["di_t_tag"] = {" t__": "not-a-tuple"}481 flask.session["di_tag"] = {" di": "not-a-dict"}482 return "", 204483484 with client:485 client.get("/")486 s = flask.session487 assert s["t"] == (1, 2, 3)488 assert type(s["b"]) == bytes489 assert s["b"] == b"\xff"490 assert type(s["m"]) == flask.Markup491 assert s["m"] == flask.Markup("<html>")492 assert s["u"] == the_uuid493 assert s["d"] == now494 assert s["t_tag"] == {" t": "not-a-tuple"}495 assert s["di_t_tag"] == {" t__": "not-a-tuple"}496 assert s["di_tag"] == {" di": "not-a-dict"}497498499def test_session_cookie_setting(app):500 is_permanent = True501502 @app.route("/bump")503 def bump():504 rv = flask.session["foo"] = flask.session.get("foo", 0) + 1505 flask.session.permanent = is_permanent506 return str(rv)507508 @app.route("/read")509 def read():510 return str(flask.session.get("foo", 0))511512 def run_test(expect_header):513 with app.test_client() as c:514 assert c.get("/bump").data == b"1"515 assert c.get("/bump").data == b"2"516 assert c.get("/bump").data == b"3"517518 rv = c.get("/read")519 set_cookie = rv.headers.get("set-cookie")520 assert (set_cookie is not None) == expect_header521 assert rv.data == b"3"522523 is_permanent = True524 app.config["SESSION_REFRESH_EACH_REQUEST"] = True525 run_test(expect_header=True)526527 is_permanent = True528 app.config["SESSION_REFRESH_EACH_REQUEST"] = False529 run_test(expect_header=False)530531 is_permanent = False532 app.config["SESSION_REFRESH_EACH_REQUEST"] = True533 run_test(expect_header=False)534535 is_permanent = False536 app.config["SESSION_REFRESH_EACH_REQUEST"] = False537 run_test(expect_header=False)538539540def test_session_vary_cookie(app, client):541 @app.route("/set")542 def set_session():543 flask.session["test"] = "test"544 return ""545546 @app.route("/get")547 def get():548 return flask.session.get("test")549550 @app.route("/getitem")551 def getitem():552 return flask.session["test"]553554 @app.route("/setdefault")555 def setdefault():556 return flask.session.setdefault("test", "default")557558 @app.route("/vary-cookie-header-set")559 def vary_cookie_header_set():560 response = flask.Response()561 response.vary.add("Cookie")562 flask.session["test"] = "test"563 return response564565 @app.route("/vary-header-set")566 def vary_header_set():567 response = flask.Response()568 response.vary.update(("Accept-Encoding", "Accept-Language"))569 flask.session["test"] = "test"570 return response571572 @app.route("/no-vary-header")573 def no_vary_header():574 return ""575576 def expect(path, header_value="Cookie"):577 rv = client.get(path)578579 if header_value:580 # The 'Vary' key should exist in the headers only once.581 assert len(rv.headers.get_all("Vary")) == 1582 assert rv.headers["Vary"] == header_value583 else:584 assert "Vary" not in rv.headers585586 expect("/set")587 expect("/get")588 expect("/getitem")589 expect("/setdefault")590 expect("/vary-cookie-header-set")591 expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")592 expect("/no-vary-header", None)593594595def test_flashes(app, req_ctx):596 assert not flask.session.modified597 flask.flash("Zap")598 flask.session.modified = False599 flask.flash("Zip")600 assert flask.session.modified601 assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]602603604def test_extended_flashing(app):605 # Be sure app.testing=True below, else tests can fail silently.606 #607 # Specifically, if app.testing is not set to True, the AssertionErrors608 # in the view functions will cause a 500 response to the test client609 # instead of propagating exceptions.610611 @app.route("/")612 def index():613 flask.flash("Hello World")614 flask.flash("Hello World", "error")615 flask.flash(flask.Markup("<em>Testing</em>"), "warning")616 return ""617618 @app.route("/test/")619 def test():620 messages = flask.get_flashed_messages()621 assert list(messages) == [622 "Hello World",623 "Hello World",624 flask.Markup("<em>Testing</em>"),625 ]626 return ""627628 @app.route("/test_with_categories/")629 def test_with_categories():630 messages = flask.get_flashed_messages(with_categories=True)631 assert len(messages) == 3632 assert list(messages) == [633 ("message", "Hello World"),634 ("error", "Hello World"),635 ("warning", flask.Markup("<em>Testing</em>")),636 ]637 return ""638639 @app.route("/test_filter/")640 def test_filter():641 messages = flask.get_flashed_messages(642 category_filter=["message"], with_categories=True643 )644 assert list(messages) == [("message", "Hello World")]645 return ""646647 @app.route("/test_filters/")648 def test_filters():649 messages = flask.get_flashed_messages(650 category_filter=["message", "warning"], with_categories=True651 )652 assert list(messages) == [653 ("message", "Hello World"),654 ("warning", flask.Markup("<em>Testing</em>")),655 ]656 return ""657658 @app.route("/test_filters_without_returning_categories/")659 def test_filters2():660 messages = flask.get_flashed_messages(category_filter=["message", "warning"])661 assert len(messages) == 2662 assert messages[0] == "Hello World"663 assert messages[1] == flask.Markup("<em>Testing</em>")664 return ""665666 # Create new test client on each test to clean flashed messages.667668 client = app.test_client()669 client.get("/")670 client.get("/test_with_categories/")671672 client = app.test_client()673 client.get("/")674 client.get("/test_filter/")675676 client = app.test_client()677 client.get("/")678 client.get("/test_filters/")679680 client = app.test_client()681 client.get("/")682 client.get("/test_filters_without_returning_categories/")683684685def test_request_processing(app, client):686 evts = []687688 @app.before_request689 def before_request():690 evts.append("before")691692 @app.after_request693 def after_request(response):694 response.data += b"|after"695 evts.append("after")696 return response697698 @app.route("/")699 def index():700 assert "before" in evts701 assert "after" not in evts702 return "request"703704 assert "after" not in evts705 rv = client.get("/").data706 assert "after" in evts707 assert rv == b"request|after"708709710def test_request_preprocessing_early_return(app, client):711 evts = []712713 @app.before_request714 def before_request1():715 evts.append(1)716717 @app.before_request718 def before_request2():719 evts.append(2)720 return "hello"721722 @app.before_request723 def before_request3():724 evts.append(3)725 return "bye"726727 @app.route("/")728 def index():729 evts.append("index")730 return "damnit"731732 rv = client.get("/").data.strip()733 assert rv == b"hello"734 assert evts == [1, 2]735736737def test_after_request_processing(app, client):738 @app.route("/")739 def index():740 @flask.after_this_request741 def foo(response):742 response.headers["X-Foo"] = "a header"743 return response744745 return "Test"746747 resp = client.get("/")748 assert resp.status_code == 200749 assert resp.headers["X-Foo"] == "a header"750751752def test_teardown_request_handler(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_debug_mode(app, client):771 called = []772773 @app.teardown_request774 def teardown_request(exc):775 called.append(True)776 return "Ignored"777778 @app.route("/")779 def root():780 return "Response"781782 rv = client.get("/")783 assert rv.status_code == 200784 assert b"Response" in rv.data785 assert len(called) == 1786787788def test_teardown_request_handler_error(app, client):789 called = []790 app.testing = False791792 @app.teardown_request793 def teardown_request1(exc):794 assert type(exc) == ZeroDivisionError795 called.append(True)796 # This raises a new error and blows away sys.exc_info(), so we can797 # test that all teardown_requests get passed the same original798 # exception.799 try:800 raise TypeError()801 except Exception:802 pass803804 @app.teardown_request805 def teardown_request2(exc):806 assert type(exc) == ZeroDivisionError807 called.append(True)808 # This raises a new error and blows away sys.exc_info(), so we can809 # test that all teardown_requests get passed the same original810 # exception.811 try:812 raise TypeError()813 except Exception:814 pass815816 @app.route("/")817 def fails():818 1 // 0819820 rv = client.get("/")821 assert rv.status_code == 500822 assert b"Internal Server Error" in rv.data823 assert len(called) == 2824825826def test_before_after_request_order(app, client):827 called = []828829 @app.before_request830 def before1():831 called.append(1)832833 @app.before_request834 def before2():835 called.append(2)836837 @app.after_request838 def after1(response):839 called.append(4)840 return response841842 @app.after_request843 def after2(response):844 called.append(3)845 return response846847 @app.teardown_request848 def finish1(exc):849 called.append(6)850851 @app.teardown_request852 def finish2(exc):853 called.append(5)854855 @app.route("/")856 def index():857 return "42"858859 rv = client.get("/")860 assert rv.data == b"42"861 assert called == [1, 2, 3, 4, 5, 6]862863864def test_error_handling(app, client):865 app.testing = False866867 @app.errorhandler(404)868 def not_found(e):869 return "not found", 404870871 @app.errorhandler(500)872 def internal_server_error(e):873 return "internal server error", 500874875 @app.errorhandler(Forbidden)876 def forbidden(e):877 return "forbidden", 403878879 @app.route("/")880 def index():881 flask.abort(404)882883 @app.route("/error")884 def error():885 1 // 0886887 @app.route("/forbidden")888 def error2():889 flask.abort(403)890891 rv = client.get("/")892 assert rv.status_code == 404893 assert rv.data == b"not found"894 rv = client.get("/error")895 assert rv.status_code == 500896 assert b"internal server error" == rv.data897 rv = client.get("/forbidden")898 assert rv.status_code == 403899 assert b"forbidden" == rv.data900901902def test_error_handler_unknown_code(app):903 with pytest.raises(KeyError) as exc_info:904 app.register_error_handler(999, lambda e: ("999", 999))905906 assert "Use a subclass" in exc_info.value.args[0]907908909def test_error_handling_processing(app, client):910 app.testing = False911912 @app.errorhandler(500)913 def internal_server_error(e):914 return "internal server error", 500915916 @app.route("/")917 def broken_func():918 1 // 0919920 @app.after_request921 def after_request(resp):922 resp.mimetype = "text/x-special"923 return resp924925 resp = client.get("/")926 assert resp.mimetype == "text/x-special"927 assert resp.data == b"internal server error"928929930def test_baseexception_error_handling(app, client):931 app.testing = False932933 @app.route("/")934 def broken_func():935 raise KeyboardInterrupt()936

Merge pull request #4555 from pallets/pytest_raises_cleanupDavid Lordbefore adoptiona0bb10b

lines 937–939why, one step back
937 with client:
938 with pytest.raises(KeyboardInterrupt):939 client.get("/")

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 940–1244why, one step back
940
941 ctx = flask._request_ctx_stack.top942 assert ctx.preserved943 assert type(ctx._preserved_exc) is KeyboardInterrupt944945946def test_before_request_and_routing_errors(app, client):947 @app.before_request948 def attach_something():949 flask.g.something = "value"950951 @app.errorhandler(404)952 def return_something(error):953 return flask.g.something, 404954955 rv = client.get("/")956 assert rv.status_code == 404957 assert rv.data == b"value"958959960def test_user_error_handling(app, client):961 class MyException(Exception):962 pass963964 @app.errorhandler(MyException)965 def handle_my_exception(e):966 assert isinstance(e, MyException)967 return "42"968969 @app.route("/")970 def index():971 raise MyException()972973 assert client.get("/").data == b"42"974975976def test_http_error_subclass_handling(app, client):977 class ForbiddenSubclass(Forbidden):978 pass979980 @app.errorhandler(ForbiddenSubclass)981 def handle_forbidden_subclass(e):982 assert isinstance(e, ForbiddenSubclass)983 return "banana"984985 @app.errorhandler(403)986 def handle_403(e):987 assert not isinstance(e, ForbiddenSubclass)988 assert isinstance(e, Forbidden)989 return "apple"990991 @app.route("/1")992 def index1():993 raise ForbiddenSubclass()994995 @app.route("/2")996 def index2():997 flask.abort(403)998999 @app.route("/3")1000 def index3():1001 raise Forbidden()10021003 assert client.get("/1").data == b"banana"1004 assert client.get("/2").data == b"apple"1005 assert client.get("/3").data == b"apple"100610071008def test_errorhandler_precedence(app, client):1009 class E1(Exception):1010 pass10111012 class E2(Exception):1013 pass10141015 class E3(E1, E2):1016 pass10171018 @app.errorhandler(E2)1019 def handle_e2(e):1020 return "E2"10211022 @app.errorhandler(Exception)1023 def handle_exception(e):1024 return "Exception"10251026 @app.route("/E1")1027 def raise_e1():1028 raise E110291030 @app.route("/E3")1031 def raise_e3():1032 raise E310331034 rv = client.get("/E1")1035 assert rv.data == b"Exception"10361037 rv = client.get("/E3")1038 assert rv.data == b"E2"103910401041def test_trapping_of_bad_request_key_errors(app, client):1042 @app.route("/key")1043 def fail():1044 flask.request.form["missing_key"]10451046 @app.route("/abort")1047 def allow_abort():1048 flask.abort(400)10491050 rv = client.get("/key")1051 assert rv.status_code == 4001052 assert b"missing_key" not in rv.data1053 rv = client.get("/abort")1054 assert rv.status_code == 40010551056 app.debug = True1057 with pytest.raises(KeyError) as e:1058 client.get("/key")1059 assert e.errisinstance(BadRequest)1060 assert "missing_key" in e.value.get_description()1061 rv = client.get("/abort")1062 assert rv.status_code == 40010631064 app.debug = False1065 app.config["TRAP_BAD_REQUEST_ERRORS"] = True1066 with pytest.raises(KeyError):1067 client.get("/key")1068 with pytest.raises(BadRequest):1069 client.get("/abort")107010711072def test_trapping_of_all_http_exceptions(app, client):1073 app.config["TRAP_HTTP_EXCEPTIONS"] = True10741075 @app.route("/fail")1076 def fail():1077 flask.abort(404)10781079 with pytest.raises(NotFound):1080 client.get("/fail")108110821083def test_error_handler_after_processor_error(app, client):1084 app.testing = False10851086 @app.before_request1087 def before_request():1088 if _trigger == "before":1089 1 // 010901091 @app.after_request1092 def after_request(response):1093 if _trigger == "after":1094 1 // 01095 return response10961097 @app.route("/")1098 def index():1099 return "Foo"11001101 @app.errorhandler(500)1102 def internal_server_error(e):1103 return "Hello Server Error", 50011041105 for _trigger in "before", "after":1106 rv = client.get("/")1107 assert rv.status_code == 5001108 assert rv.data == b"Hello Server Error"110911101111def test_enctype_debug_helper(app, client):1112 from flask.debughelpers import DebugFilesKeyError11131114 app.debug = True11151116 @app.route("/fail", methods=["POST"])1117 def index():1118 return flask.request.files["foo"].filename11191120 # with statement is important because we leave an exception on the1121 # stack otherwise and we want to ensure that this is not the case1122 # to not negatively affect other tests.1123 with client:1124 with pytest.raises(DebugFilesKeyError) as e:1125 client.post("/fail", data={"foo": "index.txt"})1126 assert "no file contents were transmitted" in str(e.value)1127 assert "This was submitted: 'index.txt'" in str(e.value)112811291130def test_response_types(app, client):1131 @app.route("/text")1132 def from_text():1133 return "Hällo Wörld"11341135 @app.route("/bytes")1136 def from_bytes():1137 return "Hällo Wörld".encode()11381139 @app.route("/full_tuple")1140 def from_full_tuple():1141 return (1142 "Meh",1143 400,1144 {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1145 )11461147 @app.route("/text_headers")1148 def from_text_headers():1149 return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}11501151 @app.route("/text_status")1152 def from_text_status():1153 return "Hi, status!", 40011541155 @app.route("/response_headers")1156 def from_response_headers():1157 return (1158 flask.Response(1159 "Hello world", 404, {"Content-Type": "text/html", "X-Foo": "Baz"}1160 ),1161 {"Content-Type": "text/plain", "X-Foo": "Bar", "X-Bar": "Foo"},1162 )11631164 @app.route("/response_status")1165 def from_response_status():1166 return app.response_class("Hello world", 400), 50011671168 @app.route("/wsgi")1169 def from_wsgi():1170 return NotFound()11711172 @app.route("/dict")1173 def from_dict():1174 return {"foo": "bar"}, 20111751176 assert client.get("/text").data == "Hällo Wörld".encode()1177 assert client.get("/bytes").data == "Hällo Wörld".encode()11781179 rv = client.get("/full_tuple")1180 assert rv.data == b"Meh"1181 assert rv.headers["X-Foo"] == "Testing"1182 assert rv.status_code == 4001183 assert rv.mimetype == "text/plain"11841185 rv = client.get("/text_headers")1186 assert rv.data == b"Hello"1187 assert rv.headers["X-Foo"] == "Test"1188 assert rv.status_code == 2001189 assert rv.mimetype == "text/plain"11901191 rv = client.get("/text_status")1192 assert rv.data == b"Hi, status!"1193 assert rv.status_code == 4001194 assert rv.mimetype == "text/html"11951196 rv = client.get("/response_headers")1197 assert rv.data == b"Hello world"1198 assert rv.content_type == "text/plain"1199 assert rv.headers.getlist("X-Foo") == ["Bar"]1200 assert rv.headers["X-Bar"] == "Foo"1201 assert rv.status_code == 40412021203 rv = client.get("/response_status")1204 assert rv.data == b"Hello world"1205 assert rv.status_code == 50012061207 rv = client.get("/wsgi")1208 assert b"Not Found" in rv.data1209 assert rv.status_code == 40412101211 rv = client.get("/dict")1212 assert rv.json == {"foo": "bar"}1213 assert rv.status_code == 201121412151216def test_response_type_errors():1217 app = flask.Flask(__name__)1218 app.testing = True12191220 @app.route("/none")1221 def from_none():1222 pass12231224 @app.route("/small_tuple")1225 def from_small_tuple():1226 return ("Hello",)12271228 @app.route("/large_tuple")1229 def from_large_tuple():1230 return "Hello", 234, {"X-Foo": "Bar"}, "???"12311232 @app.route("/bad_type")1233 def from_bad_type():1234 return True12351236 @app.route("/bad_wsgi")1237 def from_bad_wsgi():1238 return lambda: None12391240 c = app.test_client()12411242 with pytest.raises(TypeError) as e:1243 c.get("/none")1244

Merge pull request #4555 from pallets/pytest_raises_cleanupDavid Lordbefore adoptiona0bb10b

lines 1245–1247why, one step back
1245 assert "returned None" in str(e.value)
1246 assert "from_none" in str(e.value)1247

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 1248–1250why, one step back
1248 with pytest.raises(TypeError) as e:
1249 c.get("/small_tuple")1250

Merge pull request #4555 from pallets/pytest_raises_cleanupDavid Lordbefore adoptiona0bb10b

line 1251why, one step back
1251 assert "tuple must have the form" in str(e.value)

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

line 1252why, one step back
1252

Merge pull request #4555 from pallets/pytest_raises_cleanupDavid Lordbefore adoptiona0bb10b

lines 1253–1255why, one step back
1253 with pytest.raises(TypeError):
1254 c.get("/large_tuple")1255

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 1256–1258why, one step back
1256 with pytest.raises(TypeError) as e:
1257 c.get("/bad_type")1258

Merge pull request #4555 from pallets/pytest_raises_cleanupDavid Lordbefore adoptiona0bb10b

line 1259why, one step back
1259 assert "it was a bool" in str(e.value)

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

line 1260why, one step back
1260

Merge pull request #4555 from pallets/pytest_raises_cleanupDavid Lordbefore adoptiona0bb10b

lines 1261–1262why, one step back
1261 with pytest.raises(TypeError):
1262 c.get("/bad_wsgi")

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

line 1263why, one step back
1263

Merge pull request #4555 from pallets/pytest_raises_cleanupDavid Lordbefore adoptiona0bb10b

line 1264why, one step back
1264

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 1265–1532why, one step back
1265def test_make_response(app, req_ctx):
1266 rv = flask.make_response()1267 assert rv.status_code == 2001268 assert rv.data == b""1269 assert rv.mimetype == "text/html"12701271 rv = flask.make_response("Awesome")1272 assert rv.status_code == 2001273 assert rv.data == b"Awesome"1274 assert rv.mimetype == "text/html"12751276 rv = flask.make_response("W00t", 404)1277 assert rv.status_code == 4041278 assert rv.data == b"W00t"1279 assert rv.mimetype == "text/html"128012811282def test_make_response_with_response_instance(app, req_ctx):1283 rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1284 assert rv.status_code == 4001285 assert rv.data == b'{"msg":"W00t"}\n'1286 assert rv.mimetype == "application/json"12871288 rv = flask.make_response(flask.Response(""), 400)1289 assert rv.status_code == 4001290 assert rv.data == b""1291 assert rv.mimetype == "text/html"12921293 rv = flask.make_response(1294 flask.Response("", headers={"Content-Type": "text/html"}),1295 400,1296 [("X-Foo", "bar")],1297 )1298 assert rv.status_code == 4001299 assert rv.headers["Content-Type"] == "text/html"1300 assert rv.headers["X-Foo"] == "bar"130113021303def test_jsonify_no_prettyprint(app, req_ctx):1304 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1305 compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1306 uncompressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}13071308 rv = flask.make_response(flask.jsonify(uncompressed_msg), 200)1309 assert rv.data == compressed_msg131013111312def test_jsonify_prettyprint(app, req_ctx):1313 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1314 compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1315 pretty_response = (1316 b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'1317 )13181319 rv = flask.make_response(flask.jsonify(compressed_msg), 200)1320 assert rv.data == pretty_response132113221323def test_jsonify_mimetype(app, req_ctx):1324 app.config.update({"JSONIFY_MIMETYPE": "application/vnd.api+json"})1325 msg = {"msg": {"submsg": "W00t"}}1326 rv = flask.make_response(flask.jsonify(msg), 200)1327 assert rv.mimetype == "application/vnd.api+json"132813291330def test_json_dump_dataclass(app, req_ctx):1331 from dataclasses import make_dataclass13321333 Data = make_dataclass("Data", [("name", str)])1334 value = flask.json.dumps(Data("Flask"), app=app)1335 value = flask.json.loads(value, app=app)1336 assert value == {"name": "Flask"}133713381339def test_jsonify_args_and_kwargs_check(app, req_ctx):1340 with pytest.raises(TypeError) as e:1341 flask.jsonify("fake args", kwargs="fake")1342 assert "behavior undefined" in str(e.value)134313441345def test_url_generation(app, req_ctx):1346 @app.route("/hello/<name>", methods=["POST"])1347 def hello():1348 pass13491350 assert flask.url_for("hello", name="test x") == "/hello/test%20x"1351 assert (1352 flask.url_for("hello", name="test x", _external=True)1353 == "http://localhost/hello/test%20x"1354 )135513561357def test_build_error_handler(app):1358 # Test base case, a URL which results in a BuildError.1359 with app.test_request_context():1360 pytest.raises(BuildError, flask.url_for, "spam")13611362 # Verify the error is re-raised if not the current exception.1363 try:1364 with app.test_request_context():1365 flask.url_for("spam")1366 except BuildError as err:1367 error = err1368 try:1369 raise RuntimeError("Test case where BuildError is not current.")1370 except RuntimeError:1371 pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})13721373 # Test a custom handler.1374 def handler(error, endpoint, values):1375 # Just a test.1376 return "/test_handler/"13771378 app.url_build_error_handlers.append(handler)1379 with app.test_request_context():1380 assert flask.url_for("spam") == "/test_handler/"138113821383def test_build_error_handler_reraise(app):1384 # Test a custom handler which reraises the BuildError1385 def handler_raises_build_error(error, endpoint, values):1386 raise error13871388 app.url_build_error_handlers.append(handler_raises_build_error)13891390 with app.test_request_context():1391 pytest.raises(BuildError, flask.url_for, "not.existing")139213931394def test_url_for_passes_special_values_to_build_error_handler(app):1395 @app.url_build_error_handlers.append1396 def handler(error, endpoint, values):1397 assert values == {1398 "_external": False,1399 "_anchor": None,1400 "_method": None,1401 "_scheme": None,1402 }1403 return "handled"14041405 with app.test_request_context():1406 flask.url_for("/")140714081409def test_static_files(app, client):1410 rv = client.get("/static/index.html")1411 assert rv.status_code == 2001412 assert rv.data.strip() == b"<h1>Hello World!</h1>"1413 with app.test_request_context():1414 assert flask.url_for("static", filename="index.html") == "/static/index.html"1415 rv.close()141614171418def test_static_url_path():1419 app = flask.Flask(__name__, static_url_path="/foo")1420 app.testing = True1421 rv = app.test_client().get("/foo/index.html")1422 assert rv.status_code == 2001423 rv.close()14241425 with app.test_request_context():1426 assert flask.url_for("static", filename="index.html") == "/foo/index.html"142714281429def test_static_url_path_with_ending_slash():1430 app = flask.Flask(__name__, static_url_path="/foo/")1431 app.testing = True1432 rv = app.test_client().get("/foo/index.html")1433 assert rv.status_code == 2001434 rv.close()14351436 with app.test_request_context():1437 assert flask.url_for("static", filename="index.html") == "/foo/index.html"143814391440def test_static_url_empty_path(app):1441 app = flask.Flask(__name__, static_folder="", static_url_path="")1442 rv = app.test_client().open("/static/index.html", method="GET")1443 assert rv.status_code == 2001444 rv.close()144514461447def test_static_url_empty_path_default(app):1448 app = flask.Flask(__name__, static_folder="")1449 rv = app.test_client().open("/static/index.html", method="GET")1450 assert rv.status_code == 2001451 rv.close()145214531454def test_static_folder_with_pathlib_path(app):1455 from pathlib import Path14561457 app = flask.Flask(__name__, static_folder=Path("static"))1458 rv = app.test_client().open("/static/index.html", method="GET")1459 assert rv.status_code == 2001460 rv.close()146114621463def test_static_folder_with_ending_slash():1464 app = flask.Flask(__name__, static_folder="static/")14651466 @app.route("/<path:path>")1467 def catch_all(path):1468 return path14691470 rv = app.test_client().get("/catch/all")1471 assert rv.data == b"catch/all"147214731474def test_static_route_with_host_matching():1475 app = flask.Flask(__name__, host_matching=True, static_host="example.com")1476 c = app.test_client()1477 rv = c.get("http://example.com/static/index.html")1478 assert rv.status_code == 2001479 rv.close()1480 with app.test_request_context():1481 rv = flask.url_for("static", filename="index.html", _external=True)1482 assert rv == "http://example.com/static/index.html"1483 # Providing static_host without host_matching=True should error.1484 with pytest.raises(Exception):1485 flask.Flask(__name__, static_host="example.com")1486 # Providing host_matching=True with static_folder1487 # but without static_host should error.1488 with pytest.raises(Exception):1489 flask.Flask(__name__, host_matching=True)1490 # Providing host_matching=True without static_host1491 # but with static_folder=None should not error.1492 flask.Flask(__name__, host_matching=True, static_folder=None)149314941495def test_request_locals():1496 assert repr(flask.g) == "<LocalProxy unbound>"1497 assert not flask.g149814991500def test_server_name_subdomain():1501 app = flask.Flask(__name__, subdomain_matching=True)1502 client = app.test_client()15031504 @app.route("/")1505 def index():1506 return "default"15071508 @app.route("/", subdomain="foo")1509 def subdomain():1510 return "subdomain"15111512 app.config["SERVER_NAME"] = "dev.local:5000"1513 rv = client.get("/")1514 assert rv.data == b"default"15151516 rv = client.get("/", "http://dev.local:5000")1517 assert rv.data == b"default"15181519 rv = client.get("/", "https://dev.local:5000")1520 assert rv.data == b"default"15211522 app.config["SERVER_NAME"] = "dev.local:443"1523 rv = client.get("/", "https://dev.local")15241525 # Werkzeug 1.0 fixes matching https scheme with 443 port1526 if rv.status_code != 404:1527 assert rv.data == b"default"15281529 app.config["SERVER_NAME"] = "dev.local"1530 rv = client.get("/", "https://dev.local")1531 assert rv.data == b"default"1532

Merge branch '2.0.x'David Lordbefore adoptione37e871

lines 1533–1537why, one step back
1533 # suppress Werkzeug 0.15 warning about name mismatch
1534 with warnings.catch_warnings():1535 warnings.filterwarnings(1536 "ignore", "Current server name", UserWarning, "flask.app"1537 )

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 1538–1544why, one step back
1538 rv = client.get("/", "http://foo.localhost")
1539 assert rv.status_code == 40415401541 rv = client.get("/", "http://foo.dev.local")1542 assert rv.data == b"subdomain"15431544

Merge pull request #3861 from greyli/fix-pytestDavid Lordbefore adoptionc676c2c

lines 1545–1546why, one step back
1545@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning")
1546@pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning")

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 1547–1638why, one step back
1547def test_exception_propagation(app, client):
1548 def apprunner(config_key):1549 @app.route("/")1550 def index():1551 1 // 015521553 if config_key is not None:1554 app.config[config_key] = True1555 with pytest.raises(Exception):1556 client.get("/")1557 else:1558 assert client.get("/").status_code == 50015591560 # we have to run this test in an isolated thread because if the1561 # debug flag is set to true and an exception happens the context is1562 # not torn down. This causes other tests that run after this fail1563 # when they expect no exception on the stack.1564 for config_key in "TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None:1565 t = Thread(target=apprunner, args=(config_key,))1566 t.start()1567 t.join()156815691570@pytest.mark.parametrize("debug", [True, False])1571@pytest.mark.parametrize("use_debugger", [True, False])1572@pytest.mark.parametrize("use_reloader", [True, False])1573@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1574def test_werkzeug_passthrough_errors(1575 monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1576):1577 rv = {}15781579 # Mocks werkzeug.serving.run_simple method1580 def run_simple_mock(*args, **kwargs):1581 rv["passthrough_errors"] = kwargs.get("passthrough_errors")15821583 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1584 app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1585 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)158615871588def test_max_content_length(app, client):1589 app.config["MAX_CONTENT_LENGTH"] = 6415901591 @app.before_request1592 def always_first():1593 flask.request.form["myfile"]1594 AssertionError()15951596 @app.route("/accept", methods=["POST"])1597 def accept_file():1598 flask.request.form["myfile"]1599 AssertionError()16001601 @app.errorhandler(413)1602 def catcher(error):1603 return "42"16041605 rv = client.post("/accept", data={"myfile": "foo" * 100})1606 assert rv.data == b"42"160716081609def test_url_processors(app, client):1610 @app.url_defaults1611 def add_language_code(endpoint, values):1612 if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1613 endpoint, "lang_code"1614 ):1615 values.setdefault("lang_code", flask.g.lang_code)16161617 @app.url_value_preprocessor1618 def pull_lang_code(endpoint, values):1619 flask.g.lang_code = values.pop("lang_code", None)16201621 @app.route("/<lang_code>/")1622 def index():1623 return flask.url_for("about")16241625 @app.route("/<lang_code>/about")1626 def about():1627 return flask.url_for("something_else")16281629 @app.route("/foo")1630 def something_else():1631 return flask.url_for("about", lang_code="en")16321633 assert client.get("/de/").data == b"/de/about"1634 assert client.get("/de/about").data == b"/foo"1635 assert client.get("/foo").data == b"/en/about"163616371638def test_inject_blueprint_url_defaults(app):

Merge remote-tracking branch 'origin/2.0.x'David Lordbefore adoption4240ace

line 1639why, one step back
1639 bp = flask.Blueprint("foo", __name__, template_folder="template")

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 1640–1651why, one step back
1640
1641 @bp.url_defaults1642 def bp_defaults(endpoint, values):1643 values["page"] = "login"16441645 @bp.route("/<page>")1646 def view(page):1647 pass16481649 app.register_blueprint(bp)16501651 values = dict()

Merge remote-tracking branch 'origin/2.0.x'David Lordbefore adoption4240ace

line 1652why, one step back
1652 app.inject_url_defaults("foo.view", values)

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 1653–1656why, one step back
1653 expected = dict(page="login")
1654 assert values == expected16551656 with app.test_request_context("/somepage"):

Merge remote-tracking branch 'origin/2.0.x'David Lordbefore adoption4240ace

line 1657why, one step back
1657 url = flask.url_for("foo.view")

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 1658–1680why, one step back
1658 expected = "/login"
1659 assert url == expected166016611662def test_nonascii_pathinfo(app, client):1663 @app.route("/киртест")1664 def index():1665 return "Hello World!"16661667 rv = client.get("/киртест")1668 assert rv.data == b"Hello World!"166916701671def test_debug_mode_complains_after_first_request(app, client):1672 app.debug = True16731674 @app.route("/")1675 def index():1676 return "Awesome"16771678 assert not app.got_first_request1679 assert client.get("/").data == b"Awesome"1680

Merge pull request #4555 from pallets/pytest_raises_cleanupDavid Lordbefore adoptiona0bb10b

lines 1681–1682why, one step back
1681 with pytest.raises(AssertionError) as e:
1682 app.add_url_rule("/foo", endpoint="late")

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 1683–1728why, one step back
1683
1684 assert "A setup function was called" in str(e.value)16851686 app.debug = False16871688 @app.route("/foo")1689 def working():1690 return "Meh"16911692 assert client.get("/foo").data == b"Meh"1693 assert app.got_first_request169416951696def test_before_first_request_functions(app, client):1697 got = []16981699 @app.before_first_request1700 def foo():1701 got.append(42)17021703 client.get("/")1704 assert got == [42]1705 client.get("/")1706 assert got == [42]1707 assert app.got_first_request170817091710def test_before_first_request_functions_concurrent(app, client):1711 got = []17121713 @app.before_first_request1714 def foo():1715 time.sleep(0.2)1716 got.append(42)17171718 def get_and_assert():1719 client.get("/")1720 assert got == [42]17211722 t = Thread(target=get_and_assert)1723 t.start()1724 get_and_assert()1725 t.join()1726 assert app.got_first_request17271728

Merge pull request #4492 from pallets/debug-messagesDavid Lordbefore adoptionce7b884

line 1729why, one step back
1729def test_routing_redirect_debugging(monkeypatch, app, client):

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 1730–1733why, one step back
1730 @app.route("/foo/", methods=["GET", "POST"])
1731 def foo():1732 return "success"1733

Merge pull request #4492 from pallets/debug-messagesDavid Lordbefore adoptionce7b884

lines 1734–1736why, one step back
1734 app.debug = False
1735 rv = client.post("/foo", data={}, follow_redirects=True)1736 assert rv.data == b"success"

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

line 1737why, one step back
1737

Merge pull request #4492 from pallets/debug-messagesDavid Lordbefore adoptionce7b884

line 1738why, one step back
1738 app.debug = True

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 1739–1742why, one step back
1739
1740 with client:1741 rv = client.post("/foo", data={}, follow_redirects=True)1742 assert rv.data == b"success"

Merge pull request #4492 from pallets/debug-messagesDavid Lordbefore adoptionce7b884

lines 1743–1751why, one step back
1743 rv = client.get("/foo", data={}, follow_redirects=True)
1744 assert rv.data == b"success"17451746 monkeypatch.setattr(RequestRedirect, "code", 301)17471748 with client, pytest.raises(AssertionError) as e:1749 client.post("/foo", data={})17501751 assert "canonical URL 'http://localhost/foo/'" in str(e.value)

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 1752–1902why, one step back
1752
17531754def test_route_decorator_custom_endpoint(app, client):1755 app.debug = True17561757 @app.route("/foo/")1758 def foo():1759 return flask.request.endpoint17601761 @app.route("/bar/", endpoint="bar")1762 def for_bar():1763 return flask.request.endpoint17641765 @app.route("/bar/123", endpoint="123")1766 def for_bar_foo():1767 return flask.request.endpoint17681769 with app.test_request_context():1770 assert flask.url_for("foo") == "/foo/"1771 assert flask.url_for("bar") == "/bar/"1772 assert flask.url_for("123") == "/bar/123"17731774 assert client.get("/foo/").data == b"foo"1775 assert client.get("/bar/").data == b"bar"1776 assert client.get("/bar/123").data == b"123"177717781779def test_preserve_only_once(app, client):1780 app.debug = True17811782 @app.route("/fail")1783 def fail_func():1784 1 // 017851786 for _x in range(3):1787 with pytest.raises(ZeroDivisionError):1788 client.get("/fail")17891790 assert flask._request_ctx_stack.top is not None1791 assert flask._app_ctx_stack.top is not None1792 # implicit appctx disappears too1793 flask._request_ctx_stack.top.pop()1794 assert flask._request_ctx_stack.top is None1795 assert flask._app_ctx_stack.top is None179617971798def test_preserve_remembers_exception(app, client):1799 app.debug = True1800 errors = []18011802 @app.route("/fail")1803 def fail_func():1804 1 // 018051806 @app.route("/success")1807 def success_func():1808 return "Okay"18091810 @app.teardown_request1811 def teardown_handler(exc):1812 errors.append(exc)18131814 # After this failure we did not yet call the teardown handler1815 with pytest.raises(ZeroDivisionError):1816 client.get("/fail")1817 assert errors == []18181819 # But this request triggers it, and it's an error1820 client.get("/success")1821 assert len(errors) == 21822 assert isinstance(errors[0], ZeroDivisionError)18231824 # At this point another request does nothing.1825 client.get("/success")1826 assert len(errors) == 31827 assert errors[1] is None182818291830def test_get_method_on_g(app_ctx):1831 assert flask.g.get("x") is None1832 assert flask.g.get("x", 11) == 111833 flask.g.x = 421834 assert flask.g.get("x") == 421835 assert flask.g.x == 42183618371838def test_g_iteration_protocol(app_ctx):1839 flask.g.foo = 231840 flask.g.bar = 421841 assert "foo" in flask.g1842 assert "foos" not in flask.g1843 assert sorted(flask.g) == ["bar", "foo"]184418451846def test_subdomain_basic_support():1847 app = flask.Flask(__name__, subdomain_matching=True)1848 app.config["SERVER_NAME"] = "localhost.localdomain"1849 client = app.test_client()18501851 @app.route("/")1852 def normal_index():1853 return "normal index"18541855 @app.route("/", subdomain="test")1856 def test_index():1857 return "test index"18581859 rv = client.get("/", "http://localhost.localdomain/")1860 assert rv.data == b"normal index"18611862 rv = client.get("/", "http://test.localhost.localdomain/")1863 assert rv.data == b"test index"186418651866def test_subdomain_matching():1867 app = flask.Flask(__name__, subdomain_matching=True)1868 client = app.test_client()1869 app.config["SERVER_NAME"] = "localhost.localdomain"18701871 @app.route("/", subdomain="<user>")1872 def index(user):1873 return f"index for {user}"18741875 rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1876 assert rv.data == b"index for mitsuhiko"187718781879def test_subdomain_matching_with_ports():1880 app = flask.Flask(__name__, subdomain_matching=True)1881 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1882 client = app.test_client()18831884 @app.route("/", subdomain="<user>")1885 def index(user):1886 return f"index for {user}"18871888 rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1889 assert rv.data == b"index for mitsuhiko"189018911892@pytest.mark.parametrize("matching", (False, True))1893def test_subdomain_matching_other_name(matching):1894 app = flask.Flask(__name__, subdomain_matching=matching)1895 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1896 client = app.test_client()18971898 @app.route("/")1899 def index():1900 return "", 20419011902 # suppress Werkzeug 0.15 warning about name mismatch

Merge branch '2.0.x'David Lordbefore adoptione37e871

lines 1903–1906why, one step back
1903 with warnings.catch_warnings():
1904 warnings.filterwarnings(1905 "ignore", "Current server name", UserWarning, "flask.app"1906 )

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 1907–2036why, one step back
1907 # ip address can't match name
1908 rv = client.get("/", "http://127.0.0.1:3000/")1909 assert rv.status_code == 404 if matching else 20419101911 # allow all subdomains if matching is disabled1912 rv = client.get("/", "http://www.localhost.localdomain:3000/")1913 assert rv.status_code == 404 if matching else 204191419151916def test_multi_route_rules(app, client):1917 @app.route("/")1918 @app.route("/<test>/")1919 def index(test="a"):1920 return test19211922 rv = client.open("/")1923 assert rv.data == b"a"1924 rv = client.open("/b/")1925 assert rv.data == b"b"192619271928def test_multi_route_class_views(app, client):1929 class View:1930 def __init__(self, app):1931 app.add_url_rule("/", "index", self.index)1932 app.add_url_rule("/<test>/", "index", self.index)19331934 def index(self, test="a"):1935 return test19361937 _ = View(app)1938 rv = client.open("/")1939 assert rv.data == b"a"1940 rv = client.open("/b/")1941 assert rv.data == b"b"194219431944def test_run_defaults(monkeypatch, app):1945 rv = {}19461947 # Mocks werkzeug.serving.run_simple method1948 def run_simple_mock(*args, **kwargs):1949 rv["result"] = "running..."19501951 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1952 app.run()1953 assert rv["result"] == "running..."195419551956def test_run_server_port(monkeypatch, app):1957 rv = {}19581959 # Mocks werkzeug.serving.run_simple method1960 def run_simple_mock(hostname, port, application, *args, **kwargs):1961 rv["result"] = f"running on {hostname}:{port} ..."19621963 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1964 hostname, port = "localhost", 80001965 app.run(hostname, port, debug=True)1966 assert rv["result"] == f"running on {hostname}:{port} ..."196719681969@pytest.mark.parametrize(1970 "host,port,server_name,expect_host,expect_port",1971 (1972 (None, None, "pocoo.org:8080", "pocoo.org", 8080),1973 ("localhost", None, "pocoo.org:8080", "localhost", 8080),1974 (None, 80, "pocoo.org:8080", "pocoo.org", 80),1975 ("localhost", 80, "pocoo.org:8080", "localhost", 80),1976 ("localhost", 0, "localhost:8080", "localhost", 0),1977 (None, None, "localhost:8080", "localhost", 8080),1978 (None, None, "localhost:0", "localhost", 0),1979 ),1980)1981def test_run_from_config(1982 monkeypatch, host, port, server_name, expect_host, expect_port, app1983):1984 def run_simple_mock(hostname, port, *args, **kwargs):1985 assert hostname == expect_host1986 assert port == expect_port19871988 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1989 app.config["SERVER_NAME"] = server_name1990 app.run(host, port)199119921993def test_max_cookie_size(app, client, recwarn):1994 app.config["MAX_COOKIE_SIZE"] = 10019951996 # outside app context, default to Werkzeug static value,1997 # which is also the default config1998 response = flask.Response()1999 default = flask.Flask.default_config["MAX_COOKIE_SIZE"]2000 assert response.max_cookie_size == default

The first 2,000 of 2,036 lines.