Skip to content
Myr

test_templating.py

This file

Path

tests/test_templating.py

451 lines · 12.0 KiB · Python

Last changed by

Merge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689

History of this file

Take it

The walk stopped after 200 commits: lines older than 93a7f08 point at it.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

lines 1–5why, one step back
1import logging
23import pytest4import werkzeug.serving5from jinja2 import TemplateNotFound

Merge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689

line 6why, one step back
6from markupsafe import Markup

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

lines 7–32why, one step back
7
8import flask91011def test_context_processing(app, client):12 @app.context_processor13 def context_processor():14 return {"injected_value": 42}1516 @app.route("/")17 def index():18 return flask.render_template("context_template.html", value=23)1920 rv = client.get("/")21 assert rv.data == b"<p>23|42"222324def test_original_win(app, client):25 @app.route("/")26 def index():27 return flask.render_template_string("{{ config }}", config=42)2829 rv = client.get("/")30 assert rv.data == b"42"3132

Merge pull request #4629 from pgjones/generateDavid Lordbefore adoptionab36542

lines 33–41why, one step back
33def test_simple_stream(app, client):
34 @app.route("/")35 def index():36 return flask.stream_template_string("{{ config }}", config=42)3738 rv = client.get("/")39 assert rv.data == b"42"4041

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

