Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

2,035 lines · 54.7 KiB · Python

Last changed by

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

History of this file

Take it

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

Break reference cycle created by default in Flask instances.Bogdan Opanchukbefore adoption8efea0c

line 1why, one step back
1import gc

Merge pull request #3706 from pallets/dependabot/pip/tox-3.18.1dependabot-preview[bot]before adoptionfd0a608

lines 2–4why, one step back
2import re
3import time4import uuid

Merge branch '2.0.x'David Lordbefore adoptione37e871

line 5why, one step back
5import warnings

Break reference cycle created by default in Flask instances.Bogdan Opanchukbefore adoption8efea0c

line 6why, one step back
6import weakref

Merge pull request #3706 from pallets/dependabot/pip/tox-3.18.1dependabot-preview[bot]before adoptionfd0a608

line 7why, one step back
7from datetime import datetime

Break reference cycle created by default in Flask instances.Bogdan Opanchukbefore adoption8efea0c

line 8why, one step back
8from platform import python_implementation

Merge pull request #3706 from pallets/dependabot/pip/tox-3.18.1dependabot-preview[bot]before adoptionfd0a608

lines 9–17why, one step back
9from threading import Thread
1011import 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 #3706 from pallets/dependabot/pip/tox-3.18.1dependabot-preview[bot]before adoptionfd0a608

lines 19–22why, one step back
19
20import flask2122

Break reference cycle created by default in Flask instances.Bogdan Opanchukbefore adoption8efea0c

line 23why, one step back
23require_cpython_gc = pytest.mark.skipif(

update requirements (#3823)David Lordbefore adoption373f0dd

lines 24–25why, one step back
24 python_implementation() != "CPython",
25 reason="Requires CPython GC behavior",

Break reference cycle created by default in Flask instances.Bogdan Opanchukbefore adoption8efea0c

lines 26–28why, one step back
26)
2728

Merge pull request #3706 from pallets/dependabot/pip/tox-3.18.1dependabot-preview[bot]before adoptionfd0a608

lines 29–51why, one step back
29def 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 #3706 from pallets/dependabot/pip/tox-3.18.1dependabot-preview[bot]before adoptionfd0a608

lines 69–342why, 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):153154 @app.route("/", methods="GET POST")155 def index():156 return "Hey"157158159def test_url_mapping(app, client):160 random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"161162 def index():163 return flask.request.method164165 def more():166 return flask.request.method167168 def options():169 return random_uuid4170171 app.add_url_rule("/", "index", index)172 app.add_url_rule("/more", "more", more, methods=["GET", "POST"])173174 # Issue 1288: Test that automatic options are not added175 # when non-uppercase 'options' in methods176 app.add_url_rule("/options", "options", options, methods=["options"])177178 assert client.get("/").data == b"GET"179 rv = client.post("/")180 assert rv.status_code == 405181 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]182 rv = client.head("/")183 assert rv.status_code == 200184 assert not rv.data # head truncates185 assert client.post("/more").data == b"POST"186 assert client.get("/more").data == b"GET"187 rv = client.delete("/more")188 assert rv.status_code == 405189 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]190 rv = client.open("/options", method="OPTIONS")191 assert rv.status_code == 200192 assert random_uuid4 in rv.data.decode("utf-8")193194195def test_werkzeug_routing(app, client):196 from werkzeug.routing import Submount, Rule197198 app.url_map.add(199 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])200 )201202 def bar():203 return "bar"204205 def index():206 return "index"207208 app.view_functions["bar"] = bar209 app.view_functions["index"] = index210211 assert client.get("/foo/").data == b"index"212 assert client.get("/foo/bar").data == b"bar"213214215def test_endpoint_decorator(app, client):216 from werkzeug.routing import Submount, Rule217218 app.url_map.add(219 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])220 )221222 @app.endpoint("bar")223 def bar():224 return "bar"225226 @app.endpoint("index")227 def index():228 return "index"229230 assert client.get("/foo/").data == b"index"231 assert client.get("/foo/bar").data == b"bar"232233234def test_session(app, client):235 @app.route("/set", methods=["POST"])236 def set():237 assert not flask.session.accessed238 assert not flask.session.modified239 flask.session["value"] = flask.request.form["value"]240 assert flask.session.accessed241 assert flask.session.modified242 return "value set"243244 @app.route("/get")245 def get():246 assert not flask.session.accessed247 assert not flask.session.modified248 v = flask.session.get("value", "None")249 assert flask.session.accessed250 assert not flask.session.modified251 return v252253 assert client.post("/set", data={"value": "42"}).data == b"value set"254 assert client.get("/get").data == b"42"255256257def test_session_using_server_name(app, client):258 app.config.update(SERVER_NAME="example.com")259260 @app.route("/")261 def index():262 flask.session["testing"] = 42263 return "Hello World"264265 rv = client.get("/", "http://example.com/")266 assert "domain=.example.com" in rv.headers["set-cookie"].lower()267 assert "httponly" in rv.headers["set-cookie"].lower()268269270def test_session_using_server_name_and_port(app, client):271 app.config.update(SERVER_NAME="example.com:8080")272273 @app.route("/")274 def index():275 flask.session["testing"] = 42276 return "Hello World"277278 rv = client.get("/", "http://example.com:8080/")279 assert "domain=.example.com" in rv.headers["set-cookie"].lower()280 assert "httponly" in rv.headers["set-cookie"].lower()281282283def test_session_using_server_name_port_and_path(app, client):284 app.config.update(SERVER_NAME="example.com:8080", APPLICATION_ROOT="/foo")285286 @app.route("/")287 def index():288 flask.session["testing"] = 42289 return "Hello World"290291 rv = client.get("/", "http://example.com:8080/foo")292 assert "domain=example.com" in rv.headers["set-cookie"].lower()293 assert "path=/foo" in rv.headers["set-cookie"].lower()294 assert "httponly" in rv.headers["set-cookie"].lower()295296297def test_session_using_application_root(app, client):298 class PrefixPathMiddleware:299 def __init__(self, app, prefix):300 self.app = app301 self.prefix = prefix302303 def __call__(self, environ, start_response):304 environ["SCRIPT_NAME"] = self.prefix305 return self.app(environ, start_response)306307 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, "/bar")308 app.config.update(APPLICATION_ROOT="/bar")309310 @app.route("/")311 def index():312 flask.session["testing"] = 42313 return "Hello World"314315 rv = client.get("/", "http://example.com:8080/")316 assert "path=/bar" in rv.headers["set-cookie"].lower()317318319def test_session_using_session_settings(app, client):320 app.config.update(321 SERVER_NAME="www.example.com:8080",322 APPLICATION_ROOT="/test",323 SESSION_COOKIE_DOMAIN=".example.com",324 SESSION_COOKIE_HTTPONLY=False,325 SESSION_COOKIE_SECURE=True,326 SESSION_COOKIE_SAMESITE="Lax",327 SESSION_COOKIE_PATH="/",328 )329330 @app.route("/")331 def index():332 flask.session["testing"] = 42333 return "Hello World"334335 rv = client.get("/", "http://www.example.com:8080/test/")336 cookie = rv.headers["set-cookie"].lower()337 assert "domain=.example.com" in cookie338 assert "path=/" in cookie339 assert "secure" in cookie340 assert "httponly" not in cookie341 assert "samesite" in cookie342

