Browse Source

WIP

pull/1165/head
Markus Unterwaditzer 10 years ago
parent
commit
d0cf5ef394
  1. 19
      tests/__init__.py
  2. 24
      tests/conftest.py
  3. 192
      tests/test_appctx.py
  4. 222
      tests/test_ext.py
  5. 48
      tests/test_subclassing.py
  6. 654
      tests/test_templating.py

19
tests/__init__.py

@ -90,25 +90,6 @@ class TestFlask(object):
consistency. consistency.
""" """
@pytest.fixture(autouse=True)
def setup_path(self, monkeypatch):
monkeypatch.syspath_prepend(
os.path.abspath(os.path.join(
os.path.dirname(__file__), 'test_apps'))
)
@pytest.fixture(autouse=True)
def leak_detector(self, request):
request.addfinalizer(self.ensure_clean_request_context)
def ensure_clean_request_context(self):
# make sure we're not leaking a request context since we are
# testing flask internally in debug mode in a few cases
leaks = []
while flask._request_ctx_stack.top is not None:
leaks.append(flask._request_ctx_stack.pop())
assert leaks == []
def setup_method(self, method): def setup_method(self, method):
self.setup() self.setup()

24
tests/conftest.py

@ -6,12 +6,34 @@
:copyright: (c) 2014 by the Flask Team, see AUTHORS for more details. :copyright: (c) 2014 by the Flask Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details. :license: BSD, see LICENSE for more details.
""" """
import flask
import os
import sys
import pkgutil import pkgutil
import pytest import pytest
import sys
import textwrap import textwrap
@pytest.fixture(autouse=True)
def setup_path(monkeypatch):
monkeypatch.syspath_prepend(
os.path.abspath(os.path.join(
os.path.dirname(__file__), 'test_apps'))
)
@pytest.fixture(autouse=True)
def leak_detector(request):
def ensure_clean_request_context():
# make sure we're not leaking a request context since we are
# testing flask internally in debug mode in a few cases
leaks = []
while flask._request_ctx_stack.top is not None:
leaks.append(flask._request_ctx_stack.pop())
assert leaks == []
request.addfinalizer(ensure_clean_request_context)
@pytest.fixture(params=(True, False)) @pytest.fixture(params=(True, False))
def limit_loader(request, monkeypatch): def limit_loader(request, monkeypatch):
"""Patch pkgutil.get_loader to give loader without get_filename or archive. """Patch pkgutil.get_loader to give loader without get_filename or archive.

192
tests/test_appctx.py

