Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

2,029 lines · 54.6 KiB · Python

Last changed by

Merge pull request #3907 from pgjones/sugarDavid Lordbefore adoption5fea7ca

History of this file

Take it

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

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

line 1why, one step back
1import gc

Merge branch '1.0.x'David Lordbefore adoption465da9f

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

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

line 6why, one step back
6import weakref

Merge branch '1.0.x'David Lordbefore adoption465da9f

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 branch '1.0.x'David Lordbefore adoption465da9f

lines 9–21why, 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 BuildError1819import flask2021

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

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

update requirements (#3823)David Lordbefore adoption373f0dd

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

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

lines 25–27why, one step back
25)
2627

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 28–50why, one step back
28def test_options_work(app, client):
29 @app.route("/", methods=["GET", "POST"])30 def index():31 return "Hello World"3233 rv = client.open("/", method="OPTIONS")34 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]35 assert rv.data == b""363738def test_options_on_multiple_rules(app, client):39 @app.route("/", methods=["GET", "POST"])40 def index():41 return "Hello World"4243 @app.route("/", methods=["PUT"])44 def index_put():45 return "Aha!"4647 rv = client.open("/", method="OPTIONS")48 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST", "PUT"]4950

Merge pull request #3907 from pgjones/sugarDavid Lordbefore adoption5fea7ca

lines 51–67why, one step back
51@pytest.mark.parametrize("method", ["get", "post", "put", "delete", "patch"])
52def test_method_route(app, client, method):53 method_route = getattr(app, method)54 client_method = getattr(client, method)5556 @method_route("/")57 def hello():58 return "Hello"5960 assert client_method("/").data == b"Hello"616263def test_method_route_no_methods(app):64 with pytest.raises(TypeError):65 app.get("/", methods=["GET", "POST"])6667

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 68–109why, one step back
68def test_provide_automatic_options_attr():
69 app = flask.Flask(__name__)7071 def index():72 return "Hello World!"7374 index.provide_automatic_options = False75 app.route("/")(index)76 rv = app.test_client().open("/", method="OPTIONS")77 assert rv.status_code == 4057879 app = flask.Flask(__name__)8081 def index2():82 return "Hello World!"8384 index2.provide_automatic_options = True85 app.route("/", methods=["OPTIONS"])(index2)86 rv = app.test_client().open("/", method="OPTIONS")87 assert sorted(rv.allow) == ["OPTIONS"]888990def test_provide_automatic_options_kwarg(app, client):91 def index():92 return flask.request.method9394 def more():95 return flask.request.method9697 app.add_url_rule("/", view_func=index, provide_automatic_options=False)98 app.add_url_rule(99 "/more",100 view_func=more,101 methods=["GET", "POST"],102 provide_automatic_options=False,103 )104 assert client.get("/").data == b"GET"105106 rv = client.post("/")107 assert rv.status_code == 405108 assert sorted(rv.allow) == ["GET", "HEAD"]109

Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374

line 110why, one step back
110 rv = client.open("/", method="OPTIONS")

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 111–122why, one step back
111 assert rv.status_code == 405
112113 rv = client.head("/")114 assert rv.status_code == 200115 assert not rv.data # head truncates116 assert client.post("/more").data == b"POST"117 assert client.get("/more").data == b"GET"118119 rv = client.delete("/more")120 assert rv.status_code == 405121 assert sorted(rv.allow) == ["GET", "HEAD", "POST"]122

Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374

line 123why, one step back
123 rv = client.open("/more", method="OPTIONS")

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 124–296why, one step back
124 assert rv.status_code == 405
125126127def test_request_dispatching(app, client):128 @app.route("/")129 def index():130 return flask.request.method131132 @app.route("/more", methods=["GET", "POST"])133 def more():134 return flask.request.method135136 assert client.get("/").data == b"GET"137 rv = client.post("/")138 assert rv.status_code == 405139 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]140 rv = client.head("/")141 assert rv.status_code == 200142 assert not rv.data # head truncates143 assert client.post("/more").data == b"POST"144 assert client.get("/more").data == b"GET"145 rv = client.delete("/more")146 assert rv.status_code == 405147 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]148149150def test_disallow_string_for_allowed_methods(app):151 with pytest.raises(TypeError):152153 @app.route("/", methods="GET POST")154 def index():155 return "Hey"156157158def test_url_mapping(app, client):159 random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"160161 def index():162 return flask.request.method163164 def more():165 return flask.request.method166167 def options():168 return random_uuid4169170 app.add_url_rule("/", "index", index)171 app.add_url_rule("/more", "more", more, methods=["GET", "POST"])172173 # Issue 1288: Test that automatic options are not added174 # when non-uppercase 'options' in methods175 app.add_url_rule("/options", "options", options, methods=["options"])176177 assert client.get("/").data == b"GET"178 rv = client.post("/")179 assert rv.status_code == 405180 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]181 rv = client.head("/")182 assert rv.status_code == 200183 assert not rv.data # head truncates184 assert client.post("/more").data == b"POST"185 assert client.get("/more").data == b"GET"186 rv = client.delete("/more")187 assert rv.status_code == 405188 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]189 rv = client.open("/options", method="OPTIONS")190 assert rv.status_code == 200191 assert random_uuid4 in rv.data.decode("utf-8")192193194def test_werkzeug_routing(app, client):195 from werkzeug.routing import Submount, Rule196197 app.url_map.add(198 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])199 )200201 def bar():202 return "bar"203204 def index():205 return "index"206207 app.view_functions["bar"] = bar208 app.view_functions["index"] = index209210 assert client.get("/foo/").data == b"index"211 assert client.get("/foo/bar").data == b"bar"212213214def test_endpoint_decorator(app, client):215 from werkzeug.routing import Submount, Rule216217 app.url_map.add(218 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])219 )220221 @app.endpoint("bar")222 def bar():223 return "bar"224225 @app.endpoint("index")226 def index():227 return "index"228229 assert client.get("/foo/").data == b"index"230 assert client.get("/foo/bar").data == b"bar"231232233def test_session(app, client):234 @app.route("/set", methods=["POST"])235 def set():236 assert not flask.session.accessed237 assert not flask.session.modified238 flask.session["value"] = flask.request.form["value"]239 assert flask.session.accessed240 assert flask.session.modified241 return "value set"242243 @app.route("/get")244 def get():245 assert not flask.session.accessed246 assert not flask.session.modified247 v = flask.session.get("value", "None")248 assert flask.session.accessed249 assert not flask.session.modified250 return v251252 assert client.post("/set", data={"value": "42"}).data == b"value set"253 assert client.get("/get").data == b"42"254255256def test_session_using_server_name(app, client):257 app.config.update(SERVER_NAME="example.com")258259 @app.route("/")260 def index():261 flask.session["testing"] = 42262 return "Hello World"263264 rv = client.get("/", "http://example.com/")265 assert "domain=.example.com" in rv.headers["set-cookie"].lower()266 assert "httponly" in rv.headers["set-cookie"].lower()267268269def test_session_using_server_name_and_port(app, client):270 app.config.update(SERVER_NAME="example.com:8080")271272 @app.route("/")273 def index():274 flask.session["testing"] = 42275 return "Hello World"276277 rv = client.get("/", "http://example.com:8080/")278 assert "domain=.example.com" in rv.headers["set-cookie"].lower()279 assert "httponly" in rv.headers["set-cookie"].lower()280281282def test_session_using_server_name_port_and_path(app, client):283 app.config.update(SERVER_NAME="example.com:8080", APPLICATION_ROOT="/foo")284285 @app.route("/")286 def index():287 flask.session["testing"] = 42288 return "Hello World"289290 rv = client.get("/", "http://example.com:8080/foo")291 assert "domain=example.com" in rv.headers["set-cookie"].lower()292 assert "path=/foo" in rv.headers["set-cookie"].lower()293 assert "httponly" in rv.headers["set-cookie"].lower()294295296def test_session_using_application_root(app, client):

Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374