include samesite and secure when removing session cookie (#3726)Mathurshan Vimalesvaranbefore adoption22987b6

lines 343–355why, one step back
343 @app.route("/clear")
344 def clear():345 flask.session.pop("testing", None)346 return "Goodbye World"347348 rv = client.get("/clear", "http://www.example.com:8080/test/")349 cookie = rv.headers["set-cookie"].lower()350 assert "session=;" in cookie351 assert "domain=.example.com" in cookie352 assert "path=/" in cookie353 assert "secure" in cookie354 assert "samesite" in cookie355

Merge pull request #3706 from pallets/dependabot/pip/tox-3.18.1dependabot-preview[bot]before adoptionfd0a608

lines 356–1529why, one step back
356
357def test_session_using_samesite_attribute(app, client):358 @app.route("/")359 def index():360 flask.session["testing"] = 42361 return "Hello World"362363 app.config.update(SESSION_COOKIE_SAMESITE="invalid")364365 with pytest.raises(ValueError):366 client.get("/")367368 app.config.update(SESSION_COOKIE_SAMESITE=None)369 rv = client.get("/")370 cookie = rv.headers["set-cookie"].lower()371 assert "samesite" not in cookie372373 app.config.update(SESSION_COOKIE_SAMESITE="Strict")374 rv = client.get("/")375 cookie = rv.headers["set-cookie"].lower()376 assert "samesite=strict" in cookie377378 app.config.update(SESSION_COOKIE_SAMESITE="Lax")379 rv = client.get("/")380 cookie = rv.headers["set-cookie"].lower()381 assert "samesite=lax" in cookie382383384def test_session_localhost_warning(recwarn, app, client):385 app.config.update(SERVER_NAME="localhost:5000")386387 @app.route("/")388 def index():389 flask.session["testing"] = 42390 return "testing"391392 rv = client.get("/", "http://localhost:5000/")393 assert "domain" not in rv.headers["set-cookie"].lower()394 w = recwarn.pop(UserWarning)395 assert "'localhost' is not a valid cookie domain" in str(w.message)396397398def test_session_ip_warning(recwarn, app, client):399 app.config.update(SERVER_NAME="127.0.0.1:5000")400401 @app.route("/")402 def index():403 flask.session["testing"] = 42404 return "testing"405406 rv = client.get("/", "http://127.0.0.1:5000/")407 assert "domain=127.0.0.1" in rv.headers["set-cookie"].lower()408 w = recwarn.pop(UserWarning)409 assert "cookie domain is an IP" in str(w.message)410411412def test_missing_session(app):413 app.secret_key = None414415 def expect_exception(f, *args, **kwargs):416 e = pytest.raises(RuntimeError, f, *args, **kwargs)417 assert e.value.args and "session is unavailable" in e.value.args[0]418419 with app.test_request_context():420 assert flask.session.get("missing_key") is None421 expect_exception(flask.session.__setitem__, "foo", 42)422 expect_exception(flask.session.pop, "foo")423424425def test_session_expiration(app, client):426 permanent = True427428 @app.route("/")429 def index():430 flask.session["test"] = 42431 flask.session.permanent = permanent432 return ""433434 @app.route("/test")435 def test():436 return str(flask.session.permanent)437438 rv = client.get("/")439 assert "set-cookie" in rv.headers440 match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])441 expires = parse_date(match.group())442 expected = datetime.utcnow() + app.permanent_session_lifetime443 assert expires.year == expected.year444 assert expires.month == expected.month445 assert expires.day == expected.day446447 rv = client.get("/test")448 assert rv.data == b"True"449450 permanent = False451 rv = client.get("/")452 assert "set-cookie" in rv.headers453 match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])454 assert match is None455456457def test_session_stored_last(app, client):458 @app.after_request459 def modify_session(response):460 flask.session["foo"] = 42461 return response462463 @app.route("/")464 def dump_session_contents():465 return repr(flask.session.get("foo"))466467 assert client.get("/").data == b"None"468 assert client.get("/").data == b"42"469470471def test_session_special_types(app, client):472 now = datetime.utcnow().replace(microsecond=0)473 the_uuid = uuid.uuid4()474475 @app.route("/")476 def dump_session_contents():477 flask.session["t"] = (1, 2, 3)478 flask.session["b"] = b"\xff"479 flask.session["m"] = flask.Markup("<html>")480 flask.session["u"] = the_uuid481 flask.session["d"] = now482 flask.session["t_tag"] = {" t": "not-a-tuple"}483 flask.session["di_t_tag"] = {" t__": "not-a-tuple"}484 flask.session["di_tag"] = {" di": "not-a-dict"}485 return "", 204486487 with client:488 client.get("/")489 s = flask.session490 assert s["t"] == (1, 2, 3)491 assert type(s["b"]) == bytes492 assert s["b"] == b"\xff"493 assert type(s["m"]) == flask.Markup494 assert s["m"] == flask.Markup("<html>")495 assert s["u"] == the_uuid496 assert s["d"] == now497 assert s["t_tag"] == {" t": "not-a-tuple"}498 assert s["di_t_tag"] == {" t__": "not-a-tuple"}499 assert s["di_tag"] == {" di": "not-a-dict"}500501502def test_session_cookie_setting(app):503 is_permanent = True504505 @app.route("/bump")506 def bump():507 rv = flask.session["foo"] = flask.session.get("foo", 0) + 1508 flask.session.permanent = is_permanent509 return str(rv)510511 @app.route("/read")512 def read():513 return str(flask.session.get("foo", 0))514515 def run_test(expect_header):516 with app.test_client() as c:517 assert c.get("/bump").data == b"1"518 assert c.get("/bump").data == b"2"519 assert c.get("/bump").data == b"3"520521 rv = c.get("/read")522 set_cookie = rv.headers.get("set-cookie")523 assert (set_cookie is not None) == expect_header524 assert rv.data == b"3"525526 is_permanent = True527 app.config["SESSION_REFRESH_EACH_REQUEST"] = True528 run_test(expect_header=True)529530 is_permanent = True531 app.config["SESSION_REFRESH_EACH_REQUEST"] = False532 run_test(expect_header=False)533534 is_permanent = False535 app.config["SESSION_REFRESH_EACH_REQUEST"] = True536 run_test(expect_header=False)537538 is_permanent = False539 app.config["SESSION_REFRESH_EACH_REQUEST"] = False540 run_test(expect_header=False)541542543def test_session_vary_cookie(app, client):544 @app.route("/set")545 def set_session():546 flask.session["test"] = "test"547 return ""548549 @app.route("/get")550 def get():551 return flask.session.get("test")552553 @app.route("/getitem")554 def getitem():555 return flask.session["test"]556557 @app.route("/setdefault")558 def setdefault():559 return flask.session.setdefault("test", "default")560561 @app.route("/vary-cookie-header-set")562 def vary_cookie_header_set():563 response = flask.Response()564 response.vary.add("Cookie")565 flask.session["test"] = "test"566 return response567568 @app.route("/vary-header-set")569 def vary_header_set():570 response = flask.Response()571 response.vary.update(("Accept-Encoding", "Accept-Language"))572 flask.session["test"] = "test"573 return response574575 @app.route("/no-vary-header")576 def no_vary_header():577 return ""578579 def expect(path, header_value="Cookie"):580 rv = client.get(path)581582 if header_value:583 # The 'Vary' key should exist in the headers only once.584 assert len(rv.headers.get_all("Vary")) == 1585 assert rv.headers["Vary"] == header_value586 else:587 assert "Vary" not in rv.headers588589 expect("/set")590 expect("/get")591 expect("/getitem")592 expect("/setdefault")593 expect("/vary-cookie-header-set")594 expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")595 expect("/no-vary-header", None)596597598def test_flashes(app, req_ctx):599 assert not flask.session.modified600 flask.flash("Zap")601 flask.session.modified = False602 flask.flash("Zip")603 assert flask.session.modified604 assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]605606607def test_extended_flashing(app):608 # Be sure app.testing=True below, else tests can fail silently.609 #610 # Specifically, if app.testing is not set to True, the AssertionErrors611 # in the view functions will cause a 500 response to the test client612 # instead of propagating exceptions.613614 @app.route("/")615 def index():616 flask.flash("Hello World")617 flask.flash("Hello World", "error")618 flask.flash(flask.Markup("<em>Testing</em>"), "warning")619 return ""620621 @app.route("/test/")622 def test():623 messages = flask.get_flashed_messages()624 assert list(messages) == [625 "Hello World",626 "Hello World",627 flask.Markup("<em>Testing</em>"),628 ]629 return ""630631 @app.route("/test_with_categories/")632 def test_with_categories():633 messages = flask.get_flashed_messages(with_categories=True)634 assert len(messages) == 3635 assert list(messages) == [636 ("message", "Hello World"),637 ("error", "Hello World"),638 ("warning", flask.Markup("<em>Testing</em>")),639 ]640 return ""641642 @app.route("/test_filter/")643 def test_filter():644 messages = flask.get_flashed_messages(645 category_filter=["message"], with_categories=True646 )647 assert list(messages) == [("message", "Hello World")]648 return ""649650 @app.route("/test_filters/")651 def test_filters():652 messages = flask.get_flashed_messages(653 category_filter=["message", "warning"], with_categories=True654 )655 assert list(messages) == [656 ("message", "Hello World"),657 ("warning", flask.Markup("<em>Testing</em>")),658 ]659 return ""660661 @app.route("/test_filters_without_returning_categories/")662 def test_filters2():663 messages = flask.get_flashed_messages(category_filter=["message", "warning"])664 assert len(messages) == 2665 assert messages[0] == "Hello World"666 assert messages[1] == flask.Markup("<em>Testing</em>")667 return ""668669 # Create new test client on each test to clean flashed messages.670671 client = app.test_client()672 client.get("/")673 client.get("/test_with_categories/")674675 client = app.test_client()676 client.get("/")677 client.get("/test_filter/")678679 client = app.test_client()680 client.get("/")681 client.get("/test_filters/")682683 client = app.test_client()684 client.get("/")685 client.get("/test_filters_without_returning_categories/")686687688def test_request_processing(app, client):689 evts = []690691 @app.before_request692 def before_request():693 evts.append("before")694695 @app.after_request696 def after_request(response):697 response.data += b"|after"698 evts.append("after")699 return response700701 @app.route("/")702 def index():703 assert "before" in evts704 assert "after" not in evts705 return "request"706707 assert "after" not in evts708 rv = client.get("/").data709 assert "after" in evts710 assert rv == b"request|after"711712713def test_request_preprocessing_early_return(app, client):714 evts = []715716 @app.before_request717 def before_request1():718 evts.append(1)719720 @app.before_request721 def before_request2():722 evts.append(2)723 return "hello"724725 @app.before_request726 def before_request3():727 evts.append(3)728 return "bye"729730 @app.route("/")731 def index():732 evts.append("index")733 return "damnit"734735 rv = client.get("/").data.strip()736 assert rv == b"hello"737 assert evts == [1, 2]738739740def test_after_request_processing(app, client):741 @app.route("/")742 def index():743 @flask.after_this_request744 def foo(response):745 response.headers["X-Foo"] = "a header"746 return response747748 return "Test"749750 resp = client.get("/")751 assert resp.status_code == 200752 assert resp.headers["X-Foo"] == "a header"753754755def test_teardown_request_handler(app, client):756 called = []757758 @app.teardown_request759 def teardown_request(exc):760 called.append(True)761 return "Ignored"762763 @app.route("/")764 def root():765 return "Response"766767 rv = client.get("/")768 assert rv.status_code == 200769 assert b"Response" in rv.data770 assert len(called) == 1771772773def test_teardown_request_handler_debug_mode(app, client):774 called = []775776 @app.teardown_request777 def teardown_request(exc):778 called.append(True)779 return "Ignored"780781 @app.route("/")782 def root():783 return "Response"784785 rv = client.get("/")786 assert rv.status_code == 200787 assert b"Response" in rv.data788 assert len(called) == 1789790791def test_teardown_request_handler_error(app, client):792 called = []793 app.testing = False794795 @app.teardown_request796 def teardown_request1(exc):797 assert type(exc) == ZeroDivisionError798 called.append(True)799 # This raises a new error and blows away sys.exc_info(), so we can800 # test that all teardown_requests get passed the same original801 # exception.802 try:803 raise TypeError()804 except Exception:805 pass806807 @app.teardown_request808 def teardown_request2(exc):809 assert type(exc) == ZeroDivisionError810 called.append(True)811 # This raises a new error and blows away sys.exc_info(), so we can812 # test that all teardown_requests get passed the same original813 # exception.814 try:815 raise TypeError()816 except Exception:817 pass818819 @app.route("/")820 def fails():821 1 // 0822823 rv = client.get("/")824 assert rv.status_code == 500825 assert b"Internal Server Error" in rv.data826 assert len(called) == 2827828829def test_before_after_request_order(app, client):830 called = []831832 @app.before_request833 def before1():834 called.append(1)835836 @app.before_request837 def before2():838 called.append(2)839840 @app.after_request841 def after1(response):842 called.append(4)843 return response844845 @app.after_request846 def after2(response):847 called.append(3)848 return response849850 @app.teardown_request851 def finish1(exc):852 called.append(6)853854 @app.teardown_request855 def finish2(exc):856 called.append(5)857858 @app.route("/")859 def index():860 return "42"861862 rv = client.get("/")863 assert rv.data == b"42"864 assert called == [1, 2, 3, 4, 5, 6]865866867def test_error_handling(app, client):868 app.testing = False869870 @app.errorhandler(404)871 def not_found(e):872 return "not found", 404873874 @app.errorhandler(500)875 def internal_server_error(e):876 return "internal server error", 500877878 @app.errorhandler(Forbidden)879 def forbidden(e):880 return "forbidden", 403881882 @app.route("/")883 def index():884 flask.abort(404)885886 @app.route("/error")887 def error():888 1 // 0889890 @app.route("/forbidden")891 def error2():892 flask.abort(403)893894 rv = client.get("/")895 assert rv.status_code == 404896 assert rv.data == b"not found"897 rv = client.get("/error")898 assert rv.status_code == 500899 assert b"internal server error" == rv.data900 rv = client.get("/forbidden")901 assert rv.status_code == 403902 assert b"forbidden" == rv.data903904905def test_error_handler_unknown_code(app):906 with pytest.raises(KeyError) as exc_info:907 app.register_error_handler(999, lambda e: ("999", 999))908909 assert "Use a subclass" in exc_info.value.args[0]910911912def test_error_handling_processing(app, client):913 app.testing = False914915 @app.errorhandler(500)916 def internal_server_error(e):917 return "internal server error", 500918919 @app.route("/")920 def broken_func():921 1 // 0922923 @app.after_request924 def after_request(resp):925 resp.mimetype = "text/x-special"926 return resp927928 resp = client.get("/")929 assert resp.mimetype == "text/x-special"930 assert resp.data == b"internal server error"931932933def test_baseexception_error_handling(app, client):934 app.testing = False935936 @app.route("/")937 def broken_func():938 raise KeyboardInterrupt()939940 with pytest.raises(KeyboardInterrupt):941 client.get("/")942943 ctx = flask._request_ctx_stack.top944 assert ctx.preserved945 assert type(ctx._preserved_exc) is KeyboardInterrupt946947948def test_before_request_and_routing_errors(app, client):949 @app.before_request950 def attach_something():951 flask.g.something = "value"952953 @app.errorhandler(404)954 def return_something(error):955 return flask.g.something, 404956957 rv = client.get("/")958 assert rv.status_code == 404959 assert rv.data == b"value"960961962def test_user_error_handling(app, client):963 class MyException(Exception):964 pass965966 @app.errorhandler(MyException)967 def handle_my_exception(e):968 assert isinstance(e, MyException)969 return "42"970971 @app.route("/")972 def index():973 raise MyException()974975 assert client.get("/").data == b"42"976977978def test_http_error_subclass_handling(app, client):979 class ForbiddenSubclass(Forbidden):980 pass981982 @app.errorhandler(ForbiddenSubclass)983 def handle_forbidden_subclass(e):984 assert isinstance(e, ForbiddenSubclass)985 return "banana"986987 @app.errorhandler(403)988 def handle_403(e):989 assert not isinstance(e, ForbiddenSubclass)990 assert isinstance(e, Forbidden)991 return "apple"992993 @app.route("/1")994 def index1():995 raise ForbiddenSubclass()996997 @app.route("/2")998 def index2():999 flask.abort(403)10001001 @app.route("/3")1002 def index3():1003 raise Forbidden()10041005 assert client.get("/1").data == b"banana"1006 assert client.get("/2").data == b"apple"1007 assert client.get("/3").data == b"apple"100810091010def test_errorhandler_precedence(app, client):1011 class E1(Exception):1012 pass10131014 class E2(Exception):1015 pass10161017 class E3(E1, E2):1018 pass10191020 @app.errorhandler(E2)1021 def handle_e2(e):1022 return "E2"10231024 @app.errorhandler(Exception)1025 def handle_exception(e):1026 return "Exception"10271028 @app.route("/E1")1029 def raise_e1():1030 raise E110311032 @app.route("/E3")1033 def raise_e3():1034 raise E310351036 rv = client.get("/E1")1037 assert rv.data == b"Exception"10381039 rv = client.get("/E3")1040 assert rv.data == b"E2"104110421043def test_trapping_of_bad_request_key_errors(app, client):1044 @app.route("/key")1045 def fail():1046 flask.request.form["missing_key"]10471048 @app.route("/abort")1049 def allow_abort():1050 flask.abort(400)10511052 rv = client.get("/key")1053 assert rv.status_code == 4001054 assert b"missing_key" not in rv.data1055 rv = client.get("/abort")1056 assert rv.status_code == 40010571058 app.debug = True1059 with pytest.raises(KeyError) as e:1060 client.get("/key")1061 assert e.errisinstance(BadRequest)1062 assert "missing_key" in e.value.get_description()1063 rv = client.get("/abort")1064 assert rv.status_code == 40010651066 app.debug = False1067 app.config["TRAP_BAD_REQUEST_ERRORS"] = True1068 with pytest.raises(KeyError):1069 client.get("/key")1070 with pytest.raises(BadRequest):1071 client.get("/abort")107210731074def test_trapping_of_all_http_exceptions(app, client):1075 app.config["TRAP_HTTP_EXCEPTIONS"] = True10761077 @app.route("/fail")1078 def fail():1079 flask.abort(404)10801081 with pytest.raises(NotFound):1082 client.get("/fail")108310841085def test_error_handler_after_processor_error(app, client):1086 app.testing = False10871088 @app.before_request1089 def before_request():1090 if _trigger == "before":1091 1 // 010921093 @app.after_request1094 def after_request(response):1095 if _trigger == "after":1096 1 // 01097 return response10981099 @app.route("/")1100 def index():1101 return "Foo"11021103 @app.errorhandler(500)1104 def internal_server_error(e):1105 return "Hello Server Error", 50011061107 for _trigger in "before", "after":1108 rv = client.get("/")1109 assert rv.status_code == 5001110 assert rv.data == b"Hello Server Error"111111121113def test_enctype_debug_helper(app, client):1114 from flask.debughelpers import DebugFilesKeyError11151116 app.debug = True11171118 @app.route("/fail", methods=["POST"])1119 def index():1120 return flask.request.files["foo"].filename11211122 # with statement is important because we leave an exception on the1123 # stack otherwise and we want to ensure that this is not the case1124 # to not negatively affect other tests.1125 with client:1126 with pytest.raises(DebugFilesKeyError) as e:1127 client.post("/fail", data={"foo": "index.txt"})1128 assert "no file contents were transmitted" in str(e.value)1129 assert "This was submitted: 'index.txt'" in str(e.value)113011311132def test_response_types(app, client):1133 @app.route("/text")1134 def from_text():1135 return "Hällo Wörld"11361137 @app.route("/bytes")1138 def from_bytes():1139 return "Hällo Wörld".encode()11401141 @app.route("/full_tuple")1142 def from_full_tuple():1143 return (1144 "Meh",1145 400,1146 {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1147 )11481149 @app.route("/text_headers")1150 def from_text_headers():1151 return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}11521153 @app.route("/text_status")1154 def from_text_status():1155 return "Hi, status!", 40011561157 @app.route("/response_headers")1158 def from_response_headers():1159 return (1160 flask.Response(1161 "Hello world", 404, {"Content-Type": "text/html", "X-Foo": "Baz"}1162 ),1163 {"Content-Type": "text/plain", "X-Foo": "Bar", "X-Bar": "Foo"},1164 )11651166 @app.route("/response_status")1167 def from_response_status():1168 return app.response_class("Hello world", 400), 50011691170 @app.route("/wsgi")1171 def from_wsgi():1172 return NotFound()11731174 @app.route("/dict")1175 def from_dict():1176 return {"foo": "bar"}, 20111771178 assert client.get("/text").data == "Hällo Wörld".encode()1179 assert client.get("/bytes").data == "Hällo Wörld".encode()11801181 rv = client.get("/full_tuple")1182 assert rv.data == b"Meh"1183 assert rv.headers["X-Foo"] == "Testing"1184 assert rv.status_code == 4001185 assert rv.mimetype == "text/plain"11861187 rv = client.get("/text_headers")1188 assert rv.data == b"Hello"1189 assert rv.headers["X-Foo"] == "Test"1190 assert rv.status_code == 2001191 assert rv.mimetype == "text/plain"11921193 rv = client.get("/text_status")1194 assert rv.data == b"Hi, status!"1195 assert rv.status_code == 4001196 assert rv.mimetype == "text/html"11971198 rv = client.get("/response_headers")1199 assert rv.data == b"Hello world"1200 assert rv.content_type == "text/plain"1201 assert rv.headers.getlist("X-Foo") == ["Bar"]1202 assert rv.headers["X-Bar"] == "Foo"1203 assert rv.status_code == 40412041205 rv = client.get("/response_status")1206 assert rv.data == b"Hello world"1207 assert rv.status_code == 50012081209 rv = client.get("/wsgi")1210 assert b"Not Found" in rv.data1211 assert rv.status_code == 40412121213 rv = client.get("/dict")1214 assert rv.json == {"foo": "bar"}1215 assert rv.status_code == 201121612171218def test_response_type_errors():1219 app = flask.Flask(__name__)1220 app.testing = True12211222 @app.route("/none")1223 def from_none():1224 pass12251226 @app.route("/small_tuple")1227 def from_small_tuple():1228 return ("Hello",)12291230 @app.route("/large_tuple")1231 def from_large_tuple():1232 return "Hello", 234, {"X-Foo": "Bar"}, "???"12331234 @app.route("/bad_type")1235 def from_bad_type():1236 return True12371238 @app.route("/bad_wsgi")1239 def from_bad_wsgi():1240 return lambda: None12411242 c = app.test_client()12431244 with pytest.raises(TypeError) as e:1245 c.get("/none")1246 assert "returned None" in str(e.value)1247 assert "from_none" in str(e.value)12481249 with pytest.raises(TypeError) as e:1250 c.get("/small_tuple")1251 assert "tuple must have the form" in str(e.value)12521253 pytest.raises(TypeError, c.get, "/large_tuple")12541255 with pytest.raises(TypeError) as e:1256 c.get("/bad_type")1257 assert "it was a bool" in str(e.value)12581259 pytest.raises(TypeError, c.get, "/bad_wsgi")126012611262def test_make_response(app, req_ctx):1263 rv = flask.make_response()1264 assert rv.status_code == 2001265 assert rv.data == b""1266 assert rv.mimetype == "text/html"12671268 rv = flask.make_response("Awesome")1269 assert rv.status_code == 2001270 assert rv.data == b"Awesome"1271 assert rv.mimetype == "text/html"12721273 rv = flask.make_response("W00t", 404)1274 assert rv.status_code == 4041275 assert rv.data == b"W00t"1276 assert rv.mimetype == "text/html"127712781279def test_make_response_with_response_instance(app, req_ctx):1280 rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1281 assert rv.status_code == 4001282 assert rv.data == b'{"msg":"W00t"}\n'1283 assert rv.mimetype == "application/json"12841285 rv = flask.make_response(flask.Response(""), 400)1286 assert rv.status_code == 4001287 assert rv.data == b""1288 assert rv.mimetype == "text/html"12891290 rv = flask.make_response(1291 flask.Response("", headers={"Content-Type": "text/html"}),1292 400,1293 [("X-Foo", "bar")],1294 )1295 assert rv.status_code == 4001296 assert rv.headers["Content-Type"] == "text/html"1297 assert rv.headers["X-Foo"] == "bar"129812991300def test_jsonify_no_prettyprint(app, req_ctx):1301 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1302 compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1303 uncompressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}13041305 rv = flask.make_response(flask.jsonify(uncompressed_msg), 200)1306 assert rv.data == compressed_msg130713081309def test_jsonify_prettyprint(app, req_ctx):1310 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1311 compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1312 pretty_response = (1313 b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'1314 )13151316 rv = flask.make_response(flask.jsonify(compressed_msg), 200)1317 assert rv.data == pretty_response131813191320def test_jsonify_mimetype(app, req_ctx):1321 app.config.update({"JSONIFY_MIMETYPE": "application/vnd.api+json"})1322 msg = {"msg": {"submsg": "W00t"}}1323 rv = flask.make_response(flask.jsonify(msg), 200)1324 assert rv.mimetype == "application/vnd.api+json"132513261327def test_json_dump_dataclass(app, req_ctx):1328 from dataclasses import make_dataclass13291330 Data = make_dataclass("Data", [("name", str)])1331 value = flask.json.dumps(Data("Flask"), app=app)1332 value = flask.json.loads(value, app=app)1333 assert value == {"name": "Flask"}133413351336def test_jsonify_args_and_kwargs_check(app, req_ctx):1337 with pytest.raises(TypeError) as e:1338 flask.jsonify("fake args", kwargs="fake")1339 assert "behavior undefined" in str(e.value)134013411342def test_url_generation(app, req_ctx):1343 @app.route("/hello/<name>", methods=["POST"])1344 def hello():1345 pass13461347 assert flask.url_for("hello", name="test x") == "/hello/test%20x"1348 assert (1349 flask.url_for("hello", name="test x", _external=True)1350 == "http://localhost/hello/test%20x"1351 )135213531354def test_build_error_handler(app):1355 # Test base case, a URL which results in a BuildError.1356 with app.test_request_context():1357 pytest.raises(BuildError, flask.url_for, "spam")13581359 # Verify the error is re-raised if not the current exception.1360 try:1361 with app.test_request_context():1362 flask.url_for("spam")1363 except BuildError as err:1364 error = err1365 try:1366 raise RuntimeError("Test case where BuildError is not current.")1367 except RuntimeError:1368 pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})13691370 # Test a custom handler.1371 def handler(error, endpoint, values):1372 # Just a test.1373 return "/test_handler/"13741375 app.url_build_error_handlers.append(handler)1376 with app.test_request_context():1377 assert flask.url_for("spam") == "/test_handler/"137813791380def test_build_error_handler_reraise(app):1381 # Test a custom handler which reraises the BuildError1382 def handler_raises_build_error(error, endpoint, values):1383 raise error13841385 app.url_build_error_handlers.append(handler_raises_build_error)13861387 with app.test_request_context():1388 pytest.raises(BuildError, flask.url_for, "not.existing")138913901391def test_url_for_passes_special_values_to_build_error_handler(app):1392 @app.url_build_error_handlers.append1393 def handler(error, endpoint, values):1394 assert values == {1395 "_external": False,1396 "_anchor": None,1397 "_method": None,1398 "_scheme": None,1399 }1400 return "handled"14011402 with app.test_request_context():1403 flask.url_for("/")140414051406def test_static_files(app, client):1407 rv = client.get("/static/index.html")1408 assert rv.status_code == 2001409 assert rv.data.strip() == b"<h1>Hello World!</h1>"1410 with app.test_request_context():1411 assert flask.url_for("static", filename="index.html") == "/static/index.html"1412 rv.close()141314141415def test_static_url_path():1416 app = flask.Flask(__name__, static_url_path="/foo")1417 app.testing = True1418 rv = app.test_client().get("/foo/index.html")1419 assert rv.status_code == 2001420 rv.close()14211422 with app.test_request_context():1423 assert flask.url_for("static", filename="index.html") == "/foo/index.html"142414251426def test_static_url_path_with_ending_slash():1427 app = flask.Flask(__name__, static_url_path="/foo/")1428 app.testing = True1429 rv = app.test_client().get("/foo/index.html")1430 assert rv.status_code == 2001431 rv.close()14321433 with app.test_request_context():1434 assert flask.url_for("static", filename="index.html") == "/foo/index.html"143514361437def test_static_url_empty_path(app):1438 app = flask.Flask(__name__, static_folder="", static_url_path="")1439 rv = app.test_client().open("/static/index.html", method="GET")1440 assert rv.status_code == 2001441 rv.close()144214431444def test_static_url_empty_path_default(app):1445 app = flask.Flask(__name__, static_folder="")1446 rv = app.test_client().open("/static/index.html", method="GET")1447 assert rv.status_code == 2001448 rv.close()144914501451def test_static_folder_with_pathlib_path(app):1452 from pathlib import Path14531454 app = flask.Flask(__name__, static_folder=Path("static"))1455 rv = app.test_client().open("/static/index.html", method="GET")1456 assert rv.status_code == 2001457 rv.close()145814591460def test_static_folder_with_ending_slash():1461 app = flask.Flask(__name__, static_folder="static/")14621463 @app.route("/<path:path>")1464 def catch_all(path):1465 return path14661467 rv = app.test_client().get("/catch/all")1468 assert rv.data == b"catch/all"146914701471def test_static_route_with_host_matching():1472 app = flask.Flask(__name__, host_matching=True, static_host="example.com")1473 c = app.test_client()1474 rv = c.get("http://example.com/static/index.html")1475 assert rv.status_code == 2001476 rv.close()1477 with app.test_request_context():1478 rv = flask.url_for("static", filename="index.html", _external=True)1479 assert rv == "http://example.com/static/index.html"1480 # Providing static_host without host_matching=True should error.1481 with pytest.raises(Exception):1482 flask.Flask(__name__, static_host="example.com")1483 # Providing host_matching=True with static_folder1484 # but without static_host should error.1485 with pytest.raises(Exception):1486 flask.Flask(__name__, host_matching=True)1487 # Providing host_matching=True without static_host1488 # but with static_folder=None should not error.1489 flask.Flask(__name__, host_matching=True, static_folder=None)149014911492def test_request_locals():1493 assert repr(flask.g) == "<LocalProxy unbound>"1494 assert not flask.g149514961497def test_server_name_subdomain():1498 app = flask.Flask(__name__, subdomain_matching=True)1499 client = app.test_client()15001501 @app.route("/")1502 def index():1503 return "default"15041505 @app.route("/", subdomain="foo")1506 def subdomain():1507 return "subdomain"15081509 app.config["SERVER_NAME"] = "dev.local:5000"1510 rv = client.get("/")1511 assert rv.data == b"default"15121513 rv = client.get("/", "http://dev.local:5000")1514 assert rv.data == b"default"15151516 rv = client.get("/", "https://dev.local:5000")1517 assert rv.data == b"default"15181519 app.config["SERVER_NAME"] = "dev.local:443"1520 rv = client.get("/", "https://dev.local")15211522 # Werkzeug 1.0 fixes matching https scheme with 443 port1523 if rv.status_code != 404:1524 assert rv.data == b"default"15251526 app.config["SERVER_NAME"] = "dev.local"1527 rv = client.get("/", "https://dev.local")1528 assert rv.data == b"default"1529

