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 #4443 from pallets/update-requirementsDavid Lordbefore adoptiond6496c8

History of this file

Take it

The walk stopped after 200 commits: lines older than e071734 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 #3734 from pallets/dependabot/pip/sphinx-3.2.1dependabot-preview[bot]before adoptione071734

lines 2–5why, one step back
2import re
3import sys4import time5import uuid

Merge pull request #4443 from pallets/update-requirementsDavid Lordbefore adoptiond6496c8

line 6why, one step back
6import warnings

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

line 7why, one step back
7import weakref

Merge pull request #3734 from pallets/dependabot/pip/sphinx-3.2.1dependabot-preview[bot]before adoptione071734

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

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

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

Merge pull request #3734 from pallets/dependabot/pip/sphinx-3.2.1dependabot-preview[bot]before adoptione071734

lines 10–22why, one step back
10from threading import Thread
1112import pytest13import werkzeug.serving14from werkzeug.exceptions import BadRequest15from werkzeug.exceptions import Forbidden16from werkzeug.exceptions import NotFound17from werkzeug.http import parse_date18from werkzeug.routing import BuildError1920import 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 #3734 from pallets/dependabot/pip/sphinx-3.2.1dependabot-preview[bot]before adoptione071734

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 #3734 from pallets/dependabot/pip/sphinx-3.2.1dependabot-preview[bot]before adoptione071734

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 #3734 from pallets/dependabot/pip/sphinx-3.2.1dependabot-preview[bot]before adoptione071734

