test_helpers.py
This file
Path
tests/test_helpers.py
377 lines · 11.0 KiB · Python
Last changed by
all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
History of this fileTake it
The walk stopped after 200 commits: lines older than 73739a2 point at it.
Merge branch '2.2.x'David Lordbefore adoption73739a2
lines 1–35why, one step back1import io2import os34import pytest5import werkzeug.exceptions67import flask8from flask.helpers import get_debug_flag91011class FakePath:12 """Fake object to represent a ``PathLike object``.1314 This represents a ``pathlib.Path`` object in python 3.15 See: https://www.python.org/dev/peps/pep-0519/16 """1718 def __init__(self, path):19 self.path = path2021 def __fspath__(self):22 return self.path232425class PyBytesIO:26 def __init__(self, *args, **kwargs):27 self._io = io.BytesIO(*args, **kwargs)2829 def __getattr__(self, name):30 return getattr(self._io, name)313233class TestSendfile:34 def test_send_file(self, app, req_ctx):35 with app.open_resource("static/index.html") as f:all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
lines 36–40why, one step back36 expect = f.read()3738 with flask.send_file("static/index.html") as rv:39 assert rv.direct_passthrough40 assert rv.mimetype == "text/html"Merge branch '2.2.x'David Lordbefore adoption73739a2
line 41why, one step back41 rv.direct_passthrough = Falseall teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
line 42why, one step back42 assert rv.data == expectMerge branch '2.2.x'David Lordbefore adoption73739a2
lines 43–47why, one step back4344 def test_static_file(self, app, req_ctx):45 # Default max_age is None.4647 # Test with static file handler.all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
lines 48–49why, one step back48 with app.send_static_file("index.html") as rv:49 assert rv.cache_control.max_age is NoneMerge branch '2.2.x'David Lordbefore adoption73739a2
lines 50–51why, one step back5051 # Test with direct use of send_file.all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
lines 52–53why, one step back52 with flask.send_file("static/index.html") as rv:53 assert rv.cache_control.max_age is NoneMerge branch '2.2.x'David Lordbefore adoption73739a2
lines 54–57why, one step back5455 app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 36005657 # Test with static file handler.all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
lines 58–59why, one step back58 with app.send_static_file("index.html") as rv:59 assert rv.cache_control.max_age == 3600Merge branch '2.2.x'David Lordbefore adoption73739a2
lines 60–61why, one step back6061 # Test with direct use of send_file.all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
lines 62–63why, one step back62 with flask.send_file("static/index.html") as rv:63 assert rv.cache_control.max_age == 3600Merge branch '2.2.x'David Lordbefore adoption73739a2
lines 64–65why, one step back6465 # Test with pathlib.Path.all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
lines 66–67why, one step back66 with app.send_static_file(FakePath("index.html")) as rv:67 assert rv.cache_control.max_age == 3600Merge branch '2.2.x'David Lordbefore adoption73739a2
lines 68–76why, one step back6869 class StaticFileApp(flask.Flask):70 def get_send_file_max_age(self, filename):71 return 107273 app = StaticFileApp(__name__)7475 with app.test_request_context():76 # Test with static file handler.all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
lines 77–78why, one step back77 with app.send_static_file("index.html") as rv:78 assert rv.cache_control.max_age == 10Merge branch '2.2.x'David Lordbefore adoption73739a2
lines 79–80why, one step back7980 # Test with direct use of send_file.all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
lines 81–82why, one step back81 with flask.send_file("static/index.html") as rv:82 assert rv.cache_control.max_age == 10Merge branch '2.2.x'David Lordbefore adoption73739a2
lines 83–88why, one step back8384 def test_send_from_directory(self, app, req_ctx):85 app.root_path = os.path.join(86 os.path.dirname(__file__), "test_apps", "subdomaintestmodule"87 )88all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
lines 89–91why, one step back89 with flask.send_from_directory("static", "hello.txt") as rv:90 rv.direct_passthrough = False91 assert rv.data.strip() == b"Hello Subdomain"Merge branch '2.2.x'David Lordbefore adoption73739a2
line 92why, one step back92all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
line 93why, one step back93Merge branch '2.2.x'David Lordbefore adoption73739a2
lines 94–155why, one step back94class TestUrlFor:95 def test_url_for_with_anchor(self, app, req_ctx):96 @app.route("/")97 def index():98 return "42"99100 assert flask.url_for("index", _anchor="x y") == "/#x%20y"101102 def test_url_for_with_scheme(self, app, req_ctx):103 @app.route("/")104 def index():105 return "42"106107 assert (108 flask.url_for("index", _external=True, _scheme="https")109 == "https://localhost/"110 )111112 def test_url_for_with_scheme_not_external(self, app, req_ctx):113 app.add_url_rule("/", endpoint="index")114115 # Implicit external with scheme.116 url = flask.url_for("index", _scheme="https")117 assert url == "https://localhost/"118119 # Error when external=False with scheme120 with pytest.raises(ValueError):121 flask.url_for("index", _scheme="https", _external=False)122123 def test_url_for_with_alternating_schemes(self, app, req_ctx):124 @app.route("/")125 def index():126 return "42"127128 assert flask.url_for("index", _external=True) == "http://localhost/"129 assert (130 flask.url_for("index", _external=True, _scheme="https")131 == "https://localhost/"132 )133 assert flask.url_for("index", _external=True) == "http://localhost/"134135 def test_url_with_method(self, app, req_ctx):136 from flask.views import MethodView137138 class MyView(MethodView):139 def get(self, id=None):140 if id is None:141 return "List"142 return f"Get {id:d}"143144 def post(self):145 return "Create"146147 myview = MyView.as_view("myview")148 app.add_url_rule("/myview/", methods=["GET"], view_func=myview)149 app.add_url_rule("/myview/<int:id>", methods=["GET"], view_func=myview)150 app.add_url_rule("/myview/create", methods=["POST"], view_func=myview)151152 assert flask.url_for("myview", _method="GET") == "/myview/"153 assert flask.url_for("myview", id=42, _method="GET") == "/myview/42"154 assert flask.url_for("myview", _method="POST") == "/myview/create"155Allow self as an argument to url_forpgjonesbefore adoption438edcd
lines 156–162why, one step back156 def test_url_for_with_self(self, app, req_ctx):157 @app.route("/<self>")158 def index(self):159 return "42"160161 assert flask.url_for("index", self="2") == "/2"162Merge branch '2.2.x'David Lordbefore adoption73739a2
lines 163–219why, one step back163164def test_redirect_no_app():165 response = flask.redirect("https://localhost", 307)166 assert response.location == "https://localhost"167 assert response.status_code == 307168169170def test_redirect_with_app(app):171 def redirect(location, code=302):172 raise ValueError173174 app.redirect = redirect175176 with app.app_context(), pytest.raises(ValueError):177 flask.redirect("other")178179180def test_abort_no_app():181 with pytest.raises(werkzeug.exceptions.Unauthorized):182 flask.abort(401)183184 with pytest.raises(LookupError):185 flask.abort(900)186187188def test_app_aborter_class():189 class MyAborter(werkzeug.exceptions.Aborter):190 pass191192 class MyFlask(flask.Flask):193 aborter_class = MyAborter194195 app = MyFlask(__name__)196 assert isinstance(app.aborter, MyAborter)197198199def test_abort_with_app(app):200 class My900Error(werkzeug.exceptions.HTTPException):201 code = 900202203 app.aborter.mapping[900] = My900Error204205 with app.app_context(), pytest.raises(My900Error):206 flask.abort(900)207208209class TestNoImports:210 """Test Flasks are created without import.211212 Avoiding ``__import__`` helps create Flask instances where there are errors213 at import time. Those runtime errors will be apparent to the user soon214 enough, but tools which build Flask instances meta-programmatically benefit215 from a Flask which does not ``__import__``. Instead of importing to216 retrieve file paths or metadata on a module or package, use the pkgutil and217 imp modules in the Python standard library.218 """219Merge branch '2.3.x'David Lordbefore adoption57e926c
lines 220–221why, one step back220 def test_name_with_import_error(self, modules_tmp_path):221 (modules_tmp_path / "importerror.py").write_text("raise NotImplementedError()")Merge branch '2.2.x'David Lordbefore adoption73739a2
lines 222–300why, one step back222 try:223 flask.Flask("importerror")224 except NotImplementedError:225 AssertionError("Flask(import_name) is importing import_name.")226227228class TestStreaming:229 def test_streaming_with_context(self, app, client):230 @app.route("/")231 def index():232 def generate():233 yield "Hello "234 yield flask.request.args["name"]235 yield "!"236237 return flask.Response(flask.stream_with_context(generate()))238239 rv = client.get("/?name=World")240 assert rv.data == b"Hello World!"241242 def test_streaming_with_context_as_decorator(self, app, client):243 @app.route("/")244 def index():245 @flask.stream_with_context246 def generate(hello):247 yield hello248 yield flask.request.args["name"]249 yield "!"250251 return flask.Response(generate("Hello "))252253 rv = client.get("/?name=World")254 assert rv.data == b"Hello World!"255256 def test_streaming_with_context_and_custom_close(self, app, client):257 called = []258259 class Wrapper:260 def __init__(self, gen):261 self._gen = gen262263 def __iter__(self):264 return self265266 def close(self):267 called.append(42)268269 def __next__(self):270 return next(self._gen)271272 next = __next__273274 @app.route("/")275 def index():276 def generate():277 yield "Hello "278 yield flask.request.args["name"]279 yield "!"280281 return flask.Response(flask.stream_with_context(Wrapper(generate())))282283 rv = client.get("/?name=World")284 assert rv.data == b"Hello World!"285 assert called == [42]286287 def test_stream_keeps_session(self, app, client):288 @app.route("/")289 def index():290 flask.session["test"] = "flask"291292 @flask.stream_with_context293 def gen():294 yield flask.session["test"]295296 return flask.Response(gen())297298 rv = client.get("/")299 assert rv.data == b"flask"300Merge branch 'stable'David Lordbefore adoption3301232
lines 301–313why, one step back301 def test_async_view(self, app, client):302 @app.route("/")303 async def index():304 flask.session["test"] = "flask"305306 @flask.stream_with_context307 def gen():308 yield flask.session["test"]309310 return flask.Response(gen())311312 # response is closed without reading stream313 client.get().close()all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
line 314why, one step back314Merge branch 'stable'David Lordbefore adoption3301232
line 315why, one step back315 # response stream is readall teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
lines 316–317why, one step back316 with client.get() as rv:317 assert rv.text == "flask"Merge branch 'stable'David Lordbefore adoption3301232
lines 318–322why, one step back318319 # same as above, but with client context preservation320 with client:321 client.get().close()322all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8
lines 323–324why, one step back323 with client, client.get() as rv:324 assert rv.text == "flask"Merge branch 'stable'David Lordbefore adoption3301232
line 325why, one step back325Merge branch '2.2.x'David Lordbefore adoption73739a2
lines 326–354why, one step back326327class TestHelpers:328 @pytest.mark.parametrize(329 ("debug", "expect"),330 [331 ("", False),332 ("0", False),333 ("False", False),334 ("No", False),335 ("True", True),336 ],337 )338 def test_get_debug_flag(self, monkeypatch, debug, expect):339 monkeypatch.setenv("FLASK_DEBUG", debug)340 assert get_debug_flag() == expect341342 def test_make_response(self):343 app = flask.Flask(__name__)344 with app.test_request_context():345 rv = flask.helpers.make_response()346 assert rv.status_code == 200347 assert rv.mimetype == "text/html"348349 rv = flask.helpers.make_response("Hello")350 assert rv.status_code == 200351 assert rv.data == b"Hello"352 assert rv.mimetype == "text/html"353354Add encoding parameter to open resource (#5526)David Lordbefore adoptiona8956fe
lines 355–357why, one step back355@pytest.mark.parametrize("mode", ("r", "rb", "rt"))356def test_open_resource(mode):357 app = flask.Flask(__name__)Merge branch '2.2.x'David Lordbefore adoption73739a2
line 358why, one step back358Add encoding parameter to open resource (#5526)David Lordbefore adoptiona8956fe
lines 359–360why, one step back359 with app.open_resource("static/index.html", mode) as f:360 assert "<h1>Hello World!</h1>" in str(f.read())Merge branch '2.2.x'David Lordbefore adoption73739a2
line 361why, one step back361Add encoding parameter to open resource (#5526)David Lordbefore adoptiona8956fe
lines 362–377why, one step back362363@pytest.mark.parametrize("mode", ("w", "x", "a", "r+"))364def test_open_resource_exceptions(mode):365 app = flask.Flask(__name__)366367 with pytest.raises(ValueError):368 app.open_resource("static/index.html", mode)369370371@pytest.mark.parametrize("encoding", ("utf-8", "utf-16-le"))372def test_open_resource_with_encoding(tmp_path, encoding):373 app = flask.Flask(__name__, root_path=os.fspath(tmp_path))374 (tmp_path / "test").write_text("test", encoding=encoding)375376 with app.open_resource("test", mode="rt", encoding=encoding) as f:377 assert f.read() == "test"