Merge branch '2.0.x'David Lordbefore adoptione37e871

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

Merge pull request #3706 from pallets/dependabot/pip/tox-3.18.1dependabot-preview[bot]before adoptionfd0a608

lines 1535–1541why, one step back
1535 rv = client.get("/", "http://foo.localhost")
1536 assert rv.status_code == 40415371538 rv = client.get("/", "http://foo.dev.local")1539 assert rv.data == b"subdomain"15401541

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

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

Merge pull request #3706 from pallets/dependabot/pip/tox-3.18.1dependabot-preview[bot]before adoptionfd0a608

lines 1544–1635why, one step back
1544def test_exception_propagation(app, client):
1545 def apprunner(config_key):1546 @app.route("/")1547 def index():1548 1 // 015491550 if config_key is not None:1551 app.config[config_key] = True1552 with pytest.raises(Exception):1553 client.get("/")1554 else:1555 assert client.get("/").status_code == 50015561557 # we have to run this test in an isolated thread because if the1558 # debug flag is set to true and an exception happens the context is1559 # not torn down. This causes other tests that run after this fail1560 # when they expect no exception on the stack.1561 for config_key in "TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None:1562 t = Thread(target=apprunner, args=(config_key,))1563 t.start()1564 t.join()156515661567@pytest.mark.parametrize("debug", [True, False])1568@pytest.mark.parametrize("use_debugger", [True, False])1569@pytest.mark.parametrize("use_reloader", [True, False])1570@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1571def test_werkzeug_passthrough_errors(1572 monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1573):1574 rv = {}15751576 # Mocks werkzeug.serving.run_simple method1577 def run_simple_mock(*args, **kwargs):1578 rv["passthrough_errors"] = kwargs.get("passthrough_errors")15791580 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1581 app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1582 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)158315841585def test_max_content_length(app, client):1586 app.config["MAX_CONTENT_LENGTH"] = 6415871588 @app.before_request1589 def always_first():1590 flask.request.form["myfile"]1591 AssertionError()15921593 @app.route("/accept", methods=["POST"])1594 def accept_file():1595 flask.request.form["myfile"]1596 AssertionError()15971598 @app.errorhandler(413)1599 def catcher(error):1600 return "42"16011602 rv = client.post("/accept", data={"myfile": "foo" * 100})1603 assert rv.data == b"42"160416051606def test_url_processors(app, client):1607 @app.url_defaults1608 def add_language_code(endpoint, values):1609 if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1610 endpoint, "lang_code"1611 ):1612 values.setdefault("lang_code", flask.g.lang_code)16131614 @app.url_value_preprocessor1615 def pull_lang_code(endpoint, values):1616 flask.g.lang_code = values.pop("lang_code", None)16171618 @app.route("/<lang_code>/")1619 def index():1620 return flask.url_for("about")16211622 @app.route("/<lang_code>/about")1623 def about():1624 return flask.url_for("something_else")16251626 @app.route("/foo")1627 def something_else():1628 return flask.url_for("about", lang_code="en")16291630 assert client.get("/de/").data == b"/de/about"1631 assert client.get("/de/about").data == b"/foo"1632 assert client.get("/foo").data == b"/en/about"163316341635def test_inject_blueprint_url_defaults(app):

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

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