lines 356–1530why, 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"132513261327@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")1328def test_json_dump_dataclass(app, req_ctx):1329 from dataclasses import make_dataclass13301331 Data = make_dataclass("Data", [("name", str)])1332 value = flask.json.dumps(Data("Flask"), app=app)1333 value = flask.json.loads(value, app=app)1334 assert value == {"name": "Flask"}133513361337def test_jsonify_args_and_kwargs_check(app, req_ctx):1338 with pytest.raises(TypeError) as e:1339 flask.jsonify("fake args", kwargs="fake")1340 assert "behavior undefined" in str(e.value)134113421343def test_url_generation(app, req_ctx):1344 @app.route("/hello/<name>", methods=["POST"])1345 def hello():1346 pass13471348 assert flask.url_for("hello", name="test x") == "/hello/test%20x"1349 assert (1350 flask.url_for("hello", name="test x", _external=True)1351 == "http://localhost/hello/test%20x"1352 )135313541355def test_build_error_handler(app):1356 # Test base case, a URL which results in a BuildError.1357 with app.test_request_context():1358 pytest.raises(BuildError, flask.url_for, "spam")13591360 # Verify the error is re-raised if not the current exception.1361 try:1362 with app.test_request_context():1363 flask.url_for("spam")1364 except BuildError as err:1365 error = err1366 try:1367 raise RuntimeError("Test case where BuildError is not current.")1368 except RuntimeError:1369 pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})13701371 # Test a custom handler.1372 def handler(error, endpoint, values):1373 # Just a test.1374 return "/test_handler/"13751376 app.url_build_error_handlers.append(handler)1377 with app.test_request_context():1378 assert flask.url_for("spam") == "/test_handler/"137913801381def test_build_error_handler_reraise(app):1382 # Test a custom handler which reraises the BuildError1383 def handler_raises_build_error(error, endpoint, values):1384 raise error13851386 app.url_build_error_handlers.append(handler_raises_build_error)13871388 with app.test_request_context():1389 pytest.raises(BuildError, flask.url_for, "not.existing")139013911392def test_url_for_passes_special_values_to_build_error_handler(app):1393 @app.url_build_error_handlers.append1394 def handler(error, endpoint, values):1395 assert values == {1396 "_external": False,1397 "_anchor": None,1398 "_method": None,1399 "_scheme": None,1400 }1401 return "handled"14021403 with app.test_request_context():1404 flask.url_for("/")140514061407def test_static_files(app, client):1408 rv = client.get("/static/index.html")1409 assert rv.status_code == 2001410 assert rv.data.strip() == b"<h1>Hello World!</h1>"1411 with app.test_request_context():1412 assert flask.url_for("static", filename="index.html") == "/static/index.html"1413 rv.close()141414151416def test_static_url_path():1417 app = flask.Flask(__name__, static_url_path="/foo")1418 app.testing = True1419 rv = app.test_client().get("/foo/index.html")1420 assert rv.status_code == 2001421 rv.close()14221423 with app.test_request_context():1424 assert flask.url_for("static", filename="index.html") == "/foo/index.html"142514261427def test_static_url_path_with_ending_slash():1428 app = flask.Flask(__name__, static_url_path="/foo/")1429 app.testing = True1430 rv = app.test_client().get("/foo/index.html")1431 assert rv.status_code == 2001432 rv.close()14331434 with app.test_request_context():1435 assert flask.url_for("static", filename="index.html") == "/foo/index.html"143614371438def test_static_url_empty_path(app):1439 app = flask.Flask(__name__, static_folder="", static_url_path="")1440 rv = app.test_client().open("/static/index.html", method="GET")1441 assert rv.status_code == 2001442 rv.close()144314441445def test_static_url_empty_path_default(app):1446 app = flask.Flask(__name__, static_folder="")1447 rv = app.test_client().open("/static/index.html", method="GET")1448 assert rv.status_code == 2001449 rv.close()145014511452def test_static_folder_with_pathlib_path(app):1453 from pathlib import Path14541455 app = flask.Flask(__name__, static_folder=Path("static"))1456 rv = app.test_client().open("/static/index.html", method="GET")1457 assert rv.status_code == 2001458 rv.close()145914601461def test_static_folder_with_ending_slash():1462 app = flask.Flask(__name__, static_folder="static/")14631464 @app.route("/<path:path>")1465 def catch_all(path):1466 return path14671468 rv = app.test_client().get("/catch/all")1469 assert rv.data == b"catch/all"147014711472def test_static_route_with_host_matching():1473 app = flask.Flask(__name__, host_matching=True, static_host="example.com")1474 c = app.test_client()1475 rv = c.get("http://example.com/static/index.html")1476 assert rv.status_code == 2001477 rv.close()1478 with app.test_request_context():1479 rv = flask.url_for("static", filename="index.html", _external=True)1480 assert rv == "http://example.com/static/index.html"1481 # Providing static_host without host_matching=True should error.1482 with pytest.raises(Exception):1483 flask.Flask(__name__, static_host="example.com")1484 # Providing host_matching=True with static_folder1485 # but without static_host should error.1486 with pytest.raises(Exception):1487 flask.Flask(__name__, host_matching=True)1488 # Providing host_matching=True without static_host1489 # but with static_folder=None should not error.1490 flask.Flask(__name__, host_matching=True, static_folder=None)149114921493def test_request_locals():1494 assert repr(flask.g) == "<LocalProxy unbound>"1495 assert not flask.g149614971498def test_server_name_subdomain():1499 app = flask.Flask(__name__, subdomain_matching=True)1500 client = app.test_client()15011502 @app.route("/")1503 def index():1504 return "default"15051506 @app.route("/", subdomain="foo")1507 def subdomain():1508 return "subdomain"15091510 app.config["SERVER_NAME"] = "dev.local:5000"1511 rv = client.get("/")1512 assert rv.data == b"default"15131514 rv = client.get("/", "http://dev.local:5000")1515 assert rv.data == b"default"15161517 rv = client.get("/", "https://dev.local:5000")1518 assert rv.data == b"default"15191520 app.config["SERVER_NAME"] = "dev.local:443"1521 rv = client.get("/", "https://dev.local")15221523 # Werkzeug 1.0 fixes matching https scheme with 443 port1524 if rv.status_code != 404:1525 assert rv.data == b"default"15261527 app.config["SERVER_NAME"] = "dev.local"1528 rv = client.get("/", "https://dev.local")1529 assert rv.data == b"default"1530

Merge pull request #4443 from pallets/update-requirementsDavid Lordbefore adoptiond6496c8

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

Merge pull request #3734 from pallets/dependabot/pip/sphinx-3.2.1dependabot-preview[bot]before adoptione071734

lines 1536–1542why, one step back
1536 rv = client.get("/", "http://foo.localhost")
1537 assert rv.status_code == 40415381539 rv = client.get("/", "http://foo.dev.local")1540 assert rv.data == b"subdomain"15411542

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

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

Merge pull request #3734 from pallets/dependabot/pip/sphinx-3.2.1dependabot-preview[bot]before adoptione071734