@ -16,106 +16,98 @@ import unittest
from tests import TestFlask from tests import TestFlask
class TestAppContext(TestFlask): def test_basic_url_generation():
app = flask.Flask(__name__)
def test_basic_url_generation(self): app.config['SERVER_NAME'] = 'localhost'
app = flask.Flask(__name__) app.config['PREFERRED_URL_SCHEME'] = 'https'
app.config['SERVER_NAME'] = 'localhost'
app.config['PREFERRED_URL_SCHEME'] = 'https' @app.route('/')
def index():
@app.route('/') pass
def index():
pass with app.app_context():
rv = flask.url_for('index')
with app.app_context(): assert rv == 'https://localhost/'
rv = flask.url_for('index')
assert rv == 'https://localhost/' def test_url_generation_requires_server_name():
app = flask.Flask(__name__)
def test_url_generation_requires_server_name(self): with app.app_context():
app = flask.Flask(__name__)
with app.app_context():
with pytest.raises(RuntimeError):
flask.url_for('index')
def test_url_generation_without_context_fails(self):
with pytest.raises(RuntimeError): with pytest.raises(RuntimeError):
flask.url_for('index') flask.url_for('index')
def test_request_context_means_app_context(self): def test_url_generation_without_context_fails():
app = flask.Flask(__name__) with pytest.raises(RuntimeError):
with app.test_request_context(): flask.url_for('index')
assert flask.current_app._get_current_object() == app
assert flask._app_ctx_stack.top == None def test_request_context_means_app_context():
app = flask.Flask(__name__)
def test_app_context_provides_current_app(self): with app.test_request_context():
app = flask.Flask(__name__) assert flask.current_app._get_current_object() == app
with app.app_context(): assert flask._app_ctx_stack.top == None
assert flask.current_app._get_current_object() == app
assert flask._app_ctx_stack.top == None def test_app_context_provides_current_app():
app = flask.Flask(__name__)
def test_app_tearing_down(self): with app.app_context():
cleanup_stuff = [] assert flask.current_app._get_current_object() == app
app = flask.Flask(__name__) assert flask._app_ctx_stack.top == None
@app.teardown_appcontext
def cleanup(exception): def test_app_tearing_down():
cleanup_stuff.append(exception) cleanup_stuff = []
app = flask.Flask(__name__)
with app.app_context(): @app.teardown_appcontext
pass def cleanup(exception):
cleanup_stuff.append(exception)
assert cleanup_stuff == [None]
with app.app_context():
def test_app_tearing_down_with_previous_exception(self): pass
cleanup_stuff = []
app = flask.Flask(__name__) assert cleanup_stuff == [None]
@app.teardown_appcontext
def cleanup(exception): def test_app_tearing_down_with_previous_exception():
cleanup_stuff.append(exception) cleanup_stuff = []
app = flask.Flask(__name__)
try: @app.teardown_appcontext
raise Exception('dummy') def cleanup(exception):
except Exception: cleanup_stuff.append(exception)
pass
try:
with app.app_context(): raise Exception('dummy')
pass except Exception:
pass
assert cleanup_stuff == [None]
with app.app_context():
def test_custom_app_ctx_globals_class(self): pass
class CustomRequestGlobals(object):
def __init__(self): assert cleanup_stuff == [None]
self.spam = 'eggs'
app = flask.Flask(__name__) def test_custom_app_ctx_globals_class():
app.app_ctx_globals_class = CustomRequestGlobals class CustomRequestGlobals(object):
with app.app_context(): def __init__(self):
assert flask.render_template_string('{{ g.spam }}') == 'eggs' self.spam = 'eggs'
app = flask.Flask(__name__)
def test_context_refcounts(self): app.app_ctx_globals_class = CustomRequestGlobals
called = [] with app.app_context():
app = flask.Flask(__name__) assert flask.render_template_string('{{ g.spam }}') == 'eggs'
@app.teardown_request
def teardown_req(error=None): def test_context_refcounts():
called.append('request') called = []
@app.teardown_appcontext app = flask.Flask(__name__)
def teardown_app(error=None): @app.teardown_request
called.append('app') def teardown_req(error=None):
@app.route('/') called.append('request')
def index(): @app.teardown_appcontext
with flask._app_ctx_stack.top: def teardown_app(error=None):
with flask._request_ctx_stack.top: called.append('app')
pass @app.route('/')
env = flask._request_ctx_stack.top.request.environ def index():
assert env['werkzeug.request'] is not None with flask._app_ctx_stack.top:
return u'' with flask._request_ctx_stack.top:
c = app.test_client() pass
res = c.get('/') env = flask._request_ctx_stack.top.request.environ
assert res.status_code == 200 assert env['werkzeug.request'] is not None
assert res.data == b'' return u''
assert called == ['request', 'app'] c = app.test_client()
res = c.get('/')
assert res.status_code == 200
def suite(): assert res.data == b''
suite = unittest.TestSuite() assert called == ['request', 'app']
suite.addTest(unittest.makeSuite(TestAppContext))
return suite

222
tests/test_ext.py