Merge pull request #3706 from pallets/dependabot/pip/tox-3.18.1dependabot-preview[bot]before adoptionfd0a608

lines 1637–1648why, one step back
1637
1638 @bp.url_defaults1639 def bp_defaults(endpoint, values):1640 values["page"] = "login"16411642 @bp.route("/<page>")1643 def view(page):1644 pass16451646 app.register_blueprint(bp)16471648 values = dict()

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

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

Merge pull request #3706 from pallets/dependabot/pip/tox-3.18.1dependabot-preview[bot]before adoptionfd0a608

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

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

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

Merge pull request #3706 from pallets/dependabot/pip/tox-3.18.1dependabot-preview[bot]before adoptionfd0a608

lines 1655–1727why, one step back
1655 expected = "/login"
1656 assert url == expected165716581659def test_nonascii_pathinfo(app, client):1660 @app.route("/киртест")1661 def index():1662 return "Hello World!"16631664 rv = client.get("/киртест")1665 assert rv.data == b"Hello World!"166616671668def test_debug_mode_complains_after_first_request(app, client):1669 app.debug = True16701671 @app.route("/")1672 def index():1673 return "Awesome"16741675 assert not app.got_first_request1676 assert client.get("/").data == b"Awesome"1677 with pytest.raises(AssertionError) as e:16781679 @app.route("/foo")1680 def broken():1681 return "Meh"16821683 assert "A setup function was called" in str(e.value)16841685 app.debug = False16861687 @app.route("/foo")1688 def working():1689 return "Meh"16901691 assert client.get("/foo").data == b"Meh"1692 assert app.got_first_request169316941695def test_before_first_request_functions(app, client):1696 got = []16971698 @app.before_first_request1699 def foo():1700 got.append(42)17011702 client.get("/")1703 assert got == [42]1704 client.get("/")1705 assert got == [42]1706 assert app.got_first_request170717081709def test_before_first_request_functions_concurrent(app, client):1710 got = []17111712 @app.before_first_request1713 def foo():1714 time.sleep(0.2)1715 got.append(42)17161717 def get_and_assert():1718 client.get("/")1719 assert got == [42]17201721 t = Thread(target=get_and_assert)1722 t.start()1723 get_and_assert()1724 t.join()1725 assert app.got_first_request17261727

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

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