line 297why, one step back
297 class PrefixPathMiddleware:

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 298–341why, one step back
298 def __init__(self, app, prefix):
299 self.app = app300 self.prefix = prefix301302 def __call__(self, environ, start_response):303 environ["SCRIPT_NAME"] = self.prefix304 return self.app(environ, start_response)305306 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, "/bar")307 app.config.update(APPLICATION_ROOT="/bar")308309 @app.route("/")310 def index():311 flask.session["testing"] = 42312 return "Hello World"313314 rv = client.get("/", "http://example.com:8080/")315 assert "path=/bar" in rv.headers["set-cookie"].lower()316317318def test_session_using_session_settings(app, client):319 app.config.update(320 SERVER_NAME="www.example.com:8080",321 APPLICATION_ROOT="/test",322 SESSION_COOKIE_DOMAIN=".example.com",323 SESSION_COOKIE_HTTPONLY=False,324 SESSION_COOKIE_SECURE=True,325 SESSION_COOKIE_SAMESITE="Lax",326 SESSION_COOKIE_PATH="/",327 )328329 @app.route("/")330 def index():331 flask.session["testing"] = 42332 return "Hello World"333334 rv = client.get("/", "http://www.example.com:8080/test/")335 cookie = rv.headers["set-cookie"].lower()336 assert "domain=.example.com" in cookie337 assert "path=/" in cookie338 assert "secure" in cookie339 assert "httponly" not in cookie340 assert "samesite" in cookie341

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

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

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 355–393why, one step back
355
356def test_session_using_samesite_attribute(app, client):357 @app.route("/")358 def index():359 flask.session["testing"] = 42360 return "Hello World"361362 app.config.update(SESSION_COOKIE_SAMESITE="invalid")363364 with pytest.raises(ValueError):365 client.get("/")366367 app.config.update(SESSION_COOKIE_SAMESITE=None)368 rv = client.get("/")369 cookie = rv.headers["set-cookie"].lower()370 assert "samesite" not in cookie371372 app.config.update(SESSION_COOKIE_SAMESITE="Strict")373 rv = client.get("/")374 cookie = rv.headers["set-cookie"].lower()375 assert "samesite=strict" in cookie376377 app.config.update(SESSION_COOKIE_SAMESITE="Lax")378 rv = client.get("/")379 cookie = rv.headers["set-cookie"].lower()380 assert "samesite=lax" in cookie381382383def test_session_localhost_warning(recwarn, app, client):384 app.config.update(SERVER_NAME="localhost:5000")385386 @app.route("/")387 def index():388 flask.session["testing"] = 42389 return "testing"390391 rv = client.get("/", "http://localhost:5000/")392 assert "domain" not in rv.headers["set-cookie"].lower()393 w = recwarn.pop(UserWarning)

Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374

line 394why, one step back
394 assert "'localhost' is not a valid cookie domain" in str(w.message)

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 395–434why, one step back
395
396397def test_session_ip_warning(recwarn, app, client):398 app.config.update(SERVER_NAME="127.0.0.1:5000")399400 @app.route("/")401 def index():402 flask.session["testing"] = 42403 return "testing"404405 rv = client.get("/", "http://127.0.0.1:5000/")406 assert "domain=127.0.0.1" in rv.headers["set-cookie"].lower()407 w = recwarn.pop(UserWarning)408 assert "cookie domain is an IP" in str(w.message)409410411def test_missing_session(app):412 app.secret_key = None413414 def expect_exception(f, *args, **kwargs):415 e = pytest.raises(RuntimeError, f, *args, **kwargs)416 assert e.value.args and "session is unavailable" in e.value.args[0]417418 with app.test_request_context():419 assert flask.session.get("missing_key") is None420 expect_exception(flask.session.__setitem__, "foo", 42)421 expect_exception(flask.session.pop, "foo")422423424def test_session_expiration(app, client):425 permanent = True426427 @app.route("/")428 def index():429 flask.session["test"] = 42430 flask.session.permanent = permanent431 return ""432433 @app.route("/test")434 def test():

Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374