@ -20,120 +20,118 @@ except ImportError:
from tests import TestFlask from tests import TestFlask
from flask._compat import PY2 from flask._compat import PY2
class TestExtImportHook(TestFlask):
@pytest.fixture(autouse=True)
def setup(self): def importhook_setup(monkeypatch, request):
# we clear this out for various reasons. The most important one is # we clear this out for various reasons. The most important one is
# that a real flaskext could be in there which would disable our # that a real flaskext could be in there which would disable our
# fake package. Secondly we want to make sure that the flaskext # fake package. Secondly we want to make sure that the flaskext
# import hook does not break on reloading. # import hook does not break on reloading.
for entry, value in list(sys.modules.items()): for entry, value in list(sys.modules.items()):
if (entry.startswith('flask.ext.') or if (entry.startswith('flask.ext.') or
entry.startswith('flask_') or entry.startswith('flask_') or
entry.startswith('flaskext.') or entry.startswith('flaskext.') or
entry == 'flaskext') and value is not None: entry == 'flaskext') and value is not None:
sys.modules.pop(entry, None) monkeypatch.delitem(sys.modules, entry)
from flask import ext from flask import ext
reload_module(ext) reload_module(ext)
# reloading must not add more hooks # reloading must not add more hooks
import_hooks = 0 import_hooks = 0
for item in sys.meta_path: for item in sys.meta_path:
cls = type(item) cls = type(item)
if cls.__module__ == 'flask.exthook' and \ if cls.__module__ == 'flask.exthook' and \
cls.__name__ == 'ExtensionImporter': cls.__name__ == 'ExtensionImporter':
import_hooks += 1 import_hooks += 1
assert import_hooks == 1 assert import_hooks == 1
def teardown(self): def teardown():
from flask import ext from flask import ext
for key in ext.__dict__: for key in ext.__dict__:
assert '.' not in key assert '.' not in key
def test_flaskext_new_simple_import_normal(self): request.addfinalizer(teardown)
from flask.ext.newext_simple import ext_id
assert ext_id == 'newext_simple' def test_flaskext_new_simple_import_normal():
from flask.ext.newext_simple import ext_id
def test_flaskext_new_simple_import_module(self): assert ext_id == 'newext_simple'
from flask.ext import newext_simple
assert newext_simple.ext_id == 'newext_simple' def test_flaskext_new_simple_import_module():
assert newext_simple.__name__ == 'flask_newext_simple' from flask.ext import newext_simple
assert newext_simple.ext_id == 'newext_simple'
def test_flaskext_new_package_import_normal(self): assert newext_simple.__name__ == 'flask_newext_simple'
from flask.ext.newext_package import ext_id
assert ext_id == 'newext_package' def test_flaskext_new_package_import_normal():
from flask.ext.newext_package import ext_id
def test_flaskext_new_package_import_module(self): assert ext_id == 'newext_package'
from flask.ext import newext_package
assert newext_package.ext_id == 'newext_package' def test_flaskext_new_package_import_module():
assert newext_package.__name__ == 'flask_newext_package' from flask.ext import newext_package
assert newext_package.ext_id == 'newext_package'
def test_flaskext_new_package_import_submodule_function(self): assert newext_package.__name__ == 'flask_newext_package'
from flask.ext.newext_package.submodule import test_function
assert test_function() == 42 def test_flaskext_new_package_import_submodule_function():
from flask.ext.newext_package.submodule import test_function
def test_flaskext_new_package_import_submodule(self): assert test_function() == 42
from flask.ext.newext_package import submodule
assert submodule.__name__ == 'flask_newext_package.submodule' def test_flaskext_new_package_import_submodule():
assert submodule.test_function() == 42 from flask.ext.newext_package import submodule
assert submodule.__name__ == 'flask_newext_package.submodule'
def test_flaskext_old_simple_import_normal(self): assert submodule.test_function() == 42
from flask.ext.oldext_simple import ext_id
assert ext_id == 'oldext_simple' def test_flaskext_old_simple_import_normal():
from flask.ext.oldext_simple import ext_id
def test_flaskext_old_simple_import_module(self): assert ext_id == 'oldext_simple'
from flask.ext import oldext_simple
assert oldext_simple.ext_id == 'oldext_simple' def test_flaskext_old_simple_import_module():
assert oldext_simple.__name__ == 'flaskext.oldext_simple' from flask.ext import oldext_simple
assert oldext_simple.ext_id == 'oldext_simple'
def test_flaskext_old_package_import_normal(self): assert oldext_simple.__name__ == 'flaskext.oldext_simple'
from flask.ext.oldext_package import ext_id
assert ext_id == 'oldext_package' def test_flaskext_old_package_import_normal():
from flask.ext.oldext_package import ext_id
def test_flaskext_old_package_import_module(self): assert ext_id == 'oldext_package'
from flask.ext import oldext_package
assert oldext_package.ext_id == 'oldext_package' def test_flaskext_old_package_import_module():
assert oldext_package.__name__ == 'flaskext.oldext_package' from flask.ext import oldext_package
assert oldext_package.ext_id == 'oldext_package'
def test_flaskext_old_package_import_submodule(self): assert oldext_package.__name__ == 'flaskext.oldext_package'
from flask.ext.oldext_package import submodule
assert submodule.__name__ == 'flaskext.oldext_package.submodule' def test_flaskext_old_package_import_submodule():
assert submodule.test_function() == 42 from flask.ext.oldext_package import submodule
assert submodule.__name__ == 'flaskext.oldext_package.submodule'
def test_flaskext_old_package_import_submodule_function(self): assert submodule.test_function() == 42
from flask.ext.oldext_package.submodule import test_function
assert test_function() == 42 def test_flaskext_old_package_import_submodule_function():
from flask.ext.oldext_package.submodule import test_function
def test_flaskext_broken_package_no_module_caching(self): assert test_function() == 42
for x in range(2):
with pytest.raises(ImportError): def test_flaskext_broken_package_no_module_caching():
import flask.ext.broken for x in range(2):
with pytest.raises(ImportError):
def test_no_error_swallowing(self):
try:
import flask.ext.broken import flask.ext.broken
except ImportError:
exc_type, exc_value, tb = sys.exc_info() def test_no_error_swallowing():
assert exc_type is ImportError try:
if PY2: import flask.ext.broken
message = 'No module named missing_module' except ImportError:
else: exc_type, exc_value, tb = sys.exc_info()
message = 'No module named \'missing_module\'' assert exc_type is ImportError
assert str(exc_value) == message if PY2:
assert tb.tb_frame.f_globals is globals() message = 'No module named missing_module'
else:
# reraise() adds a second frame so we need to skip that one too. message = 'No module named \'missing_module\''
# On PY3 we even have another one :( assert str(exc_value) == message
next = tb.tb_next.tb_next assert tb.tb_frame.f_globals is globals()
if not PY2:
next = next.tb_next # reraise() adds a second frame so we need to skip that one too.
# On PY3 we even have another one :(
import os.path next = tb.tb_next.tb_next
assert os.path.join('flask_broken', '__init__.py') in \ if not PY2:
next.tb_frame.f_code.co_filename next = next.tb_next
import os.path
def suite(): assert os.path.join('flask_broken', '__init__.py') in \
suite = unittest.TestSuite() next.tb_frame.f_code.co_filename
suite.addTest(unittest.makeSuite(TestExtImportHook)) else:
return suite 1/0 # XXX

