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
1import 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:36 expect = f.read()3738 with flask.send_file("static/index.html") as rv:39 assert rv.direct_passthrough40 assert rv.mimetype == "text/html"41 rv.direct_passthrough = False42 assert rv.data == expect4344 def test_static_file(self, app, req_ctx):45 # Default max_age is None.4647 # Test with static file handler.48 with app.send_static_file("index.html") as rv:49 assert rv.cache_control.max_age is None5051 # Test with direct use of send_file.52 with flask.send_file("static/index.html") as rv:53 assert rv.cache_control.max_age is None5455 app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 36005657 # Test with static file handler.58 with app.send_static_file("index.html") as rv:59 assert rv.cache_control.max_age == 36006061 # Test with direct use of send_file.62 with flask.send_file("static/index.html") as rv:63 assert rv.cache_control.max_age == 36006465 # Test with pathlib.Path.66 with app.send_static_file(FakePath("index.html")) as rv:67 assert rv.cache_control.max_age == 36006869 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.77 with app.send_static_file("index.html") as rv:78 assert rv.cache_control.max_age == 107980 # Test with direct use of send_file.81 with flask.send_file("static/index.html") as rv:82 assert rv.cache_control.max_age == 108384 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 )8889 with flask.send_from_directory("static", "hello.txt") as rv:90 rv.direct_passthrough = False91 assert rv.data.strip() == b"Hello Subdomain"929394class 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"155156 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"162163164def 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 """219220 def test_name_with_import_error(self, modules_tmp_path):221 (modules_tmp_path / "importerror.py").write_text("raise NotImplementedError()")222 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"300301 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()314315 # response stream is read316 with client.get() as rv:317 assert rv.text == "flask"318319 # same as above, but with client context preservation320 with client:321 client.get().close()322323 with client, client.get() as rv:324 assert rv.text == "flask"325326327class 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"353354355@pytest.mark.parametrize("mode", ("r", "rb", "rt"))356def test_open_resource(mode):357 app = flask.Flask(__name__)358359 with app.open_resource("static/index.html", mode) as f:360 assert "<h1>Hello World!</h1>" in str(f.read())361362363@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"