line 435why, one step back
435 return str(flask.session.permanent)

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 436–614why, one step back
436
437 rv = client.get("/")438 assert "set-cookie" in rv.headers439 match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])440 expires = parse_date(match.group())441 expected = datetime.utcnow() + app.permanent_session_lifetime442 assert expires.year == expected.year443 assert expires.month == expected.month444 assert expires.day == expected.day445446 rv = client.get("/test")447 assert rv.data == b"True"448449 permanent = False450 rv = client.get("/")451 assert "set-cookie" in rv.headers452 match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])453 assert match is None454455456def test_session_stored_last(app, client):457 @app.after_request458 def modify_session(response):459 flask.session["foo"] = 42460 return response461462 @app.route("/")463 def dump_session_contents():464 return repr(flask.session.get("foo"))465466 assert client.get("/").data == b"None"467 assert client.get("/").data == b"42"468469470def test_session_special_types(app, client):471 now = datetime.utcnow().replace(microsecond=0)472 the_uuid = uuid.uuid4()473474 @app.route("/")475 def dump_session_contents():476 flask.session["t"] = (1, 2, 3)477 flask.session["b"] = b"\xff"478 flask.session["m"] = flask.Markup("<html>")479 flask.session["u"] = the_uuid480 flask.session["d"] = now481 flask.session["t_tag"] = {" t": "not-a-tuple"}482 flask.session["di_t_tag"] = {" t__": "not-a-tuple"}483 flask.session["di_tag"] = {" di": "not-a-dict"}484 return "", 204485486 with client:487 client.get("/")488 s = flask.session489 assert s["t"] == (1, 2, 3)490 assert type(s["b"]) == bytes491 assert s["b"] == b"\xff"492 assert type(s["m"]) == flask.Markup493 assert s["m"] == flask.Markup("<html>")494 assert s["u"] == the_uuid495 assert s["d"] == now496 assert s["t_tag"] == {" t": "not-a-tuple"}497 assert s["di_t_tag"] == {" t__": "not-a-tuple"}498 assert s["di_tag"] == {" di": "not-a-dict"}499500501def test_session_cookie_setting(app):502 is_permanent = True503504 @app.route("/bump")505 def bump():506 rv = flask.session["foo"] = flask.session.get("foo", 0) + 1507 flask.session.permanent = is_permanent508 return str(rv)509510 @app.route("/read")511 def read():512 return str(flask.session.get("foo", 0))513514 def run_test(expect_header):515 with app.test_client() as c:516 assert c.get("/bump").data == b"1"517 assert c.get("/bump").data == b"2"518 assert c.get("/bump").data == b"3"519520 rv = c.get("/read")521 set_cookie = rv.headers.get("set-cookie")522 assert (set_cookie is not None) == expect_header523 assert rv.data == b"3"524525 is_permanent = True526 app.config["SESSION_REFRESH_EACH_REQUEST"] = True527 run_test(expect_header=True)528529 is_permanent = True530 app.config["SESSION_REFRESH_EACH_REQUEST"] = False531 run_test(expect_header=False)532533 is_permanent = False534 app.config["SESSION_REFRESH_EACH_REQUEST"] = True535 run_test(expect_header=False)536537 is_permanent = False538 app.config["SESSION_REFRESH_EACH_REQUEST"] = False539 run_test(expect_header=False)540541542def test_session_vary_cookie(app, client):543 @app.route("/set")544 def set_session():545 flask.session["test"] = "test"546 return ""547548 @app.route("/get")549 def get():550 return flask.session.get("test")551552 @app.route("/getitem")553 def getitem():554 return flask.session["test"]555556 @app.route("/setdefault")557 def setdefault():558 return flask.session.setdefault("test", "default")559560 @app.route("/vary-cookie-header-set")561 def vary_cookie_header_set():562 response = flask.Response()563 response.vary.add("Cookie")564 flask.session["test"] = "test"565 return response566567 @app.route("/vary-header-set")568 def vary_header_set():569 response = flask.Response()570 response.vary.update(("Accept-Encoding", "Accept-Language"))571 flask.session["test"] = "test"572 return response573574 @app.route("/no-vary-header")575 def no_vary_header():576 return ""577578 def expect(path, header_value="Cookie"):579 rv = client.get(path)580581 if header_value:582 # The 'Vary' key should exist in the headers only once.583 assert len(rv.headers.get_all("Vary")) == 1584 assert rv.headers["Vary"] == header_value585 else:586 assert "Vary" not in rv.headers587588 expect("/set")589 expect("/get")590 expect("/getitem")591 expect("/setdefault")592 expect("/vary-cookie-header-set")593 expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")594 expect("/no-vary-header", None)595596597def test_flashes(app, req_ctx):598 assert not flask.session.modified599 flask.flash("Zap")600 flask.session.modified = False601 flask.flash("Zip")602 assert flask.session.modified603 assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]604605606def test_extended_flashing(app):607 # Be sure app.testing=True below, else tests can fail silently.608 #609 # Specifically, if app.testing is not set to True, the AssertionErrors610 # in the view functions will cause a 500 response to the test client611 # instead of propagating exceptions.612613 @app.route("/")614 def index():

Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374

lines 615–617why, one step back
615 flask.flash("Hello World")
616 flask.flash("Hello World", "error")617 flask.flash(flask.Markup("<em>Testing</em>"), "warning")

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 618–623why, one step back
618 return ""
619620 @app.route("/test/")621 def test():622 messages = flask.get_flashed_messages()623 assert list(messages) == [

Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374

lines 624–626why, one step back
624 "Hello World",
625 "Hello World",626 flask.Markup("<em>Testing</em>"),

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 627–634why, one step back
627 ]
628 return ""629630 @app.route("/test_with_categories/")631 def test_with_categories():632 messages = flask.get_flashed_messages(with_categories=True)633 assert len(messages) == 3634 assert list(messages) == [

Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374

lines 635–637why, one step back
635 ("message", "Hello World"),
636 ("error", "Hello World"),637 ("warning", flask.Markup("<em>Testing</em>")),

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 638–645why, one step back
638 ]
639 return ""640641 @app.route("/test_filter/")642 def test_filter():643 messages = flask.get_flashed_messages(644 category_filter=["message"], with_categories=True645 )

Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374

line 646why, one step back
646 assert list(messages) == [("message", "Hello World")]

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 647–654why, one step back
647 return ""
648649 @app.route("/test_filters/")650 def test_filters():651 messages = flask.get_flashed_messages(652 category_filter=["message", "warning"], with_categories=True653 )654 assert list(messages) == [

Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374

lines 655–656why, one step back
655 ("message", "Hello World"),
656 ("warning", flask.Markup("<em>Testing</em>")),

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 657–663why, one step back
657 ]
658 return ""659660 @app.route("/test_filters_without_returning_categories/")661 def test_filters2():662 messages = flask.get_flashed_messages(category_filter=["message", "warning"])663 assert len(messages) == 2

Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374