48
tests/test_subclassing.py

@ -16,31 +16,23 @@ from tests import TestFlask
from flask._compat import StringIO from flask._compat import StringIO
class TestFlaskSubclassing(TestFlask): def test_suppressed_exception_logging():
class SuppressedFlask(flask.Flask):
def test_suppressed_exception_logging(self): def log_exception(self, exc_info):
class SuppressedFlask(flask.Flask): pass
def log_exception(self, exc_info):
pass out = StringIO()
app = SuppressedFlask(__name__)
out = StringIO() app.logger_name = 'flask_tests/test_suppressed_exception_logging'
app = SuppressedFlask(__name__) app.logger.addHandler(StreamHandler(out))
app.logger_name = 'flask_tests/test_suppressed_exception_logging'
app.logger.addHandler(StreamHandler(out)) @app.route('/')
def index():
@app.route('/') 1 // 0
def index():
1 // 0 rv = app.test_client().get('/')
assert rv.status_code == 500
rv = app.test_client().get('/') assert b'Internal Server Error' in rv.data
assert rv.status_code == 500
assert b'Internal Server Error' in rv.data err = out.getvalue()
assert err == ''
err = out.getvalue()
assert err == ''
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestFlaskSubclassing))
return suite

654
tests/test_templating.py

@ -9,6 +9,8 @@
:license: BSD, see LICENSE for more details. :license: BSD, see LICENSE for more details.
""" """
import pytest
import flask import flask
import unittest import unittest
import logging import logging
@ -17,334 +19,324 @@ from jinja2 import TemplateNotFound
from tests import TestFlask from tests import TestFlask
class TestTemplating(TestFlask): def test_context_processing():
app = flask.Flask(__name__)
def test_context_processing(self): @app.context_processor
app = flask.Flask(__name__) def context_processor():
@app.context_processor return {'injected_value': 42}
def context_processor(): @app.route('/')
return {'injected_value': 42} def index():
@app.route('/') return flask.render_template('context_template.html', value=23)
def index(): rv = app.test_client().get('/')
return flask.render_template('context_template.html', value=23) assert rv.data == b'<p>23|42'
rv = app.test_client().get('/')
assert rv.data == b'<p>23|42' def test_original_win():
app = flask.Flask(__name__)
def test_original_win(self): @app.route('/')
app = flask.Flask(__name__) def index():
@app.route('/') return flask.render_template_string('{{ config }}', config=42)
def index(): rv = app.test_client().get('/')
return flask.render_template_string('{{ config }}', config=42) assert rv.data == b'42'
rv = app.test_client().get('/')
assert rv.data == b'42' def test_request_less_rendering():
app = flask.Flask(__name__)
def test_request_less_rendering(self): app.config['WORLD_NAME'] = 'Special World'
app = flask.Flask(__name__) @app.context_processor
app.config['WORLD_NAME'] = 'Special World' def context_processor():
@app.context_processor return dict(foo=42)
def context_processor():
return dict(foo=42) with app.app_context():
rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} '
with app.app_context(): '{{ foo }}')
rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} ' assert rv == 'Hello Special World 42'
'{{ foo }}')
assert rv == 'Hello Special World 42' def test_standard_context():
app = flask.Flask(__name__)
def test_standard_context(self): app.secret_key = 'development key'
app = flask.Flask(__name__) @app.route('/')
app.secret_key = 'development key' def index():
@app.route('/') flask.g.foo = 23
def index(): flask.session['test'] = 'aha'
flask.g.foo = 23 return flask.render_template_string('''
flask.session['test'] = 'aha' {{ request.args.foo }}
return flask.render_template_string(''' {{ g.foo }}
{{ request.args.foo }} {{ config.DEBUG }}
{{ g.foo }} {{ session.test }}
{{ config.DEBUG }} ''')
{{ session.test }} rv = app.test_client().get('/?foo=42')
''') assert rv.data.split() == [b'42', b'23', b'False', b'aha']
rv = app.test_client().get('/?foo=42')
assert rv.data.split() == [b'42', b'23', b'False', b'aha'] def test_escaping():
text = '<p>Hello World!'
def test_escaping(self): app = flask.Flask(__name__)
text = '<p>Hello World!' @app.route('/')
app = flask.Flask(__name__) def index():
@app.route('/') return flask.render_template('escaping_template.html', text=text,
def index(): html=flask.Markup(text))
return flask.render_template('escaping_template.html', text=text, lines = app.test_client().get('/').data.splitlines()
html=flask.Markup(text)) assert lines == [
lines = app.test_client().get('/').data.splitlines() b'&lt;p&gt;Hello World!',
assert lines == [ b'<p>Hello World!',
b'&lt;p&gt;Hello World!', b'<p>Hello World!',
b'<p>Hello World!', b'<p>Hello World!',
b'<p>Hello World!', b'&lt;p&gt;Hello World!',
b'<p>Hello World!', b'<p>Hello World!'
b'&lt;p&gt;Hello World!', ]
b'<p>Hello World!'
] def test_no_escaping():
app = flask.Flask(__name__)
def test_no_escaping(self): with app.test_request_context():
app = flask.Flask(__name__) assert flask.render_template_string(
with app.test_request_context(): '{{ foo }}', foo='<test>') == '<test>'
assert flask.render_template_string( assert flask.render_template('mail.txt', foo='<test>') == \
'{{ foo }}', foo='<test>') == '<test>' '<test> Mail'
assert flask.render_template('mail.txt', foo='<test>') == \
'<test> Mail' def test_macros():
app = flask.Flask(__name__)
def test_macros(self): with app.test_request_context():
app = flask.Flask(__name__) macro = flask.get_template_attribute('_macro.html', 'hello')
with app.test_request_context(): assert macro('World') == 'Hello World!'
macro = flask.get_template_attribute('_macro.html', 'hello')
assert macro('World') == 'Hello World!' def test_template_filter():
app = flask.Flask(__name__)
def test_template_filter(self): @app.template_filter()
app = flask.Flask(__name__) def my_reverse(s):
@app.template_filter() return s[::-1]
def my_reverse(s): assert 'my_reverse' in app.jinja_env.filters.keys()
return s[::-1] assert app.jinja_env.filters['my_reverse'] == my_reverse
assert 'my_reverse' in app.jinja_env.filters.keys() assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'
assert app.jinja_env.filters['my_reverse'] == my_reverse
assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba' def test_add_template_filter():
app = flask.Flask(__name__)
def test_add_template_filter(self): def my_reverse(s):
app = flask.Flask(__name__) return s[::-1]
def my_reverse(s): app.add_template_filter(my_reverse)
return s[::-1] assert 'my_reverse' in app.jinja_env.filters.keys()
app.add_template_filter(my_reverse) assert app.jinja_env.filters['my_reverse'] == my_reverse
assert 'my_reverse' in app.jinja_env.filters.keys() assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'
assert app.jinja_env.filters['my_reverse'] == my_reverse
assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba' def test_template_filter_with_name():
app = flask.Flask(__name__)
def test_template_filter_with_name(self): @app.template_filter('strrev')
app = flask.Flask(__name__) def my_reverse(s):
@app.template_filter('strrev') return s[::-1]
def my_reverse(s): assert 'strrev' in app.jinja_env.filters.keys()
return s[::-1] assert app.jinja_env.filters['strrev'] == my_reverse
assert 'strrev' in app.jinja_env.filters.keys() assert app.jinja_env.filters['strrev']('abcd') == 'dcba'
assert app.jinja_env.filters['strrev'] == my_reverse
assert app.jinja_env.filters['strrev']('abcd') == 'dcba' def test_add_template_filter_with_name():
app = flask.Flask(__name__)
def test_add_template_filter_with_name(self): def my_reverse(s):
app = flask.Flask(__name__) return s[::-1]
def my_reverse(s): app.add_template_filter(my_reverse, 'strrev')
return s[::-1] assert 'strrev' in app.jinja_env.filters.keys()
app.add_template_filter(my_reverse, 'strrev') assert app.jinja_env.filters['strrev'] == my_reverse
assert 'strrev' in app.jinja_env.filters.keys() assert app.jinja_env.filters['strrev']('abcd') == 'dcba'
assert app.jinja_env.filters['strrev'] == my_reverse
assert app.jinja_env.filters['strrev']('abcd') == 'dcba' def test_template_filter_with_template():
app = flask.Flask(__name__)
def test_template_filter_with_template(self): @app.template_filter()
app = flask.Flask(__name__) def super_reverse(s):
@app.template_filter() return s[::-1]
def super_reverse(s): @app.route('/')
return s[::-1] def index():
@app.route('/') return flask.render_template('template_filter.html', value='abcd')
def index(): rv = app.test_client().get('/')
return flask.render_template('template_filter.html', value='abcd') assert rv.data == b'dcba'
rv = app.test_client().get('/')
assert rv.data == b'dcba' def test_add_template_filter_with_template():
app = flask.Flask(__name__)
def test_add_template_filter_with_template(self): def super_reverse(s):
app = flask.Flask(__name__) return s[::-1]
def super_reverse(s): app.add_template_filter(super_reverse)
return s[::-1] @app.route('/')
app.add_template_filter(super_reverse) def index():
@app.route('/') return flask.render_template('template_filter.html', value='abcd')
def index(): rv = app.test_client().get('/')
return flask.render_template('template_filter.html', value='abcd') assert rv.data == b'dcba'
rv = app.test_client().get('/')
assert rv.data == b'dcba' def test_template_filter_with_name_and_template():
app = flask.Flask(__name__)
def test_template_filter_with_name_and_template(self): @app.template_filter('super_reverse')
app = flask.Flask(__name__) def my_reverse(s):
@app.template_filter('super_reverse') return s[::-1]
def my_reverse(s): @app.route('/')
return s[::-1] def index():
@app.route('/') return flask.render_template('template_filter.html', value='abcd')
def index(): rv = app.test_client().get('/')
return flask.render_template('template_filter.html', value='abcd') assert rv.data == b'dcba'
rv = app.test_client().get('/')
assert rv.data == b'dcba' def test_add_template_filter_with_name_and_template():
app = flask.Flask(__name__)
def test_add_template_filter_with_name_and_template(self): def my_reverse(s):
app = flask.Flask(__name__) return s[::-1]
def my_reverse(s): app.add_template_filter(my_reverse, 'super_reverse')
return s[::-1] @app.route('/')
app.add_template_filter(my_reverse, 'super_reverse') def index():
@app.route('/') return flask.render_template('template_filter.html', value='abcd')
def index(): rv = app.test_client().get('/')
return flask.render_template('template_filter.html', value='abcd') assert rv.data == b'dcba'
rv = app.test_client().get('/')
assert rv.data == b'dcba' def test_template_test():
app = flask.Flask(__name__)
def test_template_test(self): @app.template_test()
app = flask.Flask(__name__) def boolean(value):
@app.template_test() return isinstance(value, bool)
def boolean(value): assert 'boolean' in app.jinja_env.tests.keys()
return isinstance(value, bool) assert app.jinja_env.tests['boolean'] == boolean
assert 'boolean' in app.jinja_env.tests.keys() assert app.jinja_env.tests['boolean'](False)
assert app.jinja_env.tests['boolean'] == boolean
assert app.jinja_env.tests['boolean'](False) def test_add_template_test():
app = flask.Flask(__name__)
def test_add_template_test(self): def boolean(value):
app = flask.Flask(__name__) return isinstance(value, bool)
def boolean(value): app.add_template_test(boolean)
return isinstance(value, bool) assert 'boolean' in app.jinja_env.tests.keys()
app.add_template_test(boolean) assert app.jinja_env.tests['boolean'] == boolean
assert 'boolean' in app.jinja_env.tests.keys() assert app.jinja_env.tests['boolean'](False)
assert app.jinja_env.tests['boolean'] == boolean
assert app.jinja_env.tests['boolean'](False) def test_template_test_with_name():
app = flask.Flask(__name__)
def test_template_test_with_name(self): @app.template_test('boolean')
app = flask.Flask(__name__) def is_boolean(value):
@app.template_test('boolean') return isinstance(value, bool)
def is_boolean(value): assert 'boolean' in app.jinja_env.tests.keys()
return isinstance(value, bool) assert app.jinja_env.tests['boolean'] == is_boolean
assert 'boolean' in app.jinja_env.tests.keys() assert app.jinja_env.tests['boolean'](False)
assert app.jinja_env.tests['boolean'] == is_boolean
assert app.jinja_env.tests['boolean'](False) def test_add_template_test_with_name():
app = flask.Flask(__name__)
def test_add_template_test_with_name(self): def is_boolean(value):
app = flask.Flask(__name__) return isinstance(value, bool)
def is_boolean(value): app.add_template_test(is_boolean, 'boolean')
return isinstance(value, bool) assert 'boolean' in app.jinja_env.tests.keys()
app.add_template_test(is_boolean, 'boolean') assert app.jinja_env.tests['boolean'] == is_boolean
assert 'boolean' in app.jinja_env.tests.keys() assert app.jinja_env.tests['boolean'](False)
assert app.jinja_env.tests['boolean'] == is_boolean
assert app.jinja_env.tests['boolean'](False) def test_template_test_with_template():
app = flask.Flask(__name__)
def test_template_test_with_template(self): @app.template_test()
app = flask.Flask(__name__) def boolean(value):
@app.template_test() return isinstance(value, bool)
def boolean(value): @app.route('/')
return isinstance(value, bool) def index():
@app.route('/') return flask.render_template('template_test.html', value=False)
def index(): rv = app.test_client().get('/')
return flask.render_template('template_test.html', value=False) assert b'Success!' in rv.data
rv = app.test_client().get('/')
assert b'Success!' in rv.data def test_add_template_test_with_template():
app = flask.Flask(__name__)
def test_add_template_test_with_template(self): def boolean(value):
app = flask.Flask(__name__) return isinstance(value, bool)
def boolean(value): app.add_template_test(boolean)
return isinstance(value, bool) @app.route('/')
app.add_template_test(boolean) def index():
@app.route('/') return flask.render_template('template_test.html', value=False)
def index(): rv = app.test_client().get('/')
return flask.render_template('template_test.html', value=False) assert b'Success!' in rv.data
rv = app.test_client().get('/')
assert b'Success!' in rv.data def test_template_test_with_name_and_template():
app = flask.Flask(__name__)
def test_template_test_with_name_and_template(self): @app.template_test('boolean')
app = flask.Flask(__name__) def is_boolean(value):
@app.template_test('boolean') return isinstance(value, bool)
def is_boolean(value): @app.route('/')
return isinstance(value, bool) def index():
@app.route('/') return flask.render_template('template_test.html', value=False)
def index(): rv = app.test_client().get('/')
return flask.render_template('template_test.html', value=False) assert b'Success!' in rv.data
rv = app.test_client().get('/')
assert b'Success!' in rv.data def test_add_template_test_with_name_and_template():
app = flask.Flask(__name__)
def test_add_template_test_with_name_and_template(self): def is_boolean(value):
app = flask.Flask(__name__) return isinstance(value, bool)
def is_boolean(value): app.add_template_test(is_boolean, 'boolean')
return isinstance(value, bool) @app.route('/')
app.add_template_test(is_boolean, 'boolean') def index():
@app.route('/') return flask.render_template('template_test.html', value=False)
def index(): rv = app.test_client().get('/')
return flask.render_template('template_test.html', value=False) assert b'Success!' in rv.data
rv = app.test_client().get('/')
assert b'Success!' in rv.data def test_add_template_global():
app = flask.Flask(__name__)
def test_add_template_global(self): @app.template_global()
app = flask.Flask(__name__) def get_stuff():
@app.template_global() return 42
def get_stuff(): assert 'get_stuff' in app.jinja_env.globals.keys()
return 42 assert app.jinja_env.globals['get_stuff'] == get_stuff
assert 'get_stuff' in app.jinja_env.globals.keys() assert app.jinja_env.globals['get_stuff'](), 42
assert app.jinja_env.globals['get_stuff'] == get_stuff with app.app_context():
assert app.jinja_env.globals['get_stuff'](), 42 rv = flask.render_template_string('{{ get_stuff() }}')
with app.app_context(): assert rv == '42'
rv = flask.render_template_string('{{ get_stuff() }}')
assert rv == '42' def test_custom_template_loader():
class MyFlask(flask.Flask):
def test_custom_template_loader(self): def create_global_jinja_loader(self):
class MyFlask(flask.Flask): from jinja2 import DictLoader
def create_global_jinja_loader(self): return DictLoader({'index.html': 'Hello Custom World!'})
from jinja2 import DictLoader app = MyFlask(__name__)
return DictLoader({'index.html': 'Hello Custom World!'}) @app.route('/')
app = MyFlask(__name__) def index():
@app.route('/') return flask.render_template('index.html')
def index(): c = app.test_client()
return flask.render_template('index.html') rv = c.get('/')
c = app.test_client() assert rv.data == b'Hello Custom World!'
rv = c.get('/')
assert rv.data == b'Hello Custom World!' def test_iterable_loader():
app = flask.Flask(__name__)
def test_iterable_loader(self): @app.context_processor
app = flask.Flask(__name__) def context_processor():
@app.context_processor return {'whiskey': 'Jameson'}
def context_processor(): @app.route('/')
return {'whiskey': 'Jameson'} def index():
@app.route('/') return flask.render_template(
def index(): ['no_template.xml', # should skip this one
return flask.render_template( 'simple_template.html', # should render this
['no_template.xml', # should skip this one 'context_template.html'],
'simple_template.html', # should render this value=23)
'context_template.html'],
value=23) rv = app.test_client().get('/')
assert rv.data == b'<h1>Jameson</h1>'
rv = app.test_client().get('/')
assert rv.data == b'<h1>Jameson</h1>' def test_templates_auto_reload():
app = flask.Flask(__name__)
def test_templates_auto_reload(self): assert app.config['TEMPLATES_AUTO_RELOAD']
app = flask.Flask(__name__) assert app.jinja_env.auto_reload
assert app.config['TEMPLATES_AUTO_RELOAD'] app = flask.Flask(__name__)
assert app.jinja_env.auto_reload app.config['TEMPLATES_AUTO_RELOAD'] = False
app = flask.Flask(__name__) assert not app.jinja_env.auto_reload
app.config['TEMPLATES_AUTO_RELOAD'] = False
assert not app.jinja_env.auto_reload def test_template_loader_debugging():
from blueprintapp import app
def test_template_loader_debugging(self):
from blueprintapp import app called = []
class _TestHandler(logging.Handler):
called = [] def handle(x, record):
class _TestHandler(logging.Handler): called.append(True)
def handle(x, record): text = str(record.msg)
called.append(True) assert '1: trying loader of application "blueprintapp"' in text
text = str(record.msg) assert ('2: trying loader of blueprint "admin" '
assert '1: trying loader of application "blueprintapp"' in text '(blueprintapp.apps.admin)') in text
assert ('2: trying loader of blueprint "admin" ' assert ('trying loader of blueprint "frontend" '
'(blueprintapp.apps.admin)') in text '(blueprintapp.apps.frontend)') in text
assert ('trying loader of blueprint "frontend" ' assert 'Error: the template could not be found' in text
'(blueprintapp.apps.frontend)') in text assert ('looked up from an endpoint that belongs to '
assert 'Error: the template could not be found' in text 'the blueprint "frontend"') in text
assert ('looked up from an endpoint that belongs to ' assert 'See http://flask.pocoo.org/docs/blueprints/#templates' in text
'the blueprint "frontend"') in text
assert 'See http://flask.pocoo.org/docs/blueprints/#templates' in text with app.test_client() as c:
try:
with app.test_client() as c: old_load_setting = app.config['EXPLAIN_TEMPLATE_LOADING']
try: old_handlers = app.logger.handlers[:]
old_load_setting = app.config['EXPLAIN_TEMPLATE_LOADING'] app.logger.handlers = [_TestHandler()]
old_handlers = app.logger.handlers[:] app.config['EXPLAIN_TEMPLATE_LOADING'] = True
app.logger.handlers = [_TestHandler()]
app.config['EXPLAIN_TEMPLATE_LOADING'] = True with pytest.raises(TemplateNotFound) as excinfo:
c.get('/missing')
try:
c.get('/missing') assert 'missing_template.html' in str(excinfo.value)
except TemplateNotFound as e: finally:
assert 'missing_template.html' in str(e) app.logger.handlers[:] = old_handlers
else: app.config['EXPLAIN_TEMPLATE_LOADING'] = old_load_setting
self.fail('Expected template not found exception.')
finally: assert len(called) == 1
app.logger.handlers[:] = old_handlers
app.config['EXPLAIN_TEMPLATE_LOADING'] = old_load_setting
assert len(called) == 1
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestTemplating))
return suite

Loading…
Cancel
Save