Skip to content
Myr

test_templating.py

This file

Path

tests/test_templating.py

451 lines · 12.1 KiB · Python

Last changed by

Merge pull request #3183 from singingwolfboy/pre-commitDavid Baumgoldbefore adoption1dda032

History of this file

Take it

1# -*- coding: utf-8 -*-2"""3    tests.templating4    ~~~~~~~~~~~~~~~~56    Template functionality78    :copyright: © 2010 by the Pallets team.9    :license: BSD, see LICENSE for more details.10"""1112import pytest1314import flask15import logging16from jinja2 import TemplateNotFound17import werkzeug.serving181920def test_context_processing(app, client):21    @app.context_processor22    def context_processor():23        return {"injected_value": 42}2425    @app.route("/")26    def index():27        return flask.render_template("context_template.html", value=23)2829    rv = client.get("/")30    assert rv.data == b"<p>23|42"313233def test_original_win(app, client):34    @app.route("/")35    def index():36        return flask.render_template_string("{{ config }}", config=42)3738    rv = client.get("/")39    assert rv.data == b"42"404142def 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(77            "escaping_template.html", text=text, html=flask.Markup(text)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(97            "non_escaping_template.txt", text=text, html=flask.Markup(text)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 app.templates_auto_reload == False402    assert app.jinja_env.auto_reload == False403404    app.run(debug=True)405    assert app.templates_auto_reload == True406    assert app.jinja_env.auto_reload == True407408409def test_template_loader_debugging(test_apps, monkeypatch):410    from blueprintapp import app411412    called = []413414    class _TestHandler(logging.Handler):415        def handle(x, record):416            called.append(True)417            text = str(record.msg)418            assert '1: trying loader of application "blueprintapp"' in text419            assert (420                '2: trying loader of blueprint "admin" ' "(blueprintapp.apps.admin)"421            ) in text422            assert (423                'trying loader of blueprint "frontend" ' "(blueprintapp.apps.frontend)"424            ) in text425            assert "Error: the template could not be found" in text426            assert (427                "looked up from an endpoint that belongs to " 'the blueprint "frontend"'428            ) in text429            assert "See http://flask.pocoo.org/docs/blueprints/#templates" in text430431    with app.test_client() as c:432        monkeypatch.setitem(app.config, "EXPLAIN_TEMPLATE_LOADING", True)433        monkeypatch.setattr(logging.getLogger("flask"), "handlers", [_TestHandler()])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)