lines 664–665why, one step back
664 assert messages[0] == "Hello World"
665 assert messages[1] == flask.Markup("<em>Testing</em>")

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 666–1127why, one step back
666 return ""
667668 # Create new test client on each test to clean flashed messages.669670 client = app.test_client()671 client.get("/")672 client.get("/test_with_categories/")673674 client = app.test_client()675 client.get("/")676 client.get("/test_filter/")677678 client = app.test_client()679 client.get("/")680 client.get("/test_filters/")681682 client = app.test_client()683 client.get("/")684 client.get("/test_filters_without_returning_categories/")685686687def test_request_processing(app, client):688 evts = []689690 @app.before_request691 def before_request():692 evts.append("before")693694 @app.after_request695 def after_request(response):696 response.data += b"|after"697 evts.append("after")698 return response699700 @app.route("/")701 def index():702 assert "before" in evts703 assert "after" not in evts704 return "request"705706 assert "after" not in evts707 rv = client.get("/").data708 assert "after" in evts709 assert rv == b"request|after"710711712def test_request_preprocessing_early_return(app, client):713 evts = []714715 @app.before_request716 def before_request1():717 evts.append(1)718719 @app.before_request720 def before_request2():721 evts.append(2)722 return "hello"723724 @app.before_request725 def before_request3():726 evts.append(3)727 return "bye"728729 @app.route("/")730 def index():731 evts.append("index")732 return "damnit"733734 rv = client.get("/").data.strip()735 assert rv == b"hello"736 assert evts == [1, 2]737738739def test_after_request_processing(app, client):740 @app.route("/")741 def index():742 @flask.after_this_request743 def foo(response):744 response.headers["X-Foo"] = "a header"745 return response746747 return "Test"748749 resp = client.get("/")750 assert resp.status_code == 200751 assert resp.headers["X-Foo"] == "a header"752753754def test_teardown_request_handler(app, client):755 called = []756757 @app.teardown_request758 def teardown_request(exc):759 called.append(True)760 return "Ignored"761762 @app.route("/")763 def root():764 return "Response"765766 rv = client.get("/")767 assert rv.status_code == 200768 assert b"Response" in rv.data769 assert len(called) == 1770771772def test_teardown_request_handler_debug_mode(app, client):773 called = []774775 @app.teardown_request776 def teardown_request(exc):777 called.append(True)778 return "Ignored"779780 @app.route("/")781 def root():782 return "Response"783784 rv = client.get("/")785 assert rv.status_code == 200786 assert b"Response" in rv.data787 assert len(called) == 1788789790def test_teardown_request_handler_error(app, client):791 called = []792 app.testing = False793794 @app.teardown_request795 def teardown_request1(exc):796 assert type(exc) == ZeroDivisionError797 called.append(True)798 # This raises a new error and blows away sys.exc_info(), so we can799 # test that all teardown_requests get passed the same original800 # exception.801 try:802 raise TypeError()803 except Exception:804 pass805806 @app.teardown_request807 def teardown_request2(exc):808 assert type(exc) == ZeroDivisionError809 called.append(True)810 # This raises a new error and blows away sys.exc_info(), so we can811 # test that all teardown_requests get passed the same original812 # exception.813 try:814 raise TypeError()815 except Exception:816 pass817818 @app.route("/")819 def fails():820 1 // 0821822 rv = client.get("/")823 assert rv.status_code == 500824 assert b"Internal Server Error" in rv.data825 assert len(called) == 2826827828def test_before_after_request_order(app, client):829 called = []830831 @app.before_request832 def before1():833 called.append(1)834835 @app.before_request836 def before2():837 called.append(2)838839 @app.after_request840 def after1(response):841 called.append(4)842 return response843844 @app.after_request845 def after2(response):846 called.append(3)847 return response848849 @app.teardown_request850 def finish1(exc):851 called.append(6)852853 @app.teardown_request854 def finish2(exc):855 called.append(5)856857 @app.route("/")858 def index():859 return "42"860861 rv = client.get("/")862 assert rv.data == b"42"863 assert called == [1, 2, 3, 4, 5, 6]864865866def test_error_handling(app, client):867 app.testing = False868869 @app.errorhandler(404)870 def not_found(e):871 return "not found", 404872873 @app.errorhandler(500)874 def internal_server_error(e):875 return "internal server error", 500876877 @app.errorhandler(Forbidden)878 def forbidden(e):879 return "forbidden", 403880881 @app.route("/")882 def index():883 flask.abort(404)884885 @app.route("/error")886 def error():887 1 // 0888889 @app.route("/forbidden")890 def error2():891 flask.abort(403)892893 rv = client.get("/")894 assert rv.status_code == 404895 assert rv.data == b"not found"896 rv = client.get("/error")897 assert rv.status_code == 500898 assert b"internal server error" == rv.data899 rv = client.get("/forbidden")900 assert rv.status_code == 403901 assert b"forbidden" == rv.data902903904def test_error_handler_unknown_code(app):905 with pytest.raises(KeyError) as exc_info:906 app.register_error_handler(999, lambda e: ("999", 999))907908 assert "Use a subclass" in exc_info.value.args[0]909910911def test_error_handling_processing(app, client):912 app.testing = False913914 @app.errorhandler(500)915 def internal_server_error(e):916 return "internal server error", 500917918 @app.route("/")919 def broken_func():920 1 // 0921922 @app.after_request923 def after_request(resp):924 resp.mimetype = "text/x-special"925 return resp926927 resp = client.get("/")928 assert resp.mimetype == "text/x-special"929 assert resp.data == b"internal server error"930931932def test_baseexception_error_handling(app, client):933 app.testing = False934935 @app.route("/")936 def broken_func():937 raise KeyboardInterrupt()938939 with pytest.raises(KeyboardInterrupt):940 client.get("/")941942 ctx = flask._request_ctx_stack.top943 assert ctx.preserved944 assert type(ctx._preserved_exc) is KeyboardInterrupt945946947def test_before_request_and_routing_errors(app, client):948 @app.before_request949 def attach_something():950 flask.g.something = "value"951952 @app.errorhandler(404)953 def return_something(error):954 return flask.g.something, 404955956 rv = client.get("/")957 assert rv.status_code == 404958 assert rv.data == b"value"959960961def test_user_error_handling(app, client):962 class MyException(Exception):963 pass964965 @app.errorhandler(MyException)966 def handle_my_exception(e):967 assert isinstance(e, MyException)968 return "42"969970 @app.route("/")971 def index():972 raise MyException()973974 assert client.get("/").data == b"42"975976977def test_http_error_subclass_handling(app, client):978 class ForbiddenSubclass(Forbidden):979 pass980981 @app.errorhandler(ForbiddenSubclass)982 def handle_forbidden_subclass(e):983 assert isinstance(e, ForbiddenSubclass)984 return "banana"985986 @app.errorhandler(403)987 def handle_403(e):988 assert not isinstance(e, ForbiddenSubclass)989 assert isinstance(e, Forbidden)990 return "apple"991992 @app.route("/1")993 def index1():994 raise ForbiddenSubclass()995996 @app.route("/2")997 def index2():998 flask.abort(403)9991000 @app.route("/3")1001 def index3():1002 raise Forbidden()10031004 assert client.get("/1").data == b"banana"1005 assert client.get("/2").data == b"apple"1006 assert client.get("/3").data == b"apple"100710081009def test_errorhandler_precedence(app, client):1010 class E1(Exception):1011 pass10121013 class E2(Exception):1014 pass10151016 class E3(E1, E2):1017 pass10181019 @app.errorhandler(E2)1020 def handle_e2(e):1021 return "E2"10221023 @app.errorhandler(Exception)1024 def handle_exception(e):1025 return "Exception"10261027 @app.route("/E1")1028 def raise_e1():1029 raise E110301031 @app.route("/E3")1032 def raise_e3():1033 raise E310341035 rv = client.get("/E1")1036 assert rv.data == b"Exception"10371038 rv = client.get("/E3")1039 assert rv.data == b"E2"104010411042def test_trapping_of_bad_request_key_errors(app, client):1043 @app.route("/key")1044 def fail():1045 flask.request.form["missing_key"]10461047 @app.route("/abort")1048 def allow_abort():1049 flask.abort(400)10501051 rv = client.get("/key")1052 assert rv.status_code == 4001053 assert b"missing_key" not in rv.data1054 rv = client.get("/abort")1055 assert rv.status_code == 40010561057 app.debug = True1058 with pytest.raises(KeyError) as e:1059 client.get("/key")1060 assert e.errisinstance(BadRequest)1061 assert "missing_key" in e.value.get_description()1062 rv = client.get("/abort")1063 assert rv.status_code == 40010641065 app.debug = False1066 app.config["TRAP_BAD_REQUEST_ERRORS"] = True1067 with pytest.raises(KeyError):1068 client.get("/key")1069 with pytest.raises(BadRequest):1070 client.get("/abort")107110721073def test_trapping_of_all_http_exceptions(app, client):1074 app.config["TRAP_HTTP_EXCEPTIONS"] = True10751076 @app.route("/fail")1077 def fail():1078 flask.abort(404)10791080 with pytest.raises(NotFound):1081 client.get("/fail")108210831084def test_error_handler_after_processor_error(app, client):1085 app.testing = False10861087 @app.before_request1088 def before_request():1089 if _trigger == "before":1090 1 // 010911092 @app.after_request1093 def after_request(response):1094 if _trigger == "after":1095 1 // 01096 return response10971098 @app.route("/")1099 def index():1100 return "Foo"11011102 @app.errorhandler(500)1103 def internal_server_error(e):1104 return "Hello Server Error", 50011051106 for _trigger in "before", "after":1107 rv = client.get("/")1108 assert rv.status_code == 5001109 assert rv.data == b"Hello Server Error"111011111112def test_enctype_debug_helper(app, client):1113 from flask.debughelpers import DebugFilesKeyError11141115 app.debug = True11161117 @app.route("/fail", methods=["POST"])1118 def index():1119 return flask.request.files["foo"].filename11201121 # with statement is important because we leave an exception on the1122 # stack otherwise and we want to ensure that this is not the case1123 # to not negatively affect other tests.1124 with client:1125 with pytest.raises(DebugFilesKeyError) as e:1126 client.post("/fail", data={"foo": "index.txt"})1127 assert "no file contents were transmitted" in str(e.value)

Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374