Merge pull request #3706 from pallets/dependabot/pip/tox-3.18.1dependabot-preview[bot]before adoptionfd0a608

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

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

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

Merge pull request #3706 from pallets/dependabot/pip/tox-3.18.1dependabot-preview[bot]before adoptionfd0a608

line 1736why, one step back
1736

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

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

Merge pull request #3706 from pallets/dependabot/pip/tox-3.18.1dependabot-preview[bot]before adoptionfd0a608

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

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

lines 1742–1750why, one step back
1742 rv = client.get("/foo", data={}, follow_redirects=True)
1743 assert rv.data == b"success"17441745 monkeypatch.setattr(RequestRedirect, "code", 301)17461747 with client, pytest.raises(AssertionError) as e:1748 client.post("/foo", data={})17491750 assert "canonical URL 'http://localhost/foo/'" in str(e.value)

Merge pull request #3706 from pallets/dependabot/pip/tox-3.18.1dependabot-preview[bot]before adoptionfd0a608

lines 1751–1901why, one step back
1751
17521753def test_route_decorator_custom_endpoint(app, client):1754 app.debug = True17551756 @app.route("/foo/")1757 def foo():1758 return flask.request.endpoint17591760 @app.route("/bar/", endpoint="bar")1761 def for_bar():1762 return flask.request.endpoint17631764 @app.route("/bar/123", endpoint="123")1765 def for_bar_foo():1766 return flask.request.endpoint17671768 with app.test_request_context():1769 assert flask.url_for("foo") == "/foo/"1770 assert flask.url_for("bar") == "/bar/"1771 assert flask.url_for("123") == "/bar/123"17721773 assert client.get("/foo/").data == b"foo"1774 assert client.get("/bar/").data == b"bar"1775 assert client.get("/bar/123").data == b"123"177617771778def test_preserve_only_once(app, client):1779 app.debug = True17801781 @app.route("/fail")1782 def fail_func():1783 1 // 017841785 for _x in range(3):1786 with pytest.raises(ZeroDivisionError):1787 client.get("/fail")17881789 assert flask._request_ctx_stack.top is not None1790 assert flask._app_ctx_stack.top is not None1791 # implicit appctx disappears too1792 flask._request_ctx_stack.top.pop()1793 assert flask._request_ctx_stack.top is None1794 assert flask._app_ctx_stack.top is None179517961797def test_preserve_remembers_exception(app, client):1798 app.debug = True1799 errors = []18001801 @app.route("/fail")1802 def fail_func():1803 1 // 018041805 @app.route("/success")1806 def success_func():1807 return "Okay"18081809 @app.teardown_request1810 def teardown_handler(exc):1811 errors.append(exc)18121813 # After this failure we did not yet call the teardown handler1814 with pytest.raises(ZeroDivisionError):1815 client.get("/fail")1816 assert errors == []18171818 # But this request triggers it, and it's an error1819 client.get("/success")1820 assert len(errors) == 21821 assert isinstance(errors[0], ZeroDivisionError)18221823 # At this point another request does nothing.1824 client.get("/success")1825 assert len(errors) == 31826 assert errors[1] is None182718281829def test_get_method_on_g(app_ctx):1830 assert flask.g.get("x") is None1831 assert flask.g.get("x", 11) == 111832 flask.g.x = 421833 assert flask.g.get("x") == 421834 assert flask.g.x == 42183518361837def test_g_iteration_protocol(app_ctx):1838 flask.g.foo = 231839 flask.g.bar = 421840 assert "foo" in flask.g1841 assert "foos" not in flask.g1842 assert sorted(flask.g) == ["bar", "foo"]184318441845def test_subdomain_basic_support():1846 app = flask.Flask(__name__, subdomain_matching=True)1847 app.config["SERVER_NAME"] = "localhost.localdomain"1848 client = app.test_client()18491850 @app.route("/")1851 def normal_index():1852 return "normal index"18531854 @app.route("/", subdomain="test")1855 def test_index():1856 return "test index"18571858 rv = client.get("/", "http://localhost.localdomain/")1859 assert rv.data == b"normal index"18601861 rv = client.get("/", "http://test.localhost.localdomain/")1862 assert rv.data == b"test index"186318641865def test_subdomain_matching():1866 app = flask.Flask(__name__, subdomain_matching=True)1867 client = app.test_client()1868 app.config["SERVER_NAME"] = "localhost.localdomain"18691870 @app.route("/", subdomain="<user>")1871 def index(user):1872 return f"index for {user}"18731874 rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1875 assert rv.data == b"index for mitsuhiko"187618771878def test_subdomain_matching_with_ports():1879 app = flask.Flask(__name__, subdomain_matching=True)1880 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1881 client = app.test_client()18821883 @app.route("/", subdomain="<user>")1884 def index(user):1885 return f"index for {user}"18861887 rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1888 assert rv.data == b"index for mitsuhiko"188918901891@pytest.mark.parametrize("matching", (False, True))1892def test_subdomain_matching_other_name(matching):1893 app = flask.Flask(__name__, subdomain_matching=matching)1894 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1895 client = app.test_client()18961897 @app.route("/")1898 def index():1899 return "", 20419001901 # suppress Werkzeug 0.15 warning about name mismatch

