test_helpers.py
This file
Path
tests/test_helpers.py
349 lines · 10.0 KiB · Python
Last changed by
Allow self as an argument to url_forpgjonesbefore adoption438edcd
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 rv = flask.send_file("static/index.html")36 assert rv.direct_passthrough37 assert rv.mimetype == "text/html"3839 with app.open_resource("static/index.html") as f:40 rv.direct_passthrough = False41 assert rv.data == f.read()4243 rv.close()4445 def test_static_file(self, app, req_ctx):46 # Default max_age is None.4748 # Test with static file handler.49 rv = app.send_static_file("index.html")50 assert rv.cache_control.max_age is None51 rv.close()5253 # Test with direct use of send_file.54 rv = flask.send_file("static/index.html")55 assert rv.cache_control.max_age is None56 rv.close()5758 app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 36005960 # Test with static file handler.61 rv = app.send_static_file("index.html")62 assert rv.cache_control.max_age == 360063 rv.close()6465 # Test with direct use of send_file.66 rv = flask.send_file("static/index.html")67 assert rv.cache_control.max_age == 360068 rv.close()6970 # Test with pathlib.Path.71 rv = app.send_static_file(FakePath("index.html"))72 assert rv.cache_control.max_age == 360073 rv.close()7475 class StaticFileApp(flask.Flask):76 def get_send_file_max_age(self, filename):77 return 107879 app = StaticFileApp(__name__)8081 with app.test_request_context():82 # Test with static file handler.83 rv = app.send_static_file("index.html")84 assert rv.cache_control.max_age == 1085 rv.close()8687 # Test with direct use of send_file.88 rv = flask.send_file("static/index.html")89 assert rv.cache_control.max_age == 1090 rv.close()9192 def test_send_from_directory(self, app, req_ctx):93 app.root_path = os.path.join(94 os.path.dirname(__file__), "test_apps", "subdomaintestmodule"95 )96 rv = flask.send_from_directory("static", "hello.txt")97 rv.direct_passthrough = False98 assert rv.data.strip() == b"Hello Subdomain"99 rv.close()100101102class TestUrlFor:103 def test_url_for_with_anchor(self, app, req_ctx):104 @app.route("/")105 def index():106 return "42"107108 assert flask.url_for("index", _anchor="x y") == "/#x%20y"109110 def test_url_for_with_scheme(self, app, req_ctx):111 @app.route("/")112 def index():113 return "42"114115 assert (116 flask.url_for("index", _external=True, _scheme="https")117 == "https://localhost/"118 )119120 def test_url_for_with_scheme_not_external(self, app, req_ctx):121 app.add_url_rule("/", endpoint="index")122123 # Implicit external with scheme.124 url = flask.url_for("index", _scheme="https")125 assert url == "https://localhost/"126127 # Error when external=False with scheme128 with pytest.raises(ValueError):129 flask.url_for("index", _scheme="https", _external=False)130131 def test_url_for_with_alternating_schemes(self, app, req_ctx):132 @app.route("/")133 def index():134 return "42"135136 assert flask.url_for("index", _external=True) == "http://localhost/"137 assert (138 flask.url_for("index", _external=True, _scheme="https")139 == "https://localhost/"140 )141 assert flask.url_for("index", _external=True) == "http://localhost/"142143 def test_url_with_method(self, app, req_ctx):144 from flask.views import MethodView145146 class MyView(MethodView):147 def get(self, id=None):148 if id is None:149 return "List"150 return f"Get {id:d}"151152 def post(self):153 return "Create"154155 myview = MyView.as_view("myview")156 app.add_url_rule("/myview/", methods=["GET"], view_func=myview)157 app.add_url_rule("/myview/<int:id>", methods=["GET"], view_func=myview)158 app.add_url_rule("/myview/create", methods=["POST"], view_func=myview)159160 assert flask.url_for("myview", _method="GET") == "/myview/"161 assert flask.url_for("myview", id=42, _method="GET") == "/myview/42"162 assert flask.url_for("myview", _method="POST") == "/myview/create"163164 def test_url_for_with_self(self, app, req_ctx):165 @app.route("/<self>")166 def index(self):167 return "42"168169 assert flask.url_for("index", self="2") == "/2"170171172def test_redirect_no_app():173 response = flask.redirect("https://localhost", 307)174 assert response.location == "https://localhost"175 assert response.status_code == 307176177178def test_redirect_with_app(app):179 def redirect(location, code=302):180 raise ValueError181182 app.redirect = redirect183184 with app.app_context(), pytest.raises(ValueError):185 flask.redirect("other")186187188def test_abort_no_app():189 with pytest.raises(werkzeug.exceptions.Unauthorized):190 flask.abort(401)191192 with pytest.raises(LookupError):193 flask.abort(900)194195196def test_app_aborter_class():197 class MyAborter(werkzeug.exceptions.Aborter):198 pass199200 class MyFlask(flask.Flask):201 aborter_class = MyAborter202203 app = MyFlask(__name__)204 assert isinstance(app.aborter, MyAborter)205206207def test_abort_with_app(app):208 class My900Error(werkzeug.exceptions.HTTPException):209 code = 900210211 app.aborter.mapping[900] = My900Error212213 with app.app_context(), pytest.raises(My900Error):214 flask.abort(900)215216217class TestNoImports:218 """Test Flasks are created without import.219220 Avoiding ``__import__`` helps create Flask instances where there are errors221 at import time. Those runtime errors will be apparent to the user soon222 enough, but tools which build Flask instances meta-programmatically benefit223 from a Flask which does not ``__import__``. Instead of importing to224 retrieve file paths or metadata on a module or package, use the pkgutil and225 imp modules in the Python standard library.226 """227228 def test_name_with_import_error(self, modules_tmp_path):229 (modules_tmp_path / "importerror.py").write_text("raise NotImplementedError()")230 try:231 flask.Flask("importerror")232 except NotImplementedError:233 AssertionError("Flask(import_name) is importing import_name.")234235236class TestStreaming:237 def test_streaming_with_context(self, app, client):238 @app.route("/")239 def index():240 def generate():241 yield "Hello "242 yield flask.request.args["name"]243 yield "!"244245 return flask.Response(flask.stream_with_context(generate()))246247 rv = client.get("/?name=World")248 assert rv.data == b"Hello World!"249250 def test_streaming_with_context_as_decorator(self, app, client):251 @app.route("/")252 def index():253 @flask.stream_with_context254 def generate(hello):255 yield hello256 yield flask.request.args["name"]257 yield "!"258259 return flask.Response(generate("Hello "))260261 rv = client.get("/?name=World")262 assert rv.data == b"Hello World!"263264 def test_streaming_with_context_and_custom_close(self, app, client):265 called = []266267 class Wrapper:268 def __init__(self, gen):269 self._gen = gen270271 def __iter__(self):272 return self273274 def close(self):275 called.append(42)276277 def __next__(self):278 return next(self._gen)279280 next = __next__281282 @app.route("/")283 def index():284 def generate():285 yield "Hello "286 yield flask.request.args["name"]287 yield "!"288289 return flask.Response(flask.stream_with_context(Wrapper(generate())))290291 rv = client.get("/?name=World")292 assert rv.data == b"Hello World!"293 assert called == [42]294295 def test_stream_keeps_session(self, app, client):296 @app.route("/")297 def index():298 flask.session["test"] = "flask"299300 @flask.stream_with_context301 def gen():302 yield flask.session["test"]303304 return flask.Response(gen())305306 rv = client.get("/")307 assert rv.data == b"flask"308309310class TestHelpers:311 @pytest.mark.parametrize(312 ("debug", "expect"),313 [314 ("", False),315 ("0", False),316 ("False", False),317 ("No", False),318 ("True", True),319 ],320 )321 def test_get_debug_flag(self, monkeypatch, debug, expect):322 monkeypatch.setenv("FLASK_DEBUG", debug)323 assert get_debug_flag() == expect324325 def test_make_response(self):326 app = flask.Flask(__name__)327 with app.test_request_context():328 rv = flask.helpers.make_response()329 assert rv.status_code == 200330 assert rv.mimetype == "text/html"331332 rv = flask.helpers.make_response("Hello")333 assert rv.status_code == 200334 assert rv.data == b"Hello"335 assert rv.mimetype == "text/html"336337 @pytest.mark.parametrize("mode", ("r", "rb", "rt"))338 def test_open_resource(self, mode):339 app = flask.Flask(__name__)340341 with app.open_resource("static/index.html", mode) as f:342 assert "<h1>Hello World!</h1>" in str(f.read())343344 @pytest.mark.parametrize("mode", ("w", "x", "a", "r+"))345 def test_open_resource_exceptions(self, mode):346 app = flask.Flask(__name__)347348 with pytest.raises(ValueError):349 app.open_resource("static/index.html", mode)