line 1128why, one step back
1128 assert "This was submitted: 'index.txt'" in str(e.value)

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 1129–1133why, one step back
1129
11301131def test_response_types(app, client):1132 @app.route("/text")1133 def from_text():

Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374

line 1134why, one step back
1134 return "Hällo Wörld"

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 1135–1137why, one step back
1135
1136 @app.route("/bytes")1137 def from_bytes():

Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374

line 1138why, one step back
1138 return "Hällo Wörld".encode()

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 1139–1158why, one step back
1139
1140 @app.route("/full_tuple")1141 def from_full_tuple():1142 return (1143 "Meh",1144 400,1145 {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1146 )11471148 @app.route("/text_headers")1149 def from_text_headers():1150 return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}11511152 @app.route("/text_status")1153 def from_text_status():1154 return "Hi, status!", 40011551156 @app.route("/response_headers")1157 def from_response_headers():1158 return (

Merge pull request #3684 from MLH-Fellowship/3628-duplicate-headersDavid Lordbefore adoption2fa8eb3

lines 1159–1162why, one step back
1159 flask.Response(
1160 "Hello world", 404, {"Content-Type": "text/html", "X-Foo": "Baz"}1161 ),1162 {"Content-Type": "text/plain", "X-Foo": "Bar", "X-Bar": "Foo"},

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 1163–1176why, one step back
1163 )
11641165 @app.route("/response_status")1166 def from_response_status():1167 return app.response_class("Hello world", 400), 50011681169 @app.route("/wsgi")1170 def from_wsgi():1171 return NotFound()11721173 @app.route("/dict")1174 def from_dict():1175 return {"foo": "bar"}, 2011176

Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374

lines 1177–1178why, one step back
1177 assert client.get("/text").data == "Hällo Wörld".encode()
1178 assert client.get("/bytes").data == "Hällo Wörld".encode()

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 1179–1198why, one step back
1179
1180 rv = client.get("/full_tuple")1181 assert rv.data == b"Meh"1182 assert rv.headers["X-Foo"] == "Testing"1183 assert rv.status_code == 4001184 assert rv.mimetype == "text/plain"11851186 rv = client.get("/text_headers")1187 assert rv.data == b"Hello"1188 assert rv.headers["X-Foo"] == "Test"1189 assert rv.status_code == 2001190 assert rv.mimetype == "text/plain"11911192 rv = client.get("/text_status")1193 assert rv.data == b"Hi, status!"1194 assert rv.status_code == 4001195 assert rv.mimetype == "text/html"11961197 rv = client.get("/response_headers")1198 assert rv.data == b"Hello world"