lines 1545–1636why, one step back
1545def test_exception_propagation(app, client):
1546 def apprunner(config_key):1547 @app.route("/")1548 def index():1549 1 // 015501551 if config_key is not None:1552 app.config[config_key] = True1553 with pytest.raises(Exception):1554 client.get("/")1555 else:1556 assert client.get("/").status_code == 50015571558 # we have to run this test in an isolated thread because if the1559 # debug flag is set to true and an exception happens the context is1560 # not torn down. This causes other tests that run after this fail1561 # when they expect no exception on the stack.1562 for config_key in "TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None:1563 t = Thread(target=apprunner, args=(config_key,))1564 t.start()1565 t.join()156615671568@pytest.mark.parametrize("debug", [True, False])1569@pytest.mark.parametrize("use_debugger", [True, False])1570@pytest.mark.parametrize("use_reloader", [True, False])1571@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1572def test_werkzeug_passthrough_errors(1573 monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1574):1575 rv = {}15761577 # Mocks werkzeug.serving.run_simple method1578 def run_simple_mock(*args, **kwargs):1579 rv["passthrough_errors"] = kwargs.get("passthrough_errors")15801581 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1582 app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1583 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)158415851586def test_max_content_length(app, client):1587 app.config["MAX_CONTENT_LENGTH"] = 6415881589 @app.before_request1590 def always_first():1591 flask.request.form["myfile"]1592 AssertionError()15931594 @app.route("/accept", methods=["POST"])1595 def accept_file():1596 flask.request.form["myfile"]1597 AssertionError()15981599 @app.errorhandler(413)1600 def catcher(error):1601 return "42"16021603 rv = client.post("/accept", data={"myfile": "foo" * 100})1604 assert rv.data == b"42"160516061607def test_url_processors(app, client):1608 @app.url_defaults1609 def add_language_code(endpoint, values):1610 if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1611 endpoint, "lang_code"1612 ):1613 values.setdefault("lang_code", flask.g.lang_code)16141615 @app.url_value_preprocessor1616 def pull_lang_code(endpoint, values):1617 flask.g.lang_code = values.pop("lang_code", None)16181619 @app.route("/<lang_code>/")1620 def index():1621 return flask.url_for("about")16221623 @app.route("/<lang_code>/about")1624 def about():1625 return flask.url_for("something_else")16261627 @app.route("/foo")1628 def something_else():1629 return flask.url_for("about", lang_code="en")16301631 assert client.get("/de/").data == b"/de/about"1632 assert client.get("/de/about").data == b"/foo"1633 assert client.get("/foo").data == b"/en/about"163416351636def test_inject_blueprint_url_defaults(app):

Merge pull request #4045 from pallets/blueprint-name-dotDavid Lordbefore adoption08e459e

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

Merge pull request #3734 from pallets/dependabot/pip/sphinx-3.2.1dependabot-preview[bot]before adoptione071734

lines 1638–1649why, one step back
1638
1639 @bp.url_defaults1640 def bp_defaults(endpoint, values):1641 values["page"] = "login"16421643 @bp.route("/<page>")1644 def view(page):1645 pass16461647 app.register_blueprint(bp)16481649 values = dict()

Merge pull request #4045 from pallets/blueprint-name-dotDavid Lordbefore adoption08e459e

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

Merge pull request #3734 from pallets/dependabot/pip/sphinx-3.2.1dependabot-preview[bot]before adoptione071734

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

Merge pull request #4045 from pallets/blueprint-name-dotDavid Lordbefore adoption08e459e

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

Merge pull request #3734 from pallets/dependabot/pip/sphinx-3.2.1dependabot-preview[bot]before adoptione071734

lines 1656–1901why, one step back
1656 expected = "/login"
1657 assert url == expected165816591660def test_nonascii_pathinfo(app, client):1661 @app.route("/киртест")1662 def index():1663 return "Hello World!"16641665 rv = client.get("/киртест")1666 assert rv.data == b"Hello World!"166716681669def test_debug_mode_complains_after_first_request(app, client):1670 app.debug = True16711672 @app.route("/")1673 def index():1674 return "Awesome"16751676 assert not app.got_first_request1677 assert client.get("/").data == b"Awesome"1678 with pytest.raises(AssertionError) as e:16791680 @app.route("/foo")1681 def broken():1682 return "Meh"16831684 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_request172717281729def test_routing_redirect_debugging(app, client):1730 app.debug = True17311732 @app.route("/foo/", methods=["GET", "POST"])1733 def foo():1734 return "success"17351736 with client:1737 with pytest.raises(AssertionError) as e:1738 client.post("/foo", data={})1739 assert "http://localhost/foo/" in str(e.value)1740 assert "Make sure to directly send your POST-request to this URL" in str(1741 e.value1742 )17431744 rv = client.get("/foo", data={}, follow_redirects=True)1745 assert rv.data == b"success"17461747 app.debug = False1748 with client:1749 rv = client.post("/foo", data={}, follow_redirects=True)1750 assert rv.data == b"success"175117521753def 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 pull request #4443 from pallets/update-requirementsDavid Lordbefore adoptiond6496c8

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 #3734 from pallets/dependabot/pip/sphinx-3.2.1dependabot-preview[bot]before adoptione071734

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.