Merge branch '2.0.x'David Lordbefore adoptione37e871

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

Merge pull request #3706 from pallets/dependabot/pip/tox-3.18.1dependabot-preview[bot]before adoptionfd0a608

lines 1906–2019why, one step back
1906 # ip address can't match name
1907 rv = client.get("/", "http://127.0.0.1:3000/")1908 assert rv.status_code == 404 if matching else 20419091910 # allow all subdomains if matching is disabled1911 rv = client.get("/", "http://www.localhost.localdomain:3000/")1912 assert rv.status_code == 404 if matching else 204191319141915def test_multi_route_rules(app, client):1916 @app.route("/")1917 @app.route("/<test>/")1918 def index(test="a"):1919 return test19201921 rv = client.open("/")1922 assert rv.data == b"a"1923 rv = client.open("/b/")1924 assert rv.data == b"b"192519261927def test_multi_route_class_views(app, client):1928 class View:1929 def __init__(self, app):1930 app.add_url_rule("/", "index", self.index)1931 app.add_url_rule("/<test>/", "index", self.index)19321933 def index(self, test="a"):1934 return test19351936 _ = View(app)1937 rv = client.open("/")1938 assert rv.data == b"a"1939 rv = client.open("/b/")1940 assert rv.data == b"b"194119421943def test_run_defaults(monkeypatch, app):1944 rv = {}19451946 # Mocks werkzeug.serving.run_simple method1947 def run_simple_mock(*args, **kwargs):1948 rv["result"] = "running..."19491950 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1951 app.run()1952 assert rv["result"] == "running..."195319541955def test_run_server_port(monkeypatch, app):1956 rv = {}19571958 # Mocks werkzeug.serving.run_simple method1959 def run_simple_mock(hostname, port, application, *args, **kwargs):1960 rv["result"] = f"running on {hostname}:{port} ..."19611962 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1963 hostname, port = "localhost", 80001964 app.run(hostname, port, debug=True)1965 assert rv["result"] == f"running on {hostname}:{port} ..."196619671968@pytest.mark.parametrize(1969 "host,port,server_name,expect_host,expect_port",1970 (1971 (None, None, "pocoo.org:8080", "pocoo.org", 8080),1972 ("localhost", None, "pocoo.org:8080", "localhost", 8080),1973 (None, 80, "pocoo.org:8080", "pocoo.org", 80),1974 ("localhost", 80, "pocoo.org:8080", "localhost", 80),1975 ("localhost", 0, "localhost:8080", "localhost", 0),1976 (None, None, "localhost:8080", "localhost", 8080),1977 (None, None, "localhost:0", "localhost", 0),1978 ),1979)1980def test_run_from_config(1981 monkeypatch, host, port, server_name, expect_host, expect_port, app1982):1983 def run_simple_mock(hostname, port, *args, **kwargs):1984 assert hostname == expect_host1985 assert port == expect_port19861987 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1988 app.config["SERVER_NAME"] = server_name1989 app.run(host, port)199019911992def test_max_cookie_size(app, client, recwarn):1993 app.config["MAX_COOKIE_SIZE"] = 10019941995 # outside app context, default to Werkzeug static value,1996 # which is also the default config1997 response = flask.Response()1998 default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1999 assert response.max_cookie_size == default2000

The first 2,000 of 2,035 lines.