lines 42–76why, one step back
42def test_request_less_rendering(app, app_ctx):
43 app.config["WORLD_NAME"] = "Special World"4445 @app.context_processor46 def context_processor():47 return dict(foo=42)4849 rv = flask.render_template_string("Hello {{ config.WORLD_NAME }} {{ foo }}")50 assert rv == "Hello Special World 42"515253def test_standard_context(app, client):54 @app.route("/")55 def index():56 flask.g.foo = 2357 flask.session["test"] = "aha"58 return flask.render_template_string(59 """60 {{ request.args.foo }}61 {{ g.foo }}62 {{ config.DEBUG }}63 {{ session.test }}64 """65 )6667 rv = client.get("/?foo=42")68 assert rv.data.split() == [b"42", b"23", b"False", b"aha"]697071def test_escaping(app, client):72 text = "<p>Hello World!"7374 @app.route("/")75 def index():76 return flask.render_template(

Merge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689

line 77why, one step back
77 "escaping_template.html", text=text, html=Markup(text)

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

lines 78–96why, one step back
78 )
7980 lines = client.get("/").data.splitlines()81 assert lines == [82 b"&lt;p&gt;Hello World!",83 b"<p>Hello World!",84 b"<p>Hello World!",85 b"<p>Hello World!",86 b"&lt;p&gt;Hello World!",87 b"<p>Hello World!",88 ]899091def test_no_escaping(app, client):92 text = "<p>Hello World!"9394 @app.route("/")95 def index():96 return flask.render_template(

Merge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689

line 97why, one step back
97 "non_escaping_template.txt", text=text, html=Markup(text)

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

lines 98–451why, one step back
98 )
99100 lines = client.get("/").data.splitlines()101 assert lines == [102 b"<p>Hello World!",103 b"<p>Hello World!",104 b"<p>Hello World!",105 b"<p>Hello World!",106 b"&lt;p&gt;Hello World!",107 b"<p>Hello World!",108 b"<p>Hello World!",109 b"<p>Hello World!",110 ]111112113def test_escaping_without_template_filename(app, client, req_ctx):114 assert flask.render_template_string("{{ foo }}", foo="<test>") == "&lt;test&gt;"115 assert flask.render_template("mail.txt", foo="<test>") == "<test> Mail"116117118def test_macros(app, req_ctx):119 macro = flask.get_template_attribute("_macro.html", "hello")120 assert macro("World") == "Hello World!"121122123def test_template_filter(app):124 @app.template_filter()125 def my_reverse(s):126 return s[::-1]127128 assert "my_reverse" in app.jinja_env.filters.keys()129 assert app.jinja_env.filters["my_reverse"] == my_reverse130 assert app.jinja_env.filters["my_reverse"]("abcd") == "dcba"131132133def test_add_template_filter(app):134 def my_reverse(s):135 return s[::-1]136137 app.add_template_filter(my_reverse)138 assert "my_reverse" in app.jinja_env.filters.keys()139 assert app.jinja_env.filters["my_reverse"] == my_reverse140 assert app.jinja_env.filters["my_reverse"]("abcd") == "dcba"141142143def test_template_filter_with_name(app):144 @app.template_filter("strrev")145 def my_reverse(s):146 return s[::-1]147148 assert "strrev" in app.jinja_env.filters.keys()149 assert app.jinja_env.filters["strrev"] == my_reverse150 assert app.jinja_env.filters["strrev"]("abcd") == "dcba"151152153def test_add_template_filter_with_name(app):154 def my_reverse(s):155 return s[::-1]156157 app.add_template_filter(my_reverse, "strrev")158 assert "strrev" in app.jinja_env.filters.keys()159 assert app.jinja_env.filters["strrev"] == my_reverse160 assert app.jinja_env.filters["strrev"]("abcd") == "dcba"161162163def test_template_filter_with_template(app, client):164 @app.template_filter()165 def super_reverse(s):166 return s[::-1]167168 @app.route("/")169 def index():170 return flask.render_template("template_filter.html", value="abcd")171172 rv = client.get("/")173 assert rv.data == b"dcba"174175176def test_add_template_filter_with_template(app, client):177 def super_reverse(s):178 return s[::-1]179180 app.add_template_filter(super_reverse)181182 @app.route("/")183 def index():184 return flask.render_template("template_filter.html", value="abcd")185186 rv = client.get("/")187 assert rv.data == b"dcba"188189190def test_template_filter_with_name_and_template(app, client):191 @app.template_filter("super_reverse")192 def my_reverse(s):193 return s[::-1]194195 @app.route("/")196 def index():197 return flask.render_template("template_filter.html", value="abcd")198199 rv = client.get("/")200 assert rv.data == b"dcba"201202203def test_add_template_filter_with_name_and_template(app, client):204 def my_reverse(s):205 return s[::-1]206207 app.add_template_filter(my_reverse, "super_reverse")208209 @app.route("/")210 def index():211 return flask.render_template("template_filter.html", value="abcd")212213 rv = client.get("/")214 assert rv.data == b"dcba"215216217def test_template_test(app):218 @app.template_test()219 def boolean(value):220 return isinstance(value, bool)221222 assert "boolean" in app.jinja_env.tests.keys()223 assert app.jinja_env.tests["boolean"] == boolean224 assert app.jinja_env.tests["boolean"](False)225226227def test_add_template_test(app):228 def boolean(value):229 return isinstance(value, bool)230231 app.add_template_test(boolean)232 assert "boolean" in app.jinja_env.tests.keys()233 assert app.jinja_env.tests["boolean"] == boolean234 assert app.jinja_env.tests["boolean"](False)235236237def test_template_test_with_name(app):238 @app.template_test("boolean")239 def is_boolean(value):240 return isinstance(value, bool)241242 assert "boolean" in app.jinja_env.tests.keys()243 assert app.jinja_env.tests["boolean"] == is_boolean244 assert app.jinja_env.tests["boolean"](False)245246247def test_add_template_test_with_name(app):248 def is_boolean(value):249 return isinstance(value, bool)250251 app.add_template_test(is_boolean, "boolean")252 assert "boolean" in app.jinja_env.tests.keys()253 assert app.jinja_env.tests["boolean"] == is_boolean254 assert app.jinja_env.tests["boolean"](False)255256257def test_template_test_with_template(app, client):258 @app.template_test()259 def boolean(value):260 return isinstance(value, bool)261262 @app.route("/")263 def index():264 return flask.render_template("template_test.html", value=False)265266 rv = client.get("/")267 assert b"Success!" in rv.data268269270def test_add_template_test_with_template(app, client):271 def boolean(value):272 return isinstance(value, bool)273274 app.add_template_test(boolean)275276 @app.route("/")277 def index():278 return flask.render_template("template_test.html", value=False)279280 rv = client.get("/")281 assert b"Success!" in rv.data282283284def test_template_test_with_name_and_template(app, client):285 @app.template_test("boolean")286 def is_boolean(value):287 return isinstance(value, bool)288289 @app.route("/")290 def index():291 return flask.render_template("template_test.html", value=False)292293 rv = client.get("/")294 assert b"Success!" in rv.data295296297def test_add_template_test_with_name_and_template(app, client):298 def is_boolean(value):299 return isinstance(value, bool)300301 app.add_template_test(is_boolean, "boolean")302303 @app.route("/")304 def index():305 return flask.render_template("template_test.html", value=False)306307 rv = client.get("/")308 assert b"Success!" in rv.data309310311def test_add_template_global(app, app_ctx):312 @app.template_global()313 def get_stuff():314 return 42315316 assert "get_stuff" in app.jinja_env.globals.keys()317 assert app.jinja_env.globals["get_stuff"] == get_stuff318 assert app.jinja_env.globals["get_stuff"](), 42319320 rv = flask.render_template_string("{{ get_stuff() }}")321 assert rv == "42"322323324def test_custom_template_loader(client):325 class MyFlask(flask.Flask):326 def create_global_jinja_loader(self):327 from jinja2 import DictLoader328329 return DictLoader({"index.html": "Hello Custom World!"})330331 app = MyFlask(__name__)332333 @app.route("/")334 def index():335 return flask.render_template("index.html")336337 c = app.test_client()338 rv = c.get("/")339 assert rv.data == b"Hello Custom World!"340341342def test_iterable_loader(app, client):343 @app.context_processor344 def context_processor():345 return {"whiskey": "Jameson"}346347 @app.route("/")348 def index():349 return flask.render_template(350 [351 "no_template.xml", # should skip this one352 "simple_template.html", # should render this353 "context_template.html",354 ],355 value=23,356 )357358 rv = client.get("/")359 assert rv.data == b"<h1>Jameson</h1>"360361362def test_templates_auto_reload(app):363 # debug is False, config option is None364 assert app.debug is False365 assert app.config["TEMPLATES_AUTO_RELOAD"] is None366 assert app.jinja_env.auto_reload is False367 # debug is False, config option is False368 app = flask.Flask(__name__)369 app.config["TEMPLATES_AUTO_RELOAD"] = False370 assert app.debug is False371 assert app.jinja_env.auto_reload is False372 # debug is False, config option is True373 app = flask.Flask(__name__)374 app.config["TEMPLATES_AUTO_RELOAD"] = True375 assert app.debug is False376 assert app.jinja_env.auto_reload is True377 # debug is True, config option is None378 app = flask.Flask(__name__)379 app.config["DEBUG"] = True380 assert app.config["TEMPLATES_AUTO_RELOAD"] is None381 assert app.jinja_env.auto_reload is True382 # debug is True, config option is False383 app = flask.Flask(__name__)384 app.config["DEBUG"] = True385 app.config["TEMPLATES_AUTO_RELOAD"] = False386 assert app.jinja_env.auto_reload is False387 # debug is True, config option is True388 app = flask.Flask(__name__)389 app.config["DEBUG"] = True390 app.config["TEMPLATES_AUTO_RELOAD"] = True391 assert app.jinja_env.auto_reload is True392393394def test_templates_auto_reload_debug_run(app, monkeypatch):395 def run_simple_mock(*args, **kwargs):396 pass397398 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)399400 app.run()401 assert not app.jinja_env.auto_reload402403 app.run(debug=True)404 assert app.jinja_env.auto_reload405406407def test_template_loader_debugging(test_apps, monkeypatch):408 from blueprintapp import app409410 called = []411412 class _TestHandler(logging.Handler):413 def handle(self, record):414 called.append(True)415 text = str(record.msg)416 assert "1: trying loader of application 'blueprintapp'" in text417 assert (418 "2: trying loader of blueprint 'admin' (blueprintapp.apps.admin)"419 ) in text420 assert (421 "trying loader of blueprint 'frontend' (blueprintapp.apps.frontend)"422 ) in text423 assert "Error: the template could not be found" in text424 assert (425 "looked up from an endpoint that belongs to the blueprint 'frontend'"426 ) in text427 assert "See https://flask.palletsprojects.com/blueprints/#templates" in text428429 with app.test_client() as c:430 monkeypatch.setitem(app.config, "EXPLAIN_TEMPLATE_LOADING", True)431 monkeypatch.setattr(432 logging.getLogger("blueprintapp"), "handlers", [_TestHandler()]433 )434435 with pytest.raises(TemplateNotFound) as excinfo:436 c.get("/missing")437438 assert "missing_template.html" in str(excinfo.value)439440 assert len(called) == 1441442443def test_custom_jinja_env():444 class CustomEnvironment(flask.templating.Environment):445 pass446447 class CustomFlask(flask.Flask):448 jinja_environment = CustomEnvironment449450 app = CustomFlask(__name__)451 assert isinstance(app.jinja_env, CustomEnvironment)