Merge pull request #3684 from MLH-Fellowship/3628-duplicate-headersDavid Lordbefore adoption2fa8eb3

lines 1199–1200why, one step back
1199 assert rv.content_type == "text/plain"
1200 assert rv.headers.getlist("X-Foo") == ["Bar"]

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 1201–1245why, one step back
1201 assert rv.headers["X-Bar"] == "Foo"
1202 assert rv.status_code == 40412031204 rv = client.get("/response_status")1205 assert rv.data == b"Hello world"1206 assert rv.status_code == 50012071208 rv = client.get("/wsgi")1209 assert b"Not Found" in rv.data1210 assert rv.status_code == 40412111212 rv = client.get("/dict")1213 assert rv.json == {"foo": "bar"}1214 assert rv.status_code == 201121512161217def test_response_type_errors():1218 app = flask.Flask(__name__)1219 app.testing = True12201221 @app.route("/none")1222 def from_none():1223 pass12241225 @app.route("/small_tuple")1226 def from_small_tuple():1227 return ("Hello",)12281229 @app.route("/large_tuple")1230 def from_large_tuple():1231 return "Hello", 234, {"X-Foo": "Bar"}, "???"12321233 @app.route("/bad_type")1234 def from_bad_type():1235 return True12361237 @app.route("/bad_wsgi")1238 def from_bad_wsgi():1239 return lambda: None12401241 c = app.test_client()12421243 with pytest.raises(TypeError) as e:1244 c.get("/none")1245 assert "returned None" in str(e.value)

Merge pull request #3498 from raymond-devries/3445-traceback-for-noneDavid Lordbefore adoptiona3e4395

line 1246why, one step back
1246 assert "from_none" in str(e.value)

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 1247–1450why, one step back
1247
1248 with pytest.raises(TypeError) as e:1249 c.get("/small_tuple")1250 assert "tuple must have the form" in str(e.value)12511252 pytest.raises(TypeError, c.get, "/large_tuple")12531254 with pytest.raises(TypeError) as e:1255 c.get("/bad_type")1256 assert "it was a bool" in str(e.value)12571258 pytest.raises(TypeError, c.get, "/bad_wsgi")125912601261def test_make_response(app, req_ctx):1262 rv = flask.make_response()1263 assert rv.status_code == 2001264 assert rv.data == b""1265 assert rv.mimetype == "text/html"12661267 rv = flask.make_response("Awesome")1268 assert rv.status_code == 2001269 assert rv.data == b"Awesome"1270 assert rv.mimetype == "text/html"12711272 rv = flask.make_response("W00t", 404)1273 assert rv.status_code == 4041274 assert rv.data == b"W00t"1275 assert rv.mimetype == "text/html"127612771278def test_make_response_with_response_instance(app, req_ctx):1279 rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1280 assert rv.status_code == 4001281 assert rv.data == b'{"msg":"W00t"}\n'1282 assert rv.mimetype == "application/json"12831284 rv = flask.make_response(flask.Response(""), 400)1285 assert rv.status_code == 4001286 assert rv.data == b""1287 assert rv.mimetype == "text/html"12881289 rv = flask.make_response(1290 flask.Response("", headers={"Content-Type": "text/html"}),1291 400,1292 [("X-Foo", "bar")],1293 )1294 assert rv.status_code == 4001295 assert rv.headers["Content-Type"] == "text/html"1296 assert rv.headers["X-Foo"] == "bar"129712981299def test_jsonify_no_prettyprint(app, req_ctx):1300 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1301 compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1302 uncompressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}13031304 rv = flask.make_response(flask.jsonify(uncompressed_msg), 200)1305 assert rv.data == compressed_msg130613071308def test_jsonify_prettyprint(app, req_ctx):1309 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1310 compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1311 pretty_response = (1312 b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'1313 )13141315 rv = flask.make_response(flask.jsonify(compressed_msg), 200)1316 assert rv.data == pretty_response131713181319def test_jsonify_mimetype(app, req_ctx):1320 app.config.update({"JSONIFY_MIMETYPE": "application/vnd.api+json"})1321 msg = {"msg": {"submsg": "W00t"}}1322 rv = flask.make_response(flask.jsonify(msg), 200)1323 assert rv.mimetype == "application/vnd.api+json"132413251326@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")1327def 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()14491450

Merge pull request #3579 from jab/pathlib-for-static_folderJoshua Bronsonbefore adoptioncf5b1d0

lines 1451–1460why, one step back
1451@pytest.mark.skipif(sys.version_info < (3, 6), reason="requires Python >= 3.6")
1452def 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()14591460

Merge remote-tracking branch 'origin/1.1.x'David Lordbefore adoption64ba434

lines 1461–1471why, one step back
1461def 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"14701471

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 1472–1539why, one step back
1472def 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"15301531 # suppress Werkzeug 1.0 warning about name mismatch1532 with pytest.warns(None):1533 rv = client.get("/", "http://foo.localhost")1534 assert rv.status_code == 40415351536 rv = client.get("/", "http://foo.dev.local")1537 assert rv.data == b"subdomain"15381539

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

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

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 1542–1657why, one step back
1542def test_exception_propagation(app, client):
1543 def apprunner(config_key):1544 @app.route("/")1545 def index():1546 1 // 015471548 if config_key is not None:1549 app.config[config_key] = True1550 with pytest.raises(Exception):1551 client.get("/")1552 else:1553 assert client.get("/").status_code == 50015541555 # we have to run this test in an isolated thread because if the1556 # debug flag is set to true and an exception happens the context is1557 # not torn down. This causes other tests that run after this fail1558 # when they expect no exception on the stack.1559 for config_key in "TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None:1560 t = Thread(target=apprunner, args=(config_key,))1561 t.start()1562 t.join()156315641565@pytest.mark.parametrize("debug", [True, False])1566@pytest.mark.parametrize("use_debugger", [True, False])1567@pytest.mark.parametrize("use_reloader", [True, False])1568@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1569def test_werkzeug_passthrough_errors(1570 monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1571):1572 rv = {}15731574 # Mocks werkzeug.serving.run_simple method1575 def run_simple_mock(*args, **kwargs):1576 rv["passthrough_errors"] = kwargs.get("passthrough_errors")15771578 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1579 app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1580 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)158115821583def test_max_content_length(app, client):1584 app.config["MAX_CONTENT_LENGTH"] = 6415851586 @app.before_request1587 def always_first():1588 flask.request.form["myfile"]1589 AssertionError()15901591 @app.route("/accept", methods=["POST"])1592 def accept_file():1593 flask.request.form["myfile"]1594 AssertionError()15951596 @app.errorhandler(413)1597 def catcher(error):1598 return "42"15991600 rv = client.post("/accept", data={"myfile": "foo" * 100})1601 assert rv.data == b"42"160216031604def test_url_processors(app, client):1605 @app.url_defaults1606 def add_language_code(endpoint, values):1607 if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1608 endpoint, "lang_code"1609 ):1610 values.setdefault("lang_code", flask.g.lang_code)16111612 @app.url_value_preprocessor1613 def pull_lang_code(endpoint, values):1614 flask.g.lang_code = values.pop("lang_code", None)16151616 @app.route("/<lang_code>/")1617 def index():1618 return flask.url_for("about")16191620 @app.route("/<lang_code>/about")1621 def about():1622 return flask.url_for("something_else")16231624 @app.route("/foo")1625 def something_else():1626 return flask.url_for("about", lang_code="en")16271628 assert client.get("/de/").data == b"/de/about"1629 assert client.get("/de/about").data == b"/foo"1630 assert client.get("/foo").data == b"/en/about"163116321633def test_inject_blueprint_url_defaults(app):1634 bp = flask.Blueprint("foo.bar.baz", __name__, template_folder="template")16351636 @bp.url_defaults1637 def bp_defaults(endpoint, values):1638 values["page"] = "login"16391640 @bp.route("/<page>")1641 def view(page):1642 pass16431644 app.register_blueprint(bp)16451646 values = dict()1647 app.inject_url_defaults("foo.bar.baz.view", values)1648 expected = dict(page="login")1649 assert values == expected16501651 with app.test_request_context("/somepage"):1652 url = flask.url_for("foo.bar.baz.view")1653 expected = "/login"1654 assert url == expected165516561657def test_nonascii_pathinfo(app, client):

Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374

line 1658why, one step back
1658 @app.route("/киртест")

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 1659–1661why, one step back
1659 def index():
1660 return "Hello World!"1661

Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374

line 1662why, one step back
1662 rv = client.get("/киртест")

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 1663–1736why, one step back
1663 assert rv.data == b"Hello World!"
166416651666def test_debug_mode_complains_after_first_request(app, client):1667 app.debug = True16681669 @app.route("/")1670 def index():1671 return "Awesome"16721673 assert not app.got_first_request1674 assert client.get("/").data == b"Awesome"1675 with pytest.raises(AssertionError) as e:16761677 @app.route("/foo")1678 def broken():1679 return "Meh"16801681 assert "A setup function was called" in str(e.value)16821683 app.debug = False16841685 @app.route("/foo")1686 def working():1687 return "Meh"16881689 assert client.get("/foo").data == b"Meh"1690 assert app.got_first_request169116921693def test_before_first_request_functions(app, client):1694 got = []16951696 @app.before_first_request1697 def foo():1698 got.append(42)16991700 client.get("/")1701 assert got == [42]1702 client.get("/")1703 assert got == [42]1704 assert app.got_first_request170517061707def test_before_first_request_functions_concurrent(app, client):1708 got = []17091710 @app.before_first_request1711 def foo():1712 time.sleep(0.2)1713 got.append(42)17141715 def get_and_assert():1716 client.get("/")1717 assert got == [42]17181719 t = Thread(target=get_and_assert)1720 t.start()1721 get_and_assert()1722 t.join()1723 assert app.got_first_request172417251726def test_routing_redirect_debugging(app, client):1727 app.debug = True17281729 @app.route("/foo/", methods=["GET", "POST"])1730 def foo():1731 return "success"17321733 with client:1734 with pytest.raises(AssertionError) as e:1735 client.post("/foo", data={})1736 assert "http://localhost/foo/" in str(e.value)

Merge pull request #3453 from noviluni/remove_redundant_parenthesesDavid Lordbefore adoption986871b

line 1737why, one step back
1737 assert "Make sure to directly send your POST-request to this URL" in str(

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 1738–1868why, one step back
1738 e.value
1739 )17401741 rv = client.get("/foo", data={}, follow_redirects=True)1742 assert rv.data == b"success"17431744 app.debug = False1745 with client:1746 rv = client.post("/foo", data={}, follow_redirects=True)1747 assert rv.data == b"success"174817491750def test_route_decorator_custom_endpoint(app, client):1751 app.debug = True17521753 @app.route("/foo/")1754 def foo():1755 return flask.request.endpoint17561757 @app.route("/bar/", endpoint="bar")1758 def for_bar():1759 return flask.request.endpoint17601761 @app.route("/bar/123", endpoint="123")1762 def for_bar_foo():1763 return flask.request.endpoint17641765 with app.test_request_context():1766 assert flask.url_for("foo") == "/foo/"1767 assert flask.url_for("bar") == "/bar/"1768 assert flask.url_for("123") == "/bar/123"17691770 assert client.get("/foo/").data == b"foo"1771 assert client.get("/bar/").data == b"bar"1772 assert client.get("/bar/123").data == b"123"177317741775def test_preserve_only_once(app, client):1776 app.debug = True17771778 @app.route("/fail")1779 def fail_func():1780 1 // 017811782 for _x in range(3):1783 with pytest.raises(ZeroDivisionError):1784 client.get("/fail")17851786 assert flask._request_ctx_stack.top is not None1787 assert flask._app_ctx_stack.top is not None1788 # implicit appctx disappears too1789 flask._request_ctx_stack.top.pop()1790 assert flask._request_ctx_stack.top is None1791 assert flask._app_ctx_stack.top is None179217931794def test_preserve_remembers_exception(app, client):1795 app.debug = True1796 errors = []17971798 @app.route("/fail")1799 def fail_func():1800 1 // 018011802 @app.route("/success")1803 def success_func():1804 return "Okay"18051806 @app.teardown_request1807 def teardown_handler(exc):1808 errors.append(exc)18091810 # After this failure we did not yet call the teardown handler1811 with pytest.raises(ZeroDivisionError):1812 client.get("/fail")1813 assert errors == []18141815 # But this request triggers it, and it's an error1816 client.get("/success")1817 assert len(errors) == 21818 assert isinstance(errors[0], ZeroDivisionError)18191820 # At this point another request does nothing.1821 client.get("/success")1822 assert len(errors) == 31823 assert errors[1] is None182418251826def test_get_method_on_g(app_ctx):1827 assert flask.g.get("x") is None1828 assert flask.g.get("x", 11) == 111829 flask.g.x = 421830 assert flask.g.get("x") == 421831 assert flask.g.x == 42183218331834def test_g_iteration_protocol(app_ctx):1835 flask.g.foo = 231836 flask.g.bar = 421837 assert "foo" in flask.g1838 assert "foos" not in flask.g1839 assert sorted(flask.g) == ["bar", "foo"]184018411842def test_subdomain_basic_support():1843 app = flask.Flask(__name__, subdomain_matching=True)1844 app.config["SERVER_NAME"] = "localhost.localdomain"1845 client = app.test_client()18461847 @app.route("/")1848 def normal_index():1849 return "normal index"18501851 @app.route("/", subdomain="test")1852 def test_index():1853 return "test index"18541855 rv = client.get("/", "http://localhost.localdomain/")1856 assert rv.data == b"normal index"18571858 rv = client.get("/", "http://test.localhost.localdomain/")1859 assert rv.data == b"test index"186018611862def test_subdomain_matching():1863 app = flask.Flask(__name__, subdomain_matching=True)1864 client = app.test_client()1865 app.config["SERVER_NAME"] = "localhost.localdomain"18661867 @app.route("/", subdomain="<user>")1868 def index(user):

Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374

line 1869why, one step back
1869 return f"index for {user}"

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 1870–1881why, one step back
1870
1871 rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1872 assert rv.data == b"index for mitsuhiko"187318741875def test_subdomain_matching_with_ports():1876 app = flask.Flask(__name__, subdomain_matching=True)1877 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1878 client = app.test_client()18791880 @app.route("/", subdomain="<user>")1881 def index(user):

Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374

line 1882why, one step back
1882 return f"index for {user}"

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 1883–1921why, one step back
1883
1884 rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1885 assert rv.data == b"index for mitsuhiko"188618871888@pytest.mark.parametrize("matching", (False, True))1889def test_subdomain_matching_other_name(matching):1890 app = flask.Flask(__name__, subdomain_matching=matching)1891 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1892 client = app.test_client()18931894 @app.route("/")1895 def index():1896 return "", 20418971898 # suppress Werkzeug 0.15 warning about name mismatch1899 with pytest.warns(None):1900 # ip address can't match name1901 rv = client.get("/", "http://127.0.0.1:3000/")1902 assert rv.status_code == 404 if matching else 20419031904 # allow all subdomains if matching is disabled1905 rv = client.get("/", "http://www.localhost.localdomain:3000/")1906 assert rv.status_code == 404 if matching else 204190719081909def test_multi_route_rules(app, client):1910 @app.route("/")1911 @app.route("/<test>/")1912 def index(test="a"):1913 return test19141915 rv = client.open("/")1916 assert rv.data == b"a"1917 rv = client.open("/b/")1918 assert rv.data == b"b"191919201921def test_multi_route_class_views(app, client):

Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374

line 1922why, one step back
1922 class View:

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 1923–1953why, one step back
1923 def __init__(self, app):
1924 app.add_url_rule("/", "index", self.index)1925 app.add_url_rule("/<test>/", "index", self.index)19261927 def index(self, test="a"):1928 return test19291930 _ = View(app)1931 rv = client.open("/")1932 assert rv.data == b"a"1933 rv = client.open("/b/")1934 assert rv.data == b"b"193519361937def test_run_defaults(monkeypatch, app):1938 rv = {}19391940 # Mocks werkzeug.serving.run_simple method1941 def run_simple_mock(*args, **kwargs):1942 rv["result"] = "running..."19431944 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1945 app.run()1946 assert rv["result"] == "running..."194719481949def test_run_server_port(monkeypatch, app):1950 rv = {}19511952 # Mocks werkzeug.serving.run_simple method1953 def run_simple_mock(hostname, port, application, *args, **kwargs):

Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374

line 1954why, one step back
1954 rv["result"] = f"running on {hostname}:{port} ..."

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 1955–1958why, one step back
1955
1956 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1957 hostname, port = "localhost", 80001958 app.run(hostname, port, debug=True)

Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374

line 1959why, one step back
1959 assert rv["result"] == f"running on {hostname}:{port} ..."

Merge branch '1.0.x'David Lordbefore adoption465da9f

lines 1960–2013why, one step back
1960
19611962@pytest.mark.parametrize(1963 "host,port,server_name,expect_host,expect_port",1964 (1965 (None, None, "pocoo.org:8080", "pocoo.org", 8080),1966 ("localhost", None, "pocoo.org:8080", "localhost", 8080),1967 (None, 80, "pocoo.org:8080", "pocoo.org", 80),1968 ("localhost", 80, "pocoo.org:8080", "localhost", 80),1969 ("localhost", 0, "localhost:8080", "localhost", 0),1970 (None, None, "localhost:8080", "localhost", 8080),1971 (None, None, "localhost:0", "localhost", 0),1972 ),1973)1974def test_run_from_config(1975 monkeypatch, host, port, server_name, expect_host, expect_port, app1976):1977 def run_simple_mock(hostname, port, *args, **kwargs):1978 assert hostname == expect_host1979 assert port == expect_port19801981 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1982 app.config["SERVER_NAME"] = server_name1983 app.run(host, port)198419851986def test_max_cookie_size(app, client, recwarn):1987 app.config["MAX_COOKIE_SIZE"] = 10019881989 # outside app context, default to Werkzeug static value,1990 # which is also the default config1991 response = flask.Response()1992 default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1993 assert response.max_cookie_size == default19941995 # inside app context, use app config1996 with app.app_context():1997 assert flask.Response().max_cookie_size == 10019981999 @app.route("/")2000 def index():

The first 2,000 of 2,029 lines.