mirror of
https://github.com/onionshare/onionshare.git
synced 2025-06-05 21:39:29 -04:00
bundling required python dependencies, to make it easier on Tails users
This commit is contained in:
parent
18fd65acd7
commit
8ffa569094
224 changed files with 52588 additions and 0 deletions
246
lib/flask/testsuite/__init__.py
Normal file
246
lib/flask/testsuite/__init__.py
Normal file
|
@ -0,0 +1,246 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
flask.testsuite
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
Tests Flask itself. The majority of Flask is already tested
|
||||
as part of Werkzeug.
|
||||
|
||||
:copyright: (c) 2011 by Armin Ronacher.
|
||||
:license: BSD, see LICENSE for more details.
|
||||
"""
|
||||
|
||||
from __future__ import print_function
|
||||
|
||||
import os
|
||||
import sys
|
||||
import flask
|
||||
import warnings
|
||||
import unittest
|
||||
from functools import update_wrapper
|
||||
from contextlib import contextmanager
|
||||
from werkzeug.utils import import_string, find_modules
|
||||
from flask._compat import reraise, StringIO
|
||||
|
||||
|
||||
def add_to_path(path):
|
||||
"""Adds an entry to sys.path if it's not already there. This does
|
||||
not append it but moves it to the front so that we can be sure it
|
||||
is loaded.
|
||||
"""
|
||||
if not os.path.isdir(path):
|
||||
raise RuntimeError('Tried to add nonexisting path')
|
||||
|
||||
def _samefile(x, y):
|
||||
if x == y:
|
||||
return True
|
||||
try:
|
||||
return os.path.samefile(x, y)
|
||||
except (IOError, OSError, AttributeError):
|
||||
# Windows has no samefile
|
||||
return False
|
||||
sys.path[:] = [x for x in sys.path if not _samefile(path, x)]
|
||||
sys.path.insert(0, path)
|
||||
|
||||
|
||||
def iter_suites():
|
||||
"""Yields all testsuites."""
|
||||
for module in find_modules(__name__):
|
||||
mod = import_string(module)
|
||||
if hasattr(mod, 'suite'):
|
||||
yield mod.suite()
|
||||
|
||||
|
||||
def find_all_tests(suite):
|
||||
"""Yields all the tests and their names from a given suite."""
|
||||
suites = [suite]
|
||||
while suites:
|
||||
s = suites.pop()
|
||||
try:
|
||||
suites.extend(s)
|
||||
except TypeError:
|
||||
yield s, '%s.%s.%s' % (
|
||||
s.__class__.__module__,
|
||||
s.__class__.__name__,
|
||||
s._testMethodName
|
||||
)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def catch_warnings():
|
||||
"""Catch warnings in a with block in a list"""
|
||||
# make sure deprecation warnings are active in tests
|
||||
warnings.simplefilter('default', category=DeprecationWarning)
|
||||
|
||||
filters = warnings.filters
|
||||
warnings.filters = filters[:]
|
||||
old_showwarning = warnings.showwarning
|
||||
log = []
|
||||
def showwarning(message, category, filename, lineno, file=None, line=None):
|
||||
log.append(locals())
|
||||
try:
|
||||
warnings.showwarning = showwarning
|
||||
yield log
|
||||
finally:
|
||||
warnings.filters = filters
|
||||
warnings.showwarning = old_showwarning
|
||||
|
||||
|
||||
@contextmanager
|
||||
def catch_stderr():
|
||||
"""Catch stderr in a StringIO"""
|
||||
old_stderr = sys.stderr
|
||||
sys.stderr = rv = StringIO()
|
||||
try:
|
||||
yield rv
|
||||
finally:
|
||||
sys.stderr = old_stderr
|
||||
|
||||
|
||||
def emits_module_deprecation_warning(f):
|
||||
def new_f(self, *args, **kwargs):
|
||||
with catch_warnings() as log:
|
||||
f(self, *args, **kwargs)
|
||||
self.assert_true(log, 'expected deprecation warning')
|
||||
for entry in log:
|
||||
self.assert_in('Modules are deprecated', str(entry['message']))
|
||||
return update_wrapper(new_f, f)
|
||||
|
||||
|
||||
class FlaskTestCase(unittest.TestCase):
|
||||
"""Baseclass for all the tests that Flask uses. Use these methods
|
||||
for testing instead of the camelcased ones in the baseclass for
|
||||
consistency.
|
||||
"""
|
||||
|
||||
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())
|
||||
self.assert_equal(leaks, [])
|
||||
|
||||
def setup(self):
|
||||
pass
|
||||
|
||||
def teardown(self):
|
||||
pass
|
||||
|
||||
def setUp(self):
|
||||
self.setup()
|
||||
|
||||
def tearDown(self):
|
||||
unittest.TestCase.tearDown(self)
|
||||
self.ensure_clean_request_context()
|
||||
self.teardown()
|
||||
|
||||
def assert_equal(self, x, y):
|
||||
return self.assertEqual(x, y)
|
||||
|
||||
def assert_raises(self, exc_type, callable=None, *args, **kwargs):
|
||||
catcher = _ExceptionCatcher(self, exc_type)
|
||||
if callable is None:
|
||||
return catcher
|
||||
with catcher:
|
||||
callable(*args, **kwargs)
|
||||
|
||||
def assert_true(self, x, msg=None):
|
||||
self.assertTrue(x, msg)
|
||||
|
||||
def assert_false(self, x, msg=None):
|
||||
self.assertFalse(x, msg)
|
||||
|
||||
def assert_in(self, x, y):
|
||||
self.assertIn(x, y)
|
||||
|
||||
def assert_not_in(self, x, y):
|
||||
self.assertNotIn(x, y)
|
||||
|
||||
if sys.version_info[:2] == (2, 6):
|
||||
def assertIn(self, x, y):
|
||||
assert x in y, "%r unexpectedly not in %r" % (x, y)
|
||||
|
||||
def assertNotIn(self, x, y):
|
||||
assert x not in y, "%r unexpectedly in %r" % (x, y)
|
||||
|
||||
|
||||
class _ExceptionCatcher(object):
|
||||
|
||||
def __init__(self, test_case, exc_type):
|
||||
self.test_case = test_case
|
||||
self.exc_type = exc_type
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_value, tb):
|
||||
exception_name = self.exc_type.__name__
|
||||
if exc_type is None:
|
||||
self.test_case.fail('Expected exception of type %r' %
|
||||
exception_name)
|
||||
elif not issubclass(exc_type, self.exc_type):
|
||||
reraise(exc_type, exc_value, tb)
|
||||
return True
|
||||
|
||||
|
||||
class BetterLoader(unittest.TestLoader):
|
||||
"""A nicer loader that solves two problems. First of all we are setting
|
||||
up tests from different sources and we're doing this programmatically
|
||||
which breaks the default loading logic so this is required anyways.
|
||||
Secondly this loader has a nicer interpolation for test names than the
|
||||
default one so you can just do ``run-tests.py ViewTestCase`` and it
|
||||
will work.
|
||||
"""
|
||||
|
||||
def getRootSuite(self):
|
||||
return suite()
|
||||
|
||||
def loadTestsFromName(self, name, module=None):
|
||||
root = self.getRootSuite()
|
||||
if name == 'suite':
|
||||
return root
|
||||
|
||||
all_tests = []
|
||||
for testcase, testname in find_all_tests(root):
|
||||
if testname == name or \
|
||||
testname.endswith('.' + name) or \
|
||||
('.' + name + '.') in testname or \
|
||||
testname.startswith(name + '.'):
|
||||
all_tests.append(testcase)
|
||||
|
||||
if not all_tests:
|
||||
raise LookupError('could not find test case for "%s"' % name)
|
||||
|
||||
if len(all_tests) == 1:
|
||||
return all_tests[0]
|
||||
rv = unittest.TestSuite()
|
||||
for test in all_tests:
|
||||
rv.addTest(test)
|
||||
return rv
|
||||
|
||||
|
||||
def setup_path():
|
||||
add_to_path(os.path.abspath(os.path.join(
|
||||
os.path.dirname(__file__), 'test_apps')))
|
||||
|
||||
|
||||
def suite():
|
||||
"""A testsuite that has all the Flask tests. You can use this
|
||||
function to integrate the Flask tests into your own testsuite
|
||||
in case you want to test that monkeypatches to Flask do not
|
||||
break it.
|
||||
"""
|
||||
setup_path()
|
||||
suite = unittest.TestSuite()
|
||||
for other_suite in iter_suites():
|
||||
suite.addTest(other_suite)
|
||||
return suite
|
||||
|
||||
|
||||
def main():
|
||||
"""Runs the testsuite as command line application."""
|
||||
try:
|
||||
unittest.main(testLoader=BetterLoader(), defaultTest='suite')
|
||||
except Exception as e:
|
||||
print('Error: %s' % e)
|
101
lib/flask/testsuite/appctx.py
Normal file
101
lib/flask/testsuite/appctx.py
Normal file
|
@ -0,0 +1,101 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
flask.testsuite.appctx
|
||||
~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Tests the application context.
|
||||
|
||||
:copyright: (c) 2012 by Armin Ronacher.
|
||||
:license: BSD, see LICENSE for more details.
|
||||
"""
|
||||
|
||||
import flask
|
||||
import unittest
|
||||
from flask.testsuite import FlaskTestCase
|
||||
|
||||
|
||||
class AppContextTestCase(FlaskTestCase):
|
||||
|
||||
def test_basic_url_generation(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.config['SERVER_NAME'] = 'localhost'
|
||||
app.config['PREFERRED_URL_SCHEME'] = 'https'
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
pass
|
||||
|
||||
with app.app_context():
|
||||
rv = flask.url_for('index')
|
||||
self.assert_equal(rv, 'https://localhost/')
|
||||
|
||||
def test_url_generation_requires_server_name(self):
|
||||
app = flask.Flask(__name__)
|
||||
with app.app_context():
|
||||
with self.assert_raises(RuntimeError):
|
||||
flask.url_for('index')
|
||||
|
||||
def test_url_generation_without_context_fails(self):
|
||||
with self.assert_raises(RuntimeError):
|
||||
flask.url_for('index')
|
||||
|
||||
def test_request_context_means_app_context(self):
|
||||
app = flask.Flask(__name__)
|
||||
with app.test_request_context():
|
||||
self.assert_equal(flask.current_app._get_current_object(), app)
|
||||
self.assert_equal(flask._app_ctx_stack.top, None)
|
||||
|
||||
def test_app_context_provides_current_app(self):
|
||||
app = flask.Flask(__name__)
|
||||
with app.app_context():
|
||||
self.assert_equal(flask.current_app._get_current_object(), app)
|
||||
self.assert_equal(flask._app_ctx_stack.top, None)
|
||||
|
||||
def test_app_tearing_down(self):
|
||||
cleanup_stuff = []
|
||||
app = flask.Flask(__name__)
|
||||
@app.teardown_appcontext
|
||||
def cleanup(exception):
|
||||
cleanup_stuff.append(exception)
|
||||
|
||||
with app.app_context():
|
||||
pass
|
||||
|
||||
self.assert_equal(cleanup_stuff, [None])
|
||||
|
||||
def test_custom_app_ctx_globals_class(self):
|
||||
class CustomRequestGlobals(object):
|
||||
def __init__(self):
|
||||
self.spam = 'eggs'
|
||||
app = flask.Flask(__name__)
|
||||
app.app_ctx_globals_class = CustomRequestGlobals
|
||||
with app.app_context():
|
||||
self.assert_equal(
|
||||
flask.render_template_string('{{ g.spam }}'), 'eggs')
|
||||
|
||||
def test_context_refcounts(self):
|
||||
called = []
|
||||
app = flask.Flask(__name__)
|
||||
@app.teardown_request
|
||||
def teardown_req(error=None):
|
||||
called.append('request')
|
||||
@app.teardown_appcontext
|
||||
def teardown_app(error=None):
|
||||
called.append('app')
|
||||
@app.route('/')
|
||||
def index():
|
||||
with flask._app_ctx_stack.top:
|
||||
with flask._request_ctx_stack.top:
|
||||
pass
|
||||
self.assert_true(flask._request_ctx_stack.top.request.environ
|
||||
['werkzeug.request'] is not None)
|
||||
return u''
|
||||
c = app.test_client()
|
||||
c.get('/')
|
||||
self.assertEqual(called, ['request', 'app'])
|
||||
|
||||
|
||||
def suite():
|
||||
suite = unittest.TestSuite()
|
||||
suite.addTest(unittest.makeSuite(AppContextTestCase))
|
||||
return suite
|
1254
lib/flask/testsuite/basic.py
Normal file
1254
lib/flask/testsuite/basic.py
Normal file
File diff suppressed because it is too large
Load diff
790
lib/flask/testsuite/blueprints.py
Normal file
790
lib/flask/testsuite/blueprints.py
Normal file
|
@ -0,0 +1,790 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
flask.testsuite.blueprints
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Blueprints (and currently modules)
|
||||
|
||||
:copyright: (c) 2011 by Armin Ronacher.
|
||||
:license: BSD, see LICENSE for more details.
|
||||
"""
|
||||
|
||||
import flask
|
||||
import unittest
|
||||
import warnings
|
||||
from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning
|
||||
from flask._compat import text_type
|
||||
from werkzeug.exceptions import NotFound
|
||||
from werkzeug.http import parse_cache_control_header
|
||||
from jinja2 import TemplateNotFound
|
||||
|
||||
|
||||
# import moduleapp here because it uses deprecated features and we don't
|
||||
# want to see the warnings
|
||||
warnings.simplefilter('ignore', DeprecationWarning)
|
||||
from moduleapp import app as moduleapp
|
||||
warnings.simplefilter('default', DeprecationWarning)
|
||||
|
||||
|
||||
class ModuleTestCase(FlaskTestCase):
|
||||
|
||||
@emits_module_deprecation_warning
|
||||
def test_basic_module(self):
|
||||
app = flask.Flask(__name__)
|
||||
admin = flask.Module(__name__, 'admin', url_prefix='/admin')
|
||||
@admin.route('/')
|
||||
def admin_index():
|
||||
return 'admin index'
|
||||
@admin.route('/login')
|
||||
def admin_login():
|
||||
return 'admin login'
|
||||
@admin.route('/logout')
|
||||
def admin_logout():
|
||||
return 'admin logout'
|
||||
@app.route('/')
|
||||
def index():
|
||||
return 'the index'
|
||||
app.register_module(admin)
|
||||
c = app.test_client()
|
||||
self.assert_equal(c.get('/').data, b'the index')
|
||||
self.assert_equal(c.get('/admin/').data, b'admin index')
|
||||
self.assert_equal(c.get('/admin/login').data, b'admin login')
|
||||
self.assert_equal(c.get('/admin/logout').data, b'admin logout')
|
||||
|
||||
@emits_module_deprecation_warning
|
||||
def test_default_endpoint_name(self):
|
||||
app = flask.Flask(__name__)
|
||||
mod = flask.Module(__name__, 'frontend')
|
||||
def index():
|
||||
return 'Awesome'
|
||||
mod.add_url_rule('/', view_func=index)
|
||||
app.register_module(mod)
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_equal(rv.data, b'Awesome')
|
||||
with app.test_request_context():
|
||||
self.assert_equal(flask.url_for('frontend.index'), '/')
|
||||
|
||||
@emits_module_deprecation_warning
|
||||
def test_request_processing(self):
|
||||
catched = []
|
||||
app = flask.Flask(__name__)
|
||||
admin = flask.Module(__name__, 'admin', url_prefix='/admin')
|
||||
@admin.before_request
|
||||
def before_admin_request():
|
||||
catched.append('before-admin')
|
||||
@admin.after_request
|
||||
def after_admin_request(response):
|
||||
catched.append('after-admin')
|
||||
return response
|
||||
@admin.route('/')
|
||||
def admin_index():
|
||||
return 'the admin'
|
||||
@app.before_request
|
||||
def before_request():
|
||||
catched.append('before-app')
|
||||
@app.after_request
|
||||
def after_request(response):
|
||||
catched.append('after-app')
|
||||
return response
|
||||
@app.route('/')
|
||||
def index():
|
||||
return 'the index'
|
||||
app.register_module(admin)
|
||||
c = app.test_client()
|
||||
|
||||
self.assert_equal(c.get('/').data, b'the index')
|
||||
self.assert_equal(catched, ['before-app', 'after-app'])
|
||||
del catched[:]
|
||||
|
||||
self.assert_equal(c.get('/admin/').data, b'the admin')
|
||||
self.assert_equal(catched, ['before-app', 'before-admin',
|
||||
'after-admin', 'after-app'])
|
||||
|
||||
@emits_module_deprecation_warning
|
||||
def test_context_processors(self):
|
||||
app = flask.Flask(__name__)
|
||||
admin = flask.Module(__name__, 'admin', url_prefix='/admin')
|
||||
@app.context_processor
|
||||
def inject_all_regular():
|
||||
return {'a': 1}
|
||||
@admin.context_processor
|
||||
def inject_admin():
|
||||
return {'b': 2}
|
||||
@admin.app_context_processor
|
||||
def inject_all_module():
|
||||
return {'c': 3}
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template_string('{{ a }}{{ b }}{{ c }}')
|
||||
@admin.route('/')
|
||||
def admin_index():
|
||||
return flask.render_template_string('{{ a }}{{ b }}{{ c }}')
|
||||
app.register_module(admin)
|
||||
c = app.test_client()
|
||||
self.assert_equal(c.get('/').data, b'13')
|
||||
self.assert_equal(c.get('/admin/').data, b'123')
|
||||
|
||||
@emits_module_deprecation_warning
|
||||
def test_late_binding(self):
|
||||
app = flask.Flask(__name__)
|
||||
admin = flask.Module(__name__, 'admin')
|
||||
@admin.route('/')
|
||||
def index():
|
||||
return '42'
|
||||
app.register_module(admin, url_prefix='/admin')
|
||||
self.assert_equal(app.test_client().get('/admin/').data, b'42')
|
||||
|
||||
@emits_module_deprecation_warning
|
||||
def test_error_handling(self):
|
||||
app = flask.Flask(__name__)
|
||||
admin = flask.Module(__name__, 'admin')
|
||||
@admin.app_errorhandler(404)
|
||||
def not_found(e):
|
||||
return 'not found', 404
|
||||
@admin.app_errorhandler(500)
|
||||
def internal_server_error(e):
|
||||
return 'internal server error', 500
|
||||
@admin.route('/')
|
||||
def index():
|
||||
flask.abort(404)
|
||||
@admin.route('/error')
|
||||
def error():
|
||||
1 // 0
|
||||
app.register_module(admin)
|
||||
c = app.test_client()
|
||||
rv = c.get('/')
|
||||
self.assert_equal(rv.status_code, 404)
|
||||
self.assert_equal(rv.data, b'not found')
|
||||
rv = c.get('/error')
|
||||
self.assert_equal(rv.status_code, 500)
|
||||
self.assert_equal(b'internal server error', rv.data)
|
||||
|
||||
def test_templates_and_static(self):
|
||||
app = moduleapp
|
||||
app.testing = True
|
||||
c = app.test_client()
|
||||
|
||||
rv = c.get('/')
|
||||
self.assert_equal(rv.data, b'Hello from the Frontend')
|
||||
rv = c.get('/admin/')
|
||||
self.assert_equal(rv.data, b'Hello from the Admin')
|
||||
rv = c.get('/admin/index2')
|
||||
self.assert_equal(rv.data, b'Hello from the Admin')
|
||||
rv = c.get('/admin/static/test.txt')
|
||||
self.assert_equal(rv.data.strip(), b'Admin File')
|
||||
rv.close()
|
||||
rv = c.get('/admin/static/css/test.css')
|
||||
self.assert_equal(rv.data.strip(), b'/* nested file */')
|
||||
rv.close()
|
||||
|
||||
with app.test_request_context():
|
||||
self.assert_equal(flask.url_for('admin.static', filename='test.txt'),
|
||||
'/admin/static/test.txt')
|
||||
|
||||
with app.test_request_context():
|
||||
try:
|
||||
flask.render_template('missing.html')
|
||||
except TemplateNotFound as e:
|
||||
self.assert_equal(e.name, 'missing.html')
|
||||
else:
|
||||
self.assert_true(0, 'expected exception')
|
||||
|
||||
with flask.Flask(__name__).test_request_context():
|
||||
self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested')
|
||||
|
||||
def test_safe_access(self):
|
||||
app = moduleapp
|
||||
|
||||
with app.test_request_context():
|
||||
f = app.view_functions['admin.static']
|
||||
|
||||
try:
|
||||
f('/etc/passwd')
|
||||
except NotFound:
|
||||
pass
|
||||
else:
|
||||
self.assert_true(0, 'expected exception')
|
||||
try:
|
||||
f('../__init__.py')
|
||||
except NotFound:
|
||||
pass
|
||||
else:
|
||||
self.assert_true(0, 'expected exception')
|
||||
|
||||
# testcase for a security issue that may exist on windows systems
|
||||
import os
|
||||
import ntpath
|
||||
old_path = os.path
|
||||
os.path = ntpath
|
||||
try:
|
||||
try:
|
||||
f('..\\__init__.py')
|
||||
except NotFound:
|
||||
pass
|
||||
else:
|
||||
self.assert_true(0, 'expected exception')
|
||||
finally:
|
||||
os.path = old_path
|
||||
|
||||
@emits_module_deprecation_warning
|
||||
def test_endpoint_decorator(self):
|
||||
from werkzeug.routing import Submount, Rule
|
||||
from flask import Module
|
||||
|
||||
app = flask.Flask(__name__)
|
||||
app.testing = True
|
||||
app.url_map.add(Submount('/foo', [
|
||||
Rule('/bar', endpoint='bar'),
|
||||
Rule('/', endpoint='index')
|
||||
]))
|
||||
module = Module(__name__, __name__)
|
||||
|
||||
@module.endpoint('bar')
|
||||
def bar():
|
||||
return 'bar'
|
||||
|
||||
@module.endpoint('index')
|
||||
def index():
|
||||
return 'index'
|
||||
|
||||
app.register_module(module)
|
||||
|
||||
c = app.test_client()
|
||||
self.assert_equal(c.get('/foo/').data, b'index')
|
||||
self.assert_equal(c.get('/foo/bar').data, b'bar')
|
||||
|
||||
|
||||
class BlueprintTestCase(FlaskTestCase):
|
||||
|
||||
def test_blueprint_specific_error_handling(self):
|
||||
frontend = flask.Blueprint('frontend', __name__)
|
||||
backend = flask.Blueprint('backend', __name__)
|
||||
sideend = flask.Blueprint('sideend', __name__)
|
||||
|
||||
@frontend.errorhandler(403)
|
||||
def frontend_forbidden(e):
|
||||
return 'frontend says no', 403
|
||||
|
||||
@frontend.route('/frontend-no')
|
||||
def frontend_no():
|
||||
flask.abort(403)
|
||||
|
||||
@backend.errorhandler(403)
|
||||
def backend_forbidden(e):
|
||||
return 'backend says no', 403
|
||||
|
||||
@backend.route('/backend-no')
|
||||
def backend_no():
|
||||
flask.abort(403)
|
||||
|
||||
@sideend.route('/what-is-a-sideend')
|
||||
def sideend_no():
|
||||
flask.abort(403)
|
||||
|
||||
app = flask.Flask(__name__)
|
||||
app.register_blueprint(frontend)
|
||||
app.register_blueprint(backend)
|
||||
app.register_blueprint(sideend)
|
||||
|
||||
@app.errorhandler(403)
|
||||
def app_forbidden(e):
|
||||
return 'application itself says no', 403
|
||||
|
||||
c = app.test_client()
|
||||
|
||||
self.assert_equal(c.get('/frontend-no').data, b'frontend says no')
|
||||
self.assert_equal(c.get('/backend-no').data, b'backend says no')
|
||||
self.assert_equal(c.get('/what-is-a-sideend').data, b'application itself says no')
|
||||
|
||||
def test_blueprint_url_definitions(self):
|
||||
bp = flask.Blueprint('test', __name__)
|
||||
|
||||
@bp.route('/foo', defaults={'baz': 42})
|
||||
def foo(bar, baz):
|
||||
return '%s/%d' % (bar, baz)
|
||||
|
||||
@bp.route('/bar')
|
||||
def bar(bar):
|
||||
return text_type(bar)
|
||||
|
||||
app = flask.Flask(__name__)
|
||||
app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23})
|
||||
app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19})
|
||||
|
||||
c = app.test_client()
|
||||
self.assert_equal(c.get('/1/foo').data, b'23/42')
|
||||
self.assert_equal(c.get('/2/foo').data, b'19/42')
|
||||
self.assert_equal(c.get('/1/bar').data, b'23')
|
||||
self.assert_equal(c.get('/2/bar').data, b'19')
|
||||
|
||||
def test_blueprint_url_processors(self):
|
||||
bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')
|
||||
|
||||
@bp.url_defaults
|
||||
def add_language_code(endpoint, values):
|
||||
values.setdefault('lang_code', flask.g.lang_code)
|
||||
|
||||
@bp.url_value_preprocessor
|
||||
def pull_lang_code(endpoint, values):
|
||||
flask.g.lang_code = values.pop('lang_code')
|
||||
|
||||
@bp.route('/')
|
||||
def index():
|
||||
return flask.url_for('.about')
|
||||
|
||||
@bp.route('/about')
|
||||
def about():
|
||||
return flask.url_for('.index')
|
||||
|
||||
app = flask.Flask(__name__)
|
||||
app.register_blueprint(bp)
|
||||
|
||||
c = app.test_client()
|
||||
|
||||
self.assert_equal(c.get('/de/').data, b'/de/about')
|
||||
self.assert_equal(c.get('/de/about').data, b'/de/')
|
||||
|
||||
def test_templates_and_static(self):
|
||||
from blueprintapp import app
|
||||
c = app.test_client()
|
||||
|
||||
rv = c.get('/')
|
||||
self.assert_equal(rv.data, b'Hello from the Frontend')
|
||||
rv = c.get('/admin/')
|
||||
self.assert_equal(rv.data, b'Hello from the Admin')
|
||||
rv = c.get('/admin/index2')
|
||||
self.assert_equal(rv.data, b'Hello from the Admin')
|
||||
rv = c.get('/admin/static/test.txt')
|
||||
self.assert_equal(rv.data.strip(), b'Admin File')
|
||||
rv.close()
|
||||
rv = c.get('/admin/static/css/test.css')
|
||||
self.assert_equal(rv.data.strip(), b'/* nested file */')
|
||||
rv.close()
|
||||
|
||||
# try/finally, in case other tests use this app for Blueprint tests.
|
||||
max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']
|
||||
try:
|
||||
expected_max_age = 3600
|
||||
if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == expected_max_age:
|
||||
expected_max_age = 7200
|
||||
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age
|
||||
rv = c.get('/admin/static/css/test.css')
|
||||
cc = parse_cache_control_header(rv.headers['Cache-Control'])
|
||||
self.assert_equal(cc.max_age, expected_max_age)
|
||||
rv.close()
|
||||
finally:
|
||||
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default
|
||||
|
||||
with app.test_request_context():
|
||||
self.assert_equal(flask.url_for('admin.static', filename='test.txt'),
|
||||
'/admin/static/test.txt')
|
||||
|
||||
with app.test_request_context():
|
||||
try:
|
||||
flask.render_template('missing.html')
|
||||
except TemplateNotFound as e:
|
||||
self.assert_equal(e.name, 'missing.html')
|
||||
else:
|
||||
self.assert_true(0, 'expected exception')
|
||||
|
||||
with flask.Flask(__name__).test_request_context():
|
||||
self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested')
|
||||
|
||||
def test_default_static_cache_timeout(self):
|
||||
app = flask.Flask(__name__)
|
||||
class MyBlueprint(flask.Blueprint):
|
||||
def get_send_file_max_age(self, filename):
|
||||
return 100
|
||||
|
||||
blueprint = MyBlueprint('blueprint', __name__, static_folder='static')
|
||||
app.register_blueprint(blueprint)
|
||||
|
||||
# try/finally, in case other tests use this app for Blueprint tests.
|
||||
max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']
|
||||
try:
|
||||
with app.test_request_context():
|
||||
unexpected_max_age = 3600
|
||||
if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == unexpected_max_age:
|
||||
unexpected_max_age = 7200
|
||||
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = unexpected_max_age
|
||||
rv = blueprint.send_static_file('index.html')
|
||||
cc = parse_cache_control_header(rv.headers['Cache-Control'])
|
||||
self.assert_equal(cc.max_age, 100)
|
||||
rv.close()
|
||||
finally:
|
||||
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default
|
||||
|
||||
def test_templates_list(self):
|
||||
from blueprintapp import app
|
||||
templates = sorted(app.jinja_env.list_templates())
|
||||
self.assert_equal(templates, ['admin/index.html',
|
||||
'frontend/index.html'])
|
||||
|
||||
def test_dotted_names(self):
|
||||
frontend = flask.Blueprint('myapp.frontend', __name__)
|
||||
backend = flask.Blueprint('myapp.backend', __name__)
|
||||
|
||||
@frontend.route('/fe')
|
||||
def frontend_index():
|
||||
return flask.url_for('myapp.backend.backend_index')
|
||||
|
||||
@frontend.route('/fe2')
|
||||
def frontend_page2():
|
||||
return flask.url_for('.frontend_index')
|
||||
|
||||
@backend.route('/be')
|
||||
def backend_index():
|
||||
return flask.url_for('myapp.frontend.frontend_index')
|
||||
|
||||
app = flask.Flask(__name__)
|
||||
app.register_blueprint(frontend)
|
||||
app.register_blueprint(backend)
|
||||
|
||||
c = app.test_client()
|
||||
self.assert_equal(c.get('/fe').data.strip(), b'/be')
|
||||
self.assert_equal(c.get('/fe2').data.strip(), b'/fe')
|
||||
self.assert_equal(c.get('/be').data.strip(), b'/fe')
|
||||
|
||||
def test_dotted_names_from_app(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.testing = True
|
||||
test = flask.Blueprint('test', __name__)
|
||||
|
||||
@app.route('/')
|
||||
def app_index():
|
||||
return flask.url_for('test.index')
|
||||
|
||||
@test.route('/test/')
|
||||
def index():
|
||||
return flask.url_for('app_index')
|
||||
|
||||
app.register_blueprint(test)
|
||||
|
||||
with app.test_client() as c:
|
||||
rv = c.get('/')
|
||||
self.assert_equal(rv.data, b'/test/')
|
||||
|
||||
def test_empty_url_defaults(self):
|
||||
bp = flask.Blueprint('bp', __name__)
|
||||
|
||||
@bp.route('/', defaults={'page': 1})
|
||||
@bp.route('/page/<int:page>')
|
||||
def something(page):
|
||||
return str(page)
|
||||
|
||||
app = flask.Flask(__name__)
|
||||
app.register_blueprint(bp)
|
||||
|
||||
c = app.test_client()
|
||||
self.assert_equal(c.get('/').data, b'1')
|
||||
self.assert_equal(c.get('/page/2').data, b'2')
|
||||
|
||||
def test_route_decorator_custom_endpoint(self):
|
||||
|
||||
bp = flask.Blueprint('bp', __name__)
|
||||
|
||||
@bp.route('/foo')
|
||||
def foo():
|
||||
return flask.request.endpoint
|
||||
|
||||
@bp.route('/bar', endpoint='bar')
|
||||
def foo_bar():
|
||||
return flask.request.endpoint
|
||||
|
||||
@bp.route('/bar/123', endpoint='123')
|
||||
def foo_bar_foo():
|
||||
return flask.request.endpoint
|
||||
|
||||
@bp.route('/bar/foo')
|
||||
def bar_foo():
|
||||
return flask.request.endpoint
|
||||
|
||||
app = flask.Flask(__name__)
|
||||
app.register_blueprint(bp, url_prefix='/py')
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.request.endpoint
|
||||
|
||||
c = app.test_client()
|
||||
self.assertEqual(c.get('/').data, b'index')
|
||||
self.assertEqual(c.get('/py/foo').data, b'bp.foo')
|
||||
self.assertEqual(c.get('/py/bar').data, b'bp.bar')
|
||||
self.assertEqual(c.get('/py/bar/123').data, b'bp.123')
|
||||
self.assertEqual(c.get('/py/bar/foo').data, b'bp.bar_foo')
|
||||
|
||||
def test_route_decorator_custom_endpoint_with_dots(self):
|
||||
bp = flask.Blueprint('bp', __name__)
|
||||
|
||||
@bp.route('/foo')
|
||||
def foo():
|
||||
return flask.request.endpoint
|
||||
|
||||
try:
|
||||
@bp.route('/bar', endpoint='bar.bar')
|
||||
def foo_bar():
|
||||
return flask.request.endpoint
|
||||
except AssertionError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('expected AssertionError not raised')
|
||||
|
||||
try:
|
||||
@bp.route('/bar/123', endpoint='bar.123')
|
||||
def foo_bar_foo():
|
||||
return flask.request.endpoint
|
||||
except AssertionError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('expected AssertionError not raised')
|
||||
|
||||
def foo_foo_foo():
|
||||
pass
|
||||
|
||||
self.assertRaises(
|
||||
AssertionError,
|
||||
lambda: bp.add_url_rule(
|
||||
'/bar/123', endpoint='bar.123', view_func=foo_foo_foo
|
||||
)
|
||||
)
|
||||
|
||||
self.assertRaises(
|
||||
AssertionError,
|
||||
bp.route('/bar/123', endpoint='bar.123'),
|
||||
lambda: None
|
||||
)
|
||||
|
||||
app = flask.Flask(__name__)
|
||||
app.register_blueprint(bp, url_prefix='/py')
|
||||
|
||||
c = app.test_client()
|
||||
self.assertEqual(c.get('/py/foo').data, b'bp.foo')
|
||||
# The rule's didn't actually made it through
|
||||
rv = c.get('/py/bar')
|
||||
assert rv.status_code == 404
|
||||
rv = c.get('/py/bar/123')
|
||||
assert rv.status_code == 404
|
||||
|
||||
def test_template_filter(self):
|
||||
bp = flask.Blueprint('bp', __name__)
|
||||
@bp.app_template_filter()
|
||||
def my_reverse(s):
|
||||
return s[::-1]
|
||||
app = flask.Flask(__name__)
|
||||
app.register_blueprint(bp, url_prefix='/py')
|
||||
self.assert_in('my_reverse', app.jinja_env.filters.keys())
|
||||
self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)
|
||||
self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba')
|
||||
|
||||
def test_add_template_filter(self):
|
||||
bp = flask.Blueprint('bp', __name__)
|
||||
def my_reverse(s):
|
||||
return s[::-1]
|
||||
bp.add_app_template_filter(my_reverse)
|
||||
app = flask.Flask(__name__)
|
||||
app.register_blueprint(bp, url_prefix='/py')
|
||||
self.assert_in('my_reverse', app.jinja_env.filters.keys())
|
||||
self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)
|
||||
self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba')
|
||||
|
||||
def test_template_filter_with_name(self):
|
||||
bp = flask.Blueprint('bp', __name__)
|
||||
@bp.app_template_filter('strrev')
|
||||
def my_reverse(s):
|
||||
return s[::-1]
|
||||
app = flask.Flask(__name__)
|
||||
app.register_blueprint(bp, url_prefix='/py')
|
||||
self.assert_in('strrev', app.jinja_env.filters.keys())
|
||||
self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)
|
||||
self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba')
|
||||
|
||||
def test_add_template_filter_with_name(self):
|
||||
bp = flask.Blueprint('bp', __name__)
|
||||
def my_reverse(s):
|
||||
return s[::-1]
|
||||
bp.add_app_template_filter(my_reverse, 'strrev')
|
||||
app = flask.Flask(__name__)
|
||||
app.register_blueprint(bp, url_prefix='/py')
|
||||
self.assert_in('strrev', app.jinja_env.filters.keys())
|
||||
self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)
|
||||
self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba')
|
||||
|
||||
def test_template_filter_with_template(self):
|
||||
bp = flask.Blueprint('bp', __name__)
|
||||
@bp.app_template_filter()
|
||||
def super_reverse(s):
|
||||
return s[::-1]
|
||||
app = flask.Flask(__name__)
|
||||
app.register_blueprint(bp, url_prefix='/py')
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template('template_filter.html', value='abcd')
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_equal(rv.data, b'dcba')
|
||||
|
||||
def test_template_filter_after_route_with_template(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template('template_filter.html', value='abcd')
|
||||
bp = flask.Blueprint('bp', __name__)
|
||||
@bp.app_template_filter()
|
||||
def super_reverse(s):
|
||||
return s[::-1]
|
||||
app.register_blueprint(bp, url_prefix='/py')
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_equal(rv.data, b'dcba')
|
||||
|
||||
def test_add_template_filter_with_template(self):
|
||||
bp = flask.Blueprint('bp', __name__)
|
||||
def super_reverse(s):
|
||||
return s[::-1]
|
||||
bp.add_app_template_filter(super_reverse)
|
||||
app = flask.Flask(__name__)
|
||||
app.register_blueprint(bp, url_prefix='/py')
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template('template_filter.html', value='abcd')
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_equal(rv.data, b'dcba')
|
||||
|
||||
def test_template_filter_with_name_and_template(self):
|
||||
bp = flask.Blueprint('bp', __name__)
|
||||
@bp.app_template_filter('super_reverse')
|
||||
def my_reverse(s):
|
||||
return s[::-1]
|
||||
app = flask.Flask(__name__)
|
||||
app.register_blueprint(bp, url_prefix='/py')
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template('template_filter.html', value='abcd')
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_equal(rv.data, b'dcba')
|
||||
|
||||
def test_add_template_filter_with_name_and_template(self):
|
||||
bp = flask.Blueprint('bp', __name__)
|
||||
def my_reverse(s):
|
||||
return s[::-1]
|
||||
bp.add_app_template_filter(my_reverse, 'super_reverse')
|
||||
app = flask.Flask(__name__)
|
||||
app.register_blueprint(bp, url_prefix='/py')
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template('template_filter.html', value='abcd')
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_equal(rv.data, b'dcba')
|
||||
|
||||
def test_template_test(self):
|
||||
bp = flask.Blueprint('bp', __name__)
|
||||
@bp.app_template_test()
|
||||
def is_boolean(value):
|
||||
return isinstance(value, bool)
|
||||
app = flask.Flask(__name__)
|
||||
app.register_blueprint(bp, url_prefix='/py')
|
||||
self.assert_in('is_boolean', app.jinja_env.tests.keys())
|
||||
self.assert_equal(app.jinja_env.tests['is_boolean'], is_boolean)
|
||||
self.assert_true(app.jinja_env.tests['is_boolean'](False))
|
||||
|
||||
def test_add_template_test(self):
|
||||
bp = flask.Blueprint('bp', __name__)
|
||||
def is_boolean(value):
|
||||
return isinstance(value, bool)
|
||||
bp.add_app_template_test(is_boolean)
|
||||
app = flask.Flask(__name__)
|
||||
app.register_blueprint(bp, url_prefix='/py')
|
||||
self.assert_in('is_boolean', app.jinja_env.tests.keys())
|
||||
self.assert_equal(app.jinja_env.tests['is_boolean'], is_boolean)
|
||||
self.assert_true(app.jinja_env.tests['is_boolean'](False))
|
||||
|
||||
def test_template_test_with_name(self):
|
||||
bp = flask.Blueprint('bp', __name__)
|
||||
@bp.app_template_test('boolean')
|
||||
def is_boolean(value):
|
||||
return isinstance(value, bool)
|
||||
app = flask.Flask(__name__)
|
||||
app.register_blueprint(bp, url_prefix='/py')
|
||||
self.assert_in('boolean', app.jinja_env.tests.keys())
|
||||
self.assert_equal(app.jinja_env.tests['boolean'], is_boolean)
|
||||
self.assert_true(app.jinja_env.tests['boolean'](False))
|
||||
|
||||
def test_add_template_test_with_name(self):
|
||||
bp = flask.Blueprint('bp', __name__)
|
||||
def is_boolean(value):
|
||||
return isinstance(value, bool)
|
||||
bp.add_app_template_test(is_boolean, 'boolean')
|
||||
app = flask.Flask(__name__)
|
||||
app.register_blueprint(bp, url_prefix='/py')
|
||||
self.assert_in('boolean', app.jinja_env.tests.keys())
|
||||
self.assert_equal(app.jinja_env.tests['boolean'], is_boolean)
|
||||
self.assert_true(app.jinja_env.tests['boolean'](False))
|
||||
|
||||
def test_template_test_with_template(self):
|
||||
bp = flask.Blueprint('bp', __name__)
|
||||
@bp.app_template_test()
|
||||
def boolean(value):
|
||||
return isinstance(value, bool)
|
||||
app = flask.Flask(__name__)
|
||||
app.register_blueprint(bp, url_prefix='/py')
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template('template_test.html', value=False)
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_in(b'Success!', rv.data)
|
||||
|
||||
def test_template_test_after_route_with_template(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template('template_test.html', value=False)
|
||||
bp = flask.Blueprint('bp', __name__)
|
||||
@bp.app_template_test()
|
||||
def boolean(value):
|
||||
return isinstance(value, bool)
|
||||
app.register_blueprint(bp, url_prefix='/py')
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_in(b'Success!', rv.data)
|
||||
|
||||
def test_add_template_test_with_template(self):
|
||||
bp = flask.Blueprint('bp', __name__)
|
||||
def boolean(value):
|
||||
return isinstance(value, bool)
|
||||
bp.add_app_template_test(boolean)
|
||||
app = flask.Flask(__name__)
|
||||
app.register_blueprint(bp, url_prefix='/py')
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template('template_test.html', value=False)
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_in(b'Success!', rv.data)
|
||||
|
||||
def test_template_test_with_name_and_template(self):
|
||||
bp = flask.Blueprint('bp', __name__)
|
||||
@bp.app_template_test('boolean')
|
||||
def is_boolean(value):
|
||||
return isinstance(value, bool)
|
||||
app = flask.Flask(__name__)
|
||||
app.register_blueprint(bp, url_prefix='/py')
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template('template_test.html', value=False)
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_in(b'Success!', rv.data)
|
||||
|
||||
def test_add_template_test_with_name_and_template(self):
|
||||
bp = flask.Blueprint('bp', __name__)
|
||||
def is_boolean(value):
|
||||
return isinstance(value, bool)
|
||||
bp.add_app_template_test(is_boolean, 'boolean')
|
||||
app = flask.Flask(__name__)
|
||||
app.register_blueprint(bp, url_prefix='/py')
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template('template_test.html', value=False)
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_in(b'Success!', rv.data)
|
||||
|
||||
def suite():
|
||||
suite = unittest.TestSuite()
|
||||
suite.addTest(unittest.makeSuite(BlueprintTestCase))
|
||||
suite.addTest(unittest.makeSuite(ModuleTestCase))
|
||||
return suite
|
299
lib/flask/testsuite/config.py
Normal file
299
lib/flask/testsuite/config.py
Normal file
|
@ -0,0 +1,299 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
flask.testsuite.config
|
||||
~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Configuration and instances.
|
||||
|
||||
:copyright: (c) 2011 by Armin Ronacher.
|
||||
:license: BSD, see LICENSE for more details.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import flask
|
||||
import pkgutil
|
||||
import unittest
|
||||
from contextlib import contextmanager
|
||||
from flask.testsuite import FlaskTestCase
|
||||
|
||||
|
||||
# config keys used for the ConfigTestCase
|
||||
TEST_KEY = 'foo'
|
||||
SECRET_KEY = 'devkey'
|
||||
|
||||
|
||||
class ConfigTestCase(FlaskTestCase):
|
||||
|
||||
def common_object_test(self, app):
|
||||
self.assert_equal(app.secret_key, 'devkey')
|
||||
self.assert_equal(app.config['TEST_KEY'], 'foo')
|
||||
self.assert_not_in('ConfigTestCase', app.config)
|
||||
|
||||
def test_config_from_file(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.config.from_pyfile(__file__.rsplit('.', 1)[0] + '.py')
|
||||
self.common_object_test(app)
|
||||
|
||||
def test_config_from_object(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.config.from_object(__name__)
|
||||
self.common_object_test(app)
|
||||
|
||||
def test_config_from_class(self):
|
||||
class Base(object):
|
||||
TEST_KEY = 'foo'
|
||||
class Test(Base):
|
||||
SECRET_KEY = 'devkey'
|
||||
app = flask.Flask(__name__)
|
||||
app.config.from_object(Test)
|
||||
self.common_object_test(app)
|
||||
|
||||
def test_config_from_envvar(self):
|
||||
env = os.environ
|
||||
try:
|
||||
os.environ = {}
|
||||
app = flask.Flask(__name__)
|
||||
try:
|
||||
app.config.from_envvar('FOO_SETTINGS')
|
||||
except RuntimeError as e:
|
||||
self.assert_true("'FOO_SETTINGS' is not set" in str(e))
|
||||
else:
|
||||
self.assert_true(0, 'expected exception')
|
||||
self.assert_false(app.config.from_envvar('FOO_SETTINGS', silent=True))
|
||||
|
||||
os.environ = {'FOO_SETTINGS': __file__.rsplit('.', 1)[0] + '.py'}
|
||||
self.assert_true(app.config.from_envvar('FOO_SETTINGS'))
|
||||
self.common_object_test(app)
|
||||
finally:
|
||||
os.environ = env
|
||||
|
||||
def test_config_from_envvar_missing(self):
|
||||
env = os.environ
|
||||
try:
|
||||
os.environ = {'FOO_SETTINGS': 'missing.cfg'}
|
||||
try:
|
||||
app = flask.Flask(__name__)
|
||||
app.config.from_envvar('FOO_SETTINGS')
|
||||
except IOError as e:
|
||||
msg = str(e)
|
||||
self.assert_true(msg.startswith('[Errno 2] Unable to load configuration '
|
||||
'file (No such file or directory):'))
|
||||
self.assert_true(msg.endswith("missing.cfg'"))
|
||||
else:
|
||||
self.fail('expected IOError')
|
||||
self.assertFalse(app.config.from_envvar('FOO_SETTINGS', silent=True))
|
||||
finally:
|
||||
os.environ = env
|
||||
|
||||
def test_config_missing(self):
|
||||
app = flask.Flask(__name__)
|
||||
try:
|
||||
app.config.from_pyfile('missing.cfg')
|
||||
except IOError as e:
|
||||
msg = str(e)
|
||||
self.assert_true(msg.startswith('[Errno 2] Unable to load configuration '
|
||||
'file (No such file or directory):'))
|
||||
self.assert_true(msg.endswith("missing.cfg'"))
|
||||
else:
|
||||
self.assert_true(0, 'expected config')
|
||||
self.assert_false(app.config.from_pyfile('missing.cfg', silent=True))
|
||||
|
||||
def test_session_lifetime(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.config['PERMANENT_SESSION_LIFETIME'] = 42
|
||||
self.assert_equal(app.permanent_session_lifetime.seconds, 42)
|
||||
|
||||
|
||||
class LimitedLoaderMockWrapper(object):
|
||||
def __init__(self, loader):
|
||||
self.loader = loader
|
||||
|
||||
def __getattr__(self, name):
|
||||
if name in ('archive', 'get_filename'):
|
||||
msg = 'Mocking a loader which does not have `%s.`' % name
|
||||
raise AttributeError(msg)
|
||||
return getattr(self.loader, name)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def patch_pkgutil_get_loader(wrapper_class=LimitedLoaderMockWrapper):
|
||||
"""Patch pkgutil.get_loader to give loader without get_filename or archive.
|
||||
|
||||
This provides for tests where a system has custom loaders, e.g. Google App
|
||||
Engine's HardenedModulesHook, which have neither the `get_filename` method
|
||||
nor the `archive` attribute.
|
||||
"""
|
||||
old_get_loader = pkgutil.get_loader
|
||||
def get_loader(*args, **kwargs):
|
||||
return wrapper_class(old_get_loader(*args, **kwargs))
|
||||
try:
|
||||
pkgutil.get_loader = get_loader
|
||||
yield
|
||||
finally:
|
||||
pkgutil.get_loader = old_get_loader
|
||||
|
||||
|
||||
class InstanceTestCase(FlaskTestCase):
|
||||
|
||||
def test_explicit_instance_paths(self):
|
||||
here = os.path.abspath(os.path.dirname(__file__))
|
||||
try:
|
||||
flask.Flask(__name__, instance_path='instance')
|
||||
except ValueError as e:
|
||||
self.assert_in('must be absolute', str(e))
|
||||
else:
|
||||
self.fail('Expected value error')
|
||||
|
||||
app = flask.Flask(__name__, instance_path=here)
|
||||
self.assert_equal(app.instance_path, here)
|
||||
|
||||
def test_main_module_paths(self):
|
||||
# Test an app with '__main__' as the import name, uses cwd.
|
||||
from main_app import app
|
||||
here = os.path.abspath(os.getcwd())
|
||||
self.assert_equal(app.instance_path, os.path.join(here, 'instance'))
|
||||
if 'main_app' in sys.modules:
|
||||
del sys.modules['main_app']
|
||||
|
||||
def test_uninstalled_module_paths(self):
|
||||
from config_module_app import app
|
||||
here = os.path.abspath(os.path.dirname(__file__))
|
||||
self.assert_equal(app.instance_path, os.path.join(here, 'test_apps', 'instance'))
|
||||
|
||||
def test_uninstalled_package_paths(self):
|
||||
from config_package_app import app
|
||||
here = os.path.abspath(os.path.dirname(__file__))
|
||||
self.assert_equal(app.instance_path, os.path.join(here, 'test_apps', 'instance'))
|
||||
|
||||
def test_installed_module_paths(self):
|
||||
here = os.path.abspath(os.path.dirname(__file__))
|
||||
expected_prefix = os.path.join(here, 'test_apps')
|
||||
real_prefix, sys.prefix = sys.prefix, expected_prefix
|
||||
site_packages = os.path.join(expected_prefix, 'lib', 'python2.5', 'site-packages')
|
||||
sys.path.append(site_packages)
|
||||
try:
|
||||
import site_app
|
||||
self.assert_equal(site_app.app.instance_path,
|
||||
os.path.join(expected_prefix, 'var',
|
||||
'site_app-instance'))
|
||||
finally:
|
||||
sys.prefix = real_prefix
|
||||
sys.path.remove(site_packages)
|
||||
if 'site_app' in sys.modules:
|
||||
del sys.modules['site_app']
|
||||
|
||||
def test_installed_module_paths_with_limited_loader(self):
|
||||
here = os.path.abspath(os.path.dirname(__file__))
|
||||
expected_prefix = os.path.join(here, 'test_apps')
|
||||
real_prefix, sys.prefix = sys.prefix, expected_prefix
|
||||
site_packages = os.path.join(expected_prefix, 'lib', 'python2.5', 'site-packages')
|
||||
sys.path.append(site_packages)
|
||||
with patch_pkgutil_get_loader():
|
||||
try:
|
||||
import site_app
|
||||
self.assert_equal(site_app.app.instance_path,
|
||||
os.path.join(expected_prefix, 'var',
|
||||
'site_app-instance'))
|
||||
finally:
|
||||
sys.prefix = real_prefix
|
||||
sys.path.remove(site_packages)
|
||||
if 'site_app' in sys.modules:
|
||||
del sys.modules['site_app']
|
||||
|
||||
def test_installed_package_paths(self):
|
||||
here = os.path.abspath(os.path.dirname(__file__))
|
||||
expected_prefix = os.path.join(here, 'test_apps')
|
||||
real_prefix, sys.prefix = sys.prefix, expected_prefix
|
||||
installed_path = os.path.join(expected_prefix, 'path')
|
||||
sys.path.append(installed_path)
|
||||
try:
|
||||
import installed_package
|
||||
self.assert_equal(installed_package.app.instance_path,
|
||||
os.path.join(expected_prefix, 'var',
|
||||
'installed_package-instance'))
|
||||
finally:
|
||||
sys.prefix = real_prefix
|
||||
sys.path.remove(installed_path)
|
||||
if 'installed_package' in sys.modules:
|
||||
del sys.modules['installed_package']
|
||||
|
||||
def test_installed_package_paths_with_limited_loader(self):
|
||||
here = os.path.abspath(os.path.dirname(__file__))
|
||||
expected_prefix = os.path.join(here, 'test_apps')
|
||||
real_prefix, sys.prefix = sys.prefix, expected_prefix
|
||||
installed_path = os.path.join(expected_prefix, 'path')
|
||||
sys.path.append(installed_path)
|
||||
with patch_pkgutil_get_loader():
|
||||
try:
|
||||
import installed_package
|
||||
self.assert_equal(installed_package.app.instance_path,
|
||||
os.path.join(expected_prefix, 'var',
|
||||
'installed_package-instance'))
|
||||
finally:
|
||||
sys.prefix = real_prefix
|
||||
sys.path.remove(installed_path)
|
||||
if 'installed_package' in sys.modules:
|
||||
del sys.modules['installed_package']
|
||||
|
||||
def test_prefix_package_paths(self):
|
||||
here = os.path.abspath(os.path.dirname(__file__))
|
||||
expected_prefix = os.path.join(here, 'test_apps')
|
||||
real_prefix, sys.prefix = sys.prefix, expected_prefix
|
||||
site_packages = os.path.join(expected_prefix, 'lib', 'python2.5', 'site-packages')
|
||||
sys.path.append(site_packages)
|
||||
try:
|
||||
import site_package
|
||||
self.assert_equal(site_package.app.instance_path,
|
||||
os.path.join(expected_prefix, 'var',
|
||||
'site_package-instance'))
|
||||
finally:
|
||||
sys.prefix = real_prefix
|
||||
sys.path.remove(site_packages)
|
||||
if 'site_package' in sys.modules:
|
||||
del sys.modules['site_package']
|
||||
|
||||
def test_prefix_package_paths_with_limited_loader(self):
|
||||
here = os.path.abspath(os.path.dirname(__file__))
|
||||
expected_prefix = os.path.join(here, 'test_apps')
|
||||
real_prefix, sys.prefix = sys.prefix, expected_prefix
|
||||
site_packages = os.path.join(expected_prefix, 'lib', 'python2.5', 'site-packages')
|
||||
sys.path.append(site_packages)
|
||||
with patch_pkgutil_get_loader():
|
||||
try:
|
||||
import site_package
|
||||
self.assert_equal(site_package.app.instance_path,
|
||||
os.path.join(expected_prefix, 'var',
|
||||
'site_package-instance'))
|
||||
finally:
|
||||
sys.prefix = real_prefix
|
||||
sys.path.remove(site_packages)
|
||||
if 'site_package' in sys.modules:
|
||||
del sys.modules['site_package']
|
||||
|
||||
def test_egg_installed_paths(self):
|
||||
here = os.path.abspath(os.path.dirname(__file__))
|
||||
expected_prefix = os.path.join(here, 'test_apps')
|
||||
real_prefix, sys.prefix = sys.prefix, expected_prefix
|
||||
site_packages = os.path.join(expected_prefix, 'lib', 'python2.5', 'site-packages')
|
||||
egg_path = os.path.join(site_packages, 'SiteEgg.egg')
|
||||
sys.path.append(site_packages)
|
||||
sys.path.append(egg_path)
|
||||
try:
|
||||
import site_egg # in SiteEgg.egg
|
||||
self.assert_equal(site_egg.app.instance_path,
|
||||
os.path.join(expected_prefix, 'var',
|
||||
'site_egg-instance'))
|
||||
finally:
|
||||
sys.prefix = real_prefix
|
||||
sys.path.remove(site_packages)
|
||||
sys.path.remove(egg_path)
|
||||
if 'site_egg' in sys.modules:
|
||||
del sys.modules['site_egg']
|
||||
|
||||
|
||||
def suite():
|
||||
suite = unittest.TestSuite()
|
||||
suite.addTest(unittest.makeSuite(ConfigTestCase))
|
||||
suite.addTest(unittest.makeSuite(InstanceTestCase))
|
||||
return suite
|
24
lib/flask/testsuite/deprecations.py
Normal file
24
lib/flask/testsuite/deprecations.py
Normal file
|
@ -0,0 +1,24 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
flask.testsuite.deprecations
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Tests deprecation support.
|
||||
|
||||
:copyright: (c) 2011 by Armin Ronacher.
|
||||
:license: BSD, see LICENSE for more details.
|
||||
"""
|
||||
|
||||
import flask
|
||||
import unittest
|
||||
from flask.testsuite import FlaskTestCase, catch_warnings
|
||||
|
||||
|
||||
class DeprecationsTestCase(FlaskTestCase):
|
||||
"""not used currently"""
|
||||
|
||||
|
||||
def suite():
|
||||
suite = unittest.TestSuite()
|
||||
suite.addTest(unittest.makeSuite(DeprecationsTestCase))
|
||||
return suite
|
38
lib/flask/testsuite/examples.py
Normal file
38
lib/flask/testsuite/examples.py
Normal file
|
@ -0,0 +1,38 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
flask.testsuite.examples
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Tests the examples.
|
||||
|
||||
:copyright: (c) 2011 by Armin Ronacher.
|
||||
:license: BSD, see LICENSE for more details.
|
||||
"""
|
||||
import os
|
||||
import unittest
|
||||
from flask.testsuite import add_to_path
|
||||
|
||||
|
||||
def setup_path():
|
||||
example_path = os.path.join(os.path.dirname(__file__),
|
||||
os.pardir, os.pardir, 'examples')
|
||||
add_to_path(os.path.join(example_path, 'flaskr'))
|
||||
add_to_path(os.path.join(example_path, 'minitwit'))
|
||||
|
||||
|
||||
def suite():
|
||||
setup_path()
|
||||
suite = unittest.TestSuite()
|
||||
try:
|
||||
from minitwit_tests import MiniTwitTestCase
|
||||
except ImportError:
|
||||
pass
|
||||
else:
|
||||
suite.addTest(unittest.makeSuite(MiniTwitTestCase))
|
||||
try:
|
||||
from flaskr_tests import FlaskrTestCase
|
||||
except ImportError:
|
||||
pass
|
||||
else:
|
||||
suite.addTest(unittest.makeSuite(FlaskrTestCase))
|
||||
return suite
|
134
lib/flask/testsuite/ext.py
Normal file
134
lib/flask/testsuite/ext.py
Normal file
|
@ -0,0 +1,134 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
flask.testsuite.ext
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Tests the extension import thing.
|
||||
|
||||
:copyright: (c) 2011 by Armin Ronacher.
|
||||
:license: BSD, see LICENSE for more details.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
try:
|
||||
from imp import reload as reload_module
|
||||
except ImportError:
|
||||
reload_module = reload
|
||||
from flask.testsuite import FlaskTestCase
|
||||
from flask._compat import PY2
|
||||
|
||||
class ExtImportHookTestCase(FlaskTestCase):
|
||||
|
||||
def setup(self):
|
||||
# we clear this out for various reasons. The most important one is
|
||||
# that a real flaskext could be in there which would disable our
|
||||
# fake package. Secondly we want to make sure that the flaskext
|
||||
# import hook does not break on reloading.
|
||||
for entry, value in list(sys.modules.items()):
|
||||
if (entry.startswith('flask.ext.') or
|
||||
entry.startswith('flask_') or
|
||||
entry.startswith('flaskext.') or
|
||||
entry == 'flaskext') and value is not None:
|
||||
sys.modules.pop(entry, None)
|
||||
from flask import ext
|
||||
reload_module(ext)
|
||||
|
||||
# reloading must not add more hooks
|
||||
import_hooks = 0
|
||||
for item in sys.meta_path:
|
||||
cls = type(item)
|
||||
if cls.__module__ == 'flask.exthook' and \
|
||||
cls.__name__ == 'ExtensionImporter':
|
||||
import_hooks += 1
|
||||
self.assert_equal(import_hooks, 1)
|
||||
|
||||
def teardown(self):
|
||||
from flask import ext
|
||||
for key in ext.__dict__:
|
||||
self.assert_not_in('.', key)
|
||||
|
||||
def test_flaskext_new_simple_import_normal(self):
|
||||
from flask.ext.newext_simple import ext_id
|
||||
self.assert_equal(ext_id, 'newext_simple')
|
||||
|
||||
def test_flaskext_new_simple_import_module(self):
|
||||
from flask.ext import newext_simple
|
||||
self.assert_equal(newext_simple.ext_id, 'newext_simple')
|
||||
self.assert_equal(newext_simple.__name__, 'flask_newext_simple')
|
||||
|
||||
def test_flaskext_new_package_import_normal(self):
|
||||
from flask.ext.newext_package import ext_id
|
||||
self.assert_equal(ext_id, 'newext_package')
|
||||
|
||||
def test_flaskext_new_package_import_module(self):
|
||||
from flask.ext import newext_package
|
||||
self.assert_equal(newext_package.ext_id, 'newext_package')
|
||||
self.assert_equal(newext_package.__name__, 'flask_newext_package')
|
||||
|
||||
def test_flaskext_new_package_import_submodule_function(self):
|
||||
from flask.ext.newext_package.submodule import test_function
|
||||
self.assert_equal(test_function(), 42)
|
||||
|
||||
def test_flaskext_new_package_import_submodule(self):
|
||||
from flask.ext.newext_package import submodule
|
||||
self.assert_equal(submodule.__name__, 'flask_newext_package.submodule')
|
||||
self.assert_equal(submodule.test_function(), 42)
|
||||
|
||||
def test_flaskext_old_simple_import_normal(self):
|
||||
from flask.ext.oldext_simple import ext_id
|
||||
self.assert_equal(ext_id, 'oldext_simple')
|
||||
|
||||
def test_flaskext_old_simple_import_module(self):
|
||||
from flask.ext import oldext_simple
|
||||
self.assert_equal(oldext_simple.ext_id, 'oldext_simple')
|
||||
self.assert_equal(oldext_simple.__name__, 'flaskext.oldext_simple')
|
||||
|
||||
def test_flaskext_old_package_import_normal(self):
|
||||
from flask.ext.oldext_package import ext_id
|
||||
self.assert_equal(ext_id, 'oldext_package')
|
||||
|
||||
def test_flaskext_old_package_import_module(self):
|
||||
from flask.ext import oldext_package
|
||||
self.assert_equal(oldext_package.ext_id, 'oldext_package')
|
||||
self.assert_equal(oldext_package.__name__, 'flaskext.oldext_package')
|
||||
|
||||
def test_flaskext_old_package_import_submodule(self):
|
||||
from flask.ext.oldext_package import submodule
|
||||
self.assert_equal(submodule.__name__, 'flaskext.oldext_package.submodule')
|
||||
self.assert_equal(submodule.test_function(), 42)
|
||||
|
||||
def test_flaskext_old_package_import_submodule_function(self):
|
||||
from flask.ext.oldext_package.submodule import test_function
|
||||
self.assert_equal(test_function(), 42)
|
||||
|
||||
def test_flaskext_broken_package_no_module_caching(self):
|
||||
for x in range(2):
|
||||
with self.assert_raises(ImportError):
|
||||
import flask.ext.broken
|
||||
|
||||
def test_no_error_swallowing(self):
|
||||
try:
|
||||
import flask.ext.broken
|
||||
except ImportError:
|
||||
exc_type, exc_value, tb = sys.exc_info()
|
||||
self.assert_true(exc_type is ImportError)
|
||||
if PY2:
|
||||
message = 'No module named missing_module'
|
||||
else:
|
||||
message = 'No module named \'missing_module\''
|
||||
self.assert_equal(str(exc_value), message)
|
||||
self.assert_true(tb.tb_frame.f_globals is globals())
|
||||
|
||||
# reraise() adds a second frame so we need to skip that one too.
|
||||
# On PY3 we even have another one :(
|
||||
next = tb.tb_next.tb_next
|
||||
if not PY2:
|
||||
next = next.tb_next
|
||||
self.assert_in('flask_broken/__init__.py', next.tb_frame.f_code.co_filename)
|
||||
|
||||
|
||||
def suite():
|
||||
suite = unittest.TestSuite()
|
||||
suite.addTest(unittest.makeSuite(ExtImportHookTestCase))
|
||||
return suite
|
593
lib/flask/testsuite/helpers.py
Normal file
593
lib/flask/testsuite/helpers.py
Normal file
|
@ -0,0 +1,593 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
flask.testsuite.helpers
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Various helpers.
|
||||
|
||||
:copyright: (c) 2011 by Armin Ronacher.
|
||||
:license: BSD, see LICENSE for more details.
|
||||
"""
|
||||
|
||||
import os
|
||||
import flask
|
||||
import unittest
|
||||
from logging import StreamHandler
|
||||
from flask.testsuite import FlaskTestCase, catch_warnings, catch_stderr
|
||||
from werkzeug.http import parse_cache_control_header, parse_options_header
|
||||
from flask._compat import StringIO, text_type
|
||||
|
||||
|
||||
def has_encoding(name):
|
||||
try:
|
||||
import codecs
|
||||
codecs.lookup(name)
|
||||
return True
|
||||
except LookupError:
|
||||
return False
|
||||
|
||||
|
||||
class JSONTestCase(FlaskTestCase):
|
||||
|
||||
def test_json_bad_requests(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.route('/json', methods=['POST'])
|
||||
def return_json():
|
||||
return flask.jsonify(foo=text_type(flask.request.get_json()))
|
||||
c = app.test_client()
|
||||
rv = c.post('/json', data='malformed', content_type='application/json')
|
||||
self.assert_equal(rv.status_code, 400)
|
||||
|
||||
def test_json_body_encoding(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.testing = True
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.request.get_json()
|
||||
|
||||
c = app.test_client()
|
||||
resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),
|
||||
content_type='application/json; charset=iso-8859-15')
|
||||
self.assert_equal(resp.data, u'Hällo Wörld'.encode('utf-8'))
|
||||
|
||||
def test_jsonify(self):
|
||||
d = dict(a=23, b=42, c=[1, 2, 3])
|
||||
app = flask.Flask(__name__)
|
||||
@app.route('/kw')
|
||||
def return_kwargs():
|
||||
return flask.jsonify(**d)
|
||||
@app.route('/dict')
|
||||
def return_dict():
|
||||
return flask.jsonify(d)
|
||||
c = app.test_client()
|
||||
for url in '/kw', '/dict':
|
||||
rv = c.get(url)
|
||||
self.assert_equal(rv.mimetype, 'application/json')
|
||||
self.assert_equal(flask.json.loads(rv.data), d)
|
||||
|
||||
def test_json_as_unicode(self):
|
||||
app = flask.Flask(__name__)
|
||||
|
||||
app.config['JSON_AS_ASCII'] = True
|
||||
with app.app_context():
|
||||
rv = flask.json.dumps(u'\N{SNOWMAN}')
|
||||
self.assert_equal(rv, '"\\u2603"')
|
||||
|
||||
app.config['JSON_AS_ASCII'] = False
|
||||
with app.app_context():
|
||||
rv = flask.json.dumps(u'\N{SNOWMAN}')
|
||||
self.assert_equal(rv, u'"\u2603"')
|
||||
|
||||
def test_json_attr(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.route('/add', methods=['POST'])
|
||||
def add():
|
||||
json = flask.request.get_json()
|
||||
return text_type(json['a'] + json['b'])
|
||||
c = app.test_client()
|
||||
rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),
|
||||
content_type='application/json')
|
||||
self.assert_equal(rv.data, b'3')
|
||||
|
||||
def test_template_escaping(self):
|
||||
app = flask.Flask(__name__)
|
||||
render = flask.render_template_string
|
||||
with app.test_request_context():
|
||||
rv = flask.json.htmlsafe_dumps('</script>')
|
||||
self.assert_equal(rv, u'"\\u003c/script\\u003e"')
|
||||
self.assert_equal(type(rv), text_type)
|
||||
rv = render('{{ "</script>"|tojson }}')
|
||||
self.assert_equal(rv, '"\\u003c/script\\u003e"')
|
||||
rv = render('{{ "<\0/script>"|tojson }}')
|
||||
self.assert_equal(rv, '"\\u003c\\u0000/script\\u003e"')
|
||||
rv = render('{{ "<!--<script>"|tojson }}')
|
||||
self.assert_equal(rv, '"\\u003c!--\\u003cscript\\u003e"')
|
||||
rv = render('{{ "&"|tojson }}')
|
||||
self.assert_equal(rv, '"\\u0026"')
|
||||
rv = render('{{ "\'"|tojson }}')
|
||||
self.assert_equal(rv, '"\\u0027"')
|
||||
rv = render("<a ng-data='{{ data|tojson }}'></a>",
|
||||
data={'x': ["foo", "bar", "baz'"]})
|
||||
self.assert_equal(rv,
|
||||
'<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>')
|
||||
|
||||
def test_json_customization(self):
|
||||
class X(object):
|
||||
def __init__(self, val):
|
||||
self.val = val
|
||||
class MyEncoder(flask.json.JSONEncoder):
|
||||
def default(self, o):
|
||||
if isinstance(o, X):
|
||||
return '<%d>' % o.val
|
||||
return flask.json.JSONEncoder.default(self, o)
|
||||
class MyDecoder(flask.json.JSONDecoder):
|
||||
def __init__(self, *args, **kwargs):
|
||||
kwargs.setdefault('object_hook', self.object_hook)
|
||||
flask.json.JSONDecoder.__init__(self, *args, **kwargs)
|
||||
def object_hook(self, obj):
|
||||
if len(obj) == 1 and '_foo' in obj:
|
||||
return X(obj['_foo'])
|
||||
return obj
|
||||
app = flask.Flask(__name__)
|
||||
app.testing = True
|
||||
app.json_encoder = MyEncoder
|
||||
app.json_decoder = MyDecoder
|
||||
@app.route('/', methods=['POST'])
|
||||
def index():
|
||||
return flask.json.dumps(flask.request.get_json()['x'])
|
||||
c = app.test_client()
|
||||
rv = c.post('/', data=flask.json.dumps({
|
||||
'x': {'_foo': 42}
|
||||
}), content_type='application/json')
|
||||
self.assertEqual(rv.data, b'"<42>"')
|
||||
|
||||
def test_modified_url_encoding(self):
|
||||
class ModifiedRequest(flask.Request):
|
||||
url_charset = 'euc-kr'
|
||||
app = flask.Flask(__name__)
|
||||
app.testing = True
|
||||
app.request_class = ModifiedRequest
|
||||
app.url_map.charset = 'euc-kr'
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.request.args['foo']
|
||||
|
||||
rv = app.test_client().get(u'/?foo=정상처리'.encode('euc-kr'))
|
||||
self.assert_equal(rv.status_code, 200)
|
||||
self.assert_equal(rv.data, u'정상처리'.encode('utf-8'))
|
||||
|
||||
if not has_encoding('euc-kr'):
|
||||
test_modified_url_encoding = None
|
||||
|
||||
def test_json_key_sorting(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.testing = True
|
||||
self.assert_equal(app.config['JSON_SORT_KEYS'], True)
|
||||
d = dict.fromkeys(range(20), 'foo')
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.jsonify(values=d)
|
||||
|
||||
c = app.test_client()
|
||||
rv = c.get('/')
|
||||
lines = [x.strip() for x in rv.data.strip().decode('utf-8').splitlines()]
|
||||
self.assert_equal(lines, [
|
||||
'{',
|
||||
'"values": {',
|
||||
'"0": "foo",',
|
||||
'"1": "foo",',
|
||||
'"2": "foo",',
|
||||
'"3": "foo",',
|
||||
'"4": "foo",',
|
||||
'"5": "foo",',
|
||||
'"6": "foo",',
|
||||
'"7": "foo",',
|
||||
'"8": "foo",',
|
||||
'"9": "foo",',
|
||||
'"10": "foo",',
|
||||
'"11": "foo",',
|
||||
'"12": "foo",',
|
||||
'"13": "foo",',
|
||||
'"14": "foo",',
|
||||
'"15": "foo",',
|
||||
'"16": "foo",',
|
||||
'"17": "foo",',
|
||||
'"18": "foo",',
|
||||
'"19": "foo"',
|
||||
'}',
|
||||
'}'
|
||||
])
|
||||
|
||||
|
||||
class SendfileTestCase(FlaskTestCase):
|
||||
|
||||
def test_send_file_regular(self):
|
||||
app = flask.Flask(__name__)
|
||||
with app.test_request_context():
|
||||
rv = flask.send_file('static/index.html')
|
||||
self.assert_true(rv.direct_passthrough)
|
||||
self.assert_equal(rv.mimetype, 'text/html')
|
||||
with app.open_resource('static/index.html') as f:
|
||||
rv.direct_passthrough = False
|
||||
self.assert_equal(rv.data, f.read())
|
||||
rv.close()
|
||||
|
||||
def test_send_file_xsendfile(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.use_x_sendfile = True
|
||||
with app.test_request_context():
|
||||
rv = flask.send_file('static/index.html')
|
||||
self.assert_true(rv.direct_passthrough)
|
||||
self.assert_in('x-sendfile', rv.headers)
|
||||
self.assert_equal(rv.headers['x-sendfile'],
|
||||
os.path.join(app.root_path, 'static/index.html'))
|
||||
self.assert_equal(rv.mimetype, 'text/html')
|
||||
rv.close()
|
||||
|
||||
def test_send_file_object(self):
|
||||
app = flask.Flask(__name__)
|
||||
with catch_warnings() as captured:
|
||||
with app.test_request_context():
|
||||
f = open(os.path.join(app.root_path, 'static/index.html'))
|
||||
rv = flask.send_file(f)
|
||||
rv.direct_passthrough = False
|
||||
with app.open_resource('static/index.html') as f:
|
||||
self.assert_equal(rv.data, f.read())
|
||||
self.assert_equal(rv.mimetype, 'text/html')
|
||||
rv.close()
|
||||
# mimetypes + etag
|
||||
self.assert_equal(len(captured), 2)
|
||||
|
||||
app.use_x_sendfile = True
|
||||
with catch_warnings() as captured:
|
||||
with app.test_request_context():
|
||||
f = open(os.path.join(app.root_path, 'static/index.html'))
|
||||
rv = flask.send_file(f)
|
||||
self.assert_equal(rv.mimetype, 'text/html')
|
||||
self.assert_in('x-sendfile', rv.headers)
|
||||
self.assert_equal(rv.headers['x-sendfile'],
|
||||
os.path.join(app.root_path, 'static/index.html'))
|
||||
rv.close()
|
||||
# mimetypes + etag
|
||||
self.assert_equal(len(captured), 2)
|
||||
|
||||
app.use_x_sendfile = False
|
||||
with app.test_request_context():
|
||||
with catch_warnings() as captured:
|
||||
f = StringIO('Test')
|
||||
rv = flask.send_file(f)
|
||||
rv.direct_passthrough = False
|
||||
self.assert_equal(rv.data, b'Test')
|
||||
self.assert_equal(rv.mimetype, 'application/octet-stream')
|
||||
rv.close()
|
||||
# etags
|
||||
self.assert_equal(len(captured), 1)
|
||||
with catch_warnings() as captured:
|
||||
f = StringIO('Test')
|
||||
rv = flask.send_file(f, mimetype='text/plain')
|
||||
rv.direct_passthrough = False
|
||||
self.assert_equal(rv.data, b'Test')
|
||||
self.assert_equal(rv.mimetype, 'text/plain')
|
||||
rv.close()
|
||||
# etags
|
||||
self.assert_equal(len(captured), 1)
|
||||
|
||||
app.use_x_sendfile = True
|
||||
with catch_warnings() as captured:
|
||||
with app.test_request_context():
|
||||
f = StringIO('Test')
|
||||
rv = flask.send_file(f)
|
||||
self.assert_not_in('x-sendfile', rv.headers)
|
||||
rv.close()
|
||||
# etags
|
||||
self.assert_equal(len(captured), 1)
|
||||
|
||||
def test_attachment(self):
|
||||
app = flask.Flask(__name__)
|
||||
with catch_warnings() as captured:
|
||||
with app.test_request_context():
|
||||
f = open(os.path.join(app.root_path, 'static/index.html'))
|
||||
rv = flask.send_file(f, as_attachment=True)
|
||||
value, options = parse_options_header(rv.headers['Content-Disposition'])
|
||||
self.assert_equal(value, 'attachment')
|
||||
rv.close()
|
||||
# mimetypes + etag
|
||||
self.assert_equal(len(captured), 2)
|
||||
|
||||
with app.test_request_context():
|
||||
self.assert_equal(options['filename'], 'index.html')
|
||||
rv = flask.send_file('static/index.html', as_attachment=True)
|
||||
value, options = parse_options_header(rv.headers['Content-Disposition'])
|
||||
self.assert_equal(value, 'attachment')
|
||||
self.assert_equal(options['filename'], 'index.html')
|
||||
rv.close()
|
||||
|
||||
with app.test_request_context():
|
||||
rv = flask.send_file(StringIO('Test'), as_attachment=True,
|
||||
attachment_filename='index.txt',
|
||||
add_etags=False)
|
||||
self.assert_equal(rv.mimetype, 'text/plain')
|
||||
value, options = parse_options_header(rv.headers['Content-Disposition'])
|
||||
self.assert_equal(value, 'attachment')
|
||||
self.assert_equal(options['filename'], 'index.txt')
|
||||
rv.close()
|
||||
|
||||
def test_static_file(self):
|
||||
app = flask.Flask(__name__)
|
||||
# default cache timeout is 12 hours
|
||||
with app.test_request_context():
|
||||
# Test with static file handler.
|
||||
rv = app.send_static_file('index.html')
|
||||
cc = parse_cache_control_header(rv.headers['Cache-Control'])
|
||||
self.assert_equal(cc.max_age, 12 * 60 * 60)
|
||||
rv.close()
|
||||
# Test again with direct use of send_file utility.
|
||||
rv = flask.send_file('static/index.html')
|
||||
cc = parse_cache_control_header(rv.headers['Cache-Control'])
|
||||
self.assert_equal(cc.max_age, 12 * 60 * 60)
|
||||
rv.close()
|
||||
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600
|
||||
with app.test_request_context():
|
||||
# Test with static file handler.
|
||||
rv = app.send_static_file('index.html')
|
||||
cc = parse_cache_control_header(rv.headers['Cache-Control'])
|
||||
self.assert_equal(cc.max_age, 3600)
|
||||
rv.close()
|
||||
# Test again with direct use of send_file utility.
|
||||
rv = flask.send_file('static/index.html')
|
||||
cc = parse_cache_control_header(rv.headers['Cache-Control'])
|
||||
self.assert_equal(cc.max_age, 3600)
|
||||
rv.close()
|
||||
class StaticFileApp(flask.Flask):
|
||||
def get_send_file_max_age(self, filename):
|
||||
return 10
|
||||
app = StaticFileApp(__name__)
|
||||
with app.test_request_context():
|
||||
# Test with static file handler.
|
||||
rv = app.send_static_file('index.html')
|
||||
cc = parse_cache_control_header(rv.headers['Cache-Control'])
|
||||
self.assert_equal(cc.max_age, 10)
|
||||
rv.close()
|
||||
# Test again with direct use of send_file utility.
|
||||
rv = flask.send_file('static/index.html')
|
||||
cc = parse_cache_control_header(rv.headers['Cache-Control'])
|
||||
self.assert_equal(cc.max_age, 10)
|
||||
rv.close()
|
||||
|
||||
|
||||
class LoggingTestCase(FlaskTestCase):
|
||||
|
||||
def test_logger_cache(self):
|
||||
app = flask.Flask(__name__)
|
||||
logger1 = app.logger
|
||||
self.assert_true(app.logger is logger1)
|
||||
self.assert_equal(logger1.name, __name__)
|
||||
app.logger_name = __name__ + '/test_logger_cache'
|
||||
self.assert_true(app.logger is not logger1)
|
||||
|
||||
def test_debug_log(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.debug = True
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
app.logger.warning('the standard library is dead')
|
||||
app.logger.debug('this is a debug statement')
|
||||
return ''
|
||||
|
||||
@app.route('/exc')
|
||||
def exc():
|
||||
1 // 0
|
||||
|
||||
with app.test_client() as c:
|
||||
with catch_stderr() as err:
|
||||
c.get('/')
|
||||
out = err.getvalue()
|
||||
self.assert_in('WARNING in helpers [', out)
|
||||
self.assert_in(os.path.basename(__file__.rsplit('.', 1)[0] + '.py'), out)
|
||||
self.assert_in('the standard library is dead', out)
|
||||
self.assert_in('this is a debug statement', out)
|
||||
|
||||
with catch_stderr() as err:
|
||||
try:
|
||||
c.get('/exc')
|
||||
except ZeroDivisionError:
|
||||
pass
|
||||
else:
|
||||
self.assert_true(False, 'debug log ate the exception')
|
||||
|
||||
def test_debug_log_override(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.debug = True
|
||||
app.logger_name = 'flask_tests/test_debug_log_override'
|
||||
app.logger.level = 10
|
||||
self.assert_equal(app.logger.level, 10)
|
||||
|
||||
def test_exception_logging(self):
|
||||
out = StringIO()
|
||||
app = flask.Flask(__name__)
|
||||
app.logger_name = 'flask_tests/test_exception_logging'
|
||||
app.logger.addHandler(StreamHandler(out))
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
1 // 0
|
||||
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_equal(rv.status_code, 500)
|
||||
self.assert_in(b'Internal Server Error', rv.data)
|
||||
|
||||
err = out.getvalue()
|
||||
self.assert_in('Exception on / [GET]', err)
|
||||
self.assert_in('Traceback (most recent call last):', err)
|
||||
self.assert_in('1 // 0', err)
|
||||
self.assert_in('ZeroDivisionError:', err)
|
||||
|
||||
def test_processor_exceptions(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.before_request
|
||||
def before_request():
|
||||
if trigger == 'before':
|
||||
1 // 0
|
||||
@app.after_request
|
||||
def after_request(response):
|
||||
if trigger == 'after':
|
||||
1 // 0
|
||||
return response
|
||||
@app.route('/')
|
||||
def index():
|
||||
return 'Foo'
|
||||
@app.errorhandler(500)
|
||||
def internal_server_error(e):
|
||||
return 'Hello Server Error', 500
|
||||
for trigger in 'before', 'after':
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_equal(rv.status_code, 500)
|
||||
self.assert_equal(rv.data, b'Hello Server Error')
|
||||
|
||||
def test_url_for_with_anchor(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.route('/')
|
||||
def index():
|
||||
return '42'
|
||||
with app.test_request_context():
|
||||
self.assert_equal(flask.url_for('index', _anchor='x y'),
|
||||
'/#x%20y')
|
||||
|
||||
def test_url_for_with_scheme(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.route('/')
|
||||
def index():
|
||||
return '42'
|
||||
with app.test_request_context():
|
||||
self.assert_equal(flask.url_for('index',
|
||||
_external=True,
|
||||
_scheme='https'),
|
||||
'https://localhost/')
|
||||
|
||||
def test_url_for_with_scheme_not_external(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.route('/')
|
||||
def index():
|
||||
return '42'
|
||||
with app.test_request_context():
|
||||
self.assert_raises(ValueError,
|
||||
flask.url_for,
|
||||
'index',
|
||||
_scheme='https')
|
||||
|
||||
def test_url_with_method(self):
|
||||
from flask.views import MethodView
|
||||
app = flask.Flask(__name__)
|
||||
class MyView(MethodView):
|
||||
def get(self, id=None):
|
||||
if id is None:
|
||||
return 'List'
|
||||
return 'Get %d' % id
|
||||
def post(self):
|
||||
return 'Create'
|
||||
myview = MyView.as_view('myview')
|
||||
app.add_url_rule('/myview/', methods=['GET'],
|
||||
view_func=myview)
|
||||
app.add_url_rule('/myview/<int:id>', methods=['GET'],
|
||||
view_func=myview)
|
||||
app.add_url_rule('/myview/create', methods=['POST'],
|
||||
view_func=myview)
|
||||
|
||||
with app.test_request_context():
|
||||
self.assert_equal(flask.url_for('myview', _method='GET'),
|
||||
'/myview/')
|
||||
self.assert_equal(flask.url_for('myview', id=42, _method='GET'),
|
||||
'/myview/42')
|
||||
self.assert_equal(flask.url_for('myview', _method='POST'),
|
||||
'/myview/create')
|
||||
|
||||
|
||||
class NoImportsTestCase(FlaskTestCase):
|
||||
"""Test Flasks are created without import.
|
||||
|
||||
Avoiding ``__import__`` helps create Flask instances where there are errors
|
||||
at import time. Those runtime errors will be apparent to the user soon
|
||||
enough, but tools which build Flask instances meta-programmatically benefit
|
||||
from a Flask which does not ``__import__``. Instead of importing to
|
||||
retrieve file paths or metadata on a module or package, use the pkgutil and
|
||||
imp modules in the Python standard library.
|
||||
"""
|
||||
|
||||
def test_name_with_import_error(self):
|
||||
try:
|
||||
flask.Flask('importerror')
|
||||
except NotImplementedError:
|
||||
self.fail('Flask(import_name) is importing import_name.')
|
||||
|
||||
|
||||
class StreamingTestCase(FlaskTestCase):
|
||||
|
||||
def test_streaming_with_context(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.testing = True
|
||||
@app.route('/')
|
||||
def index():
|
||||
def generate():
|
||||
yield 'Hello '
|
||||
yield flask.request.args['name']
|
||||
yield '!'
|
||||
return flask.Response(flask.stream_with_context(generate()))
|
||||
c = app.test_client()
|
||||
rv = c.get('/?name=World')
|
||||
self.assertEqual(rv.data, b'Hello World!')
|
||||
|
||||
def test_streaming_with_context_as_decorator(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.testing = True
|
||||
@app.route('/')
|
||||
def index():
|
||||
@flask.stream_with_context
|
||||
def generate():
|
||||
yield 'Hello '
|
||||
yield flask.request.args['name']
|
||||
yield '!'
|
||||
return flask.Response(generate())
|
||||
c = app.test_client()
|
||||
rv = c.get('/?name=World')
|
||||
self.assertEqual(rv.data, b'Hello World!')
|
||||
|
||||
def test_streaming_with_context_and_custom_close(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.testing = True
|
||||
called = []
|
||||
class Wrapper(object):
|
||||
def __init__(self, gen):
|
||||
self._gen = gen
|
||||
def __iter__(self):
|
||||
return self
|
||||
def close(self):
|
||||
called.append(42)
|
||||
def __next__(self):
|
||||
return next(self._gen)
|
||||
next = __next__
|
||||
@app.route('/')
|
||||
def index():
|
||||
def generate():
|
||||
yield 'Hello '
|
||||
yield flask.request.args['name']
|
||||
yield '!'
|
||||
return flask.Response(flask.stream_with_context(
|
||||
Wrapper(generate())))
|
||||
c = app.test_client()
|
||||
rv = c.get('/?name=World')
|
||||
self.assertEqual(rv.data, b'Hello World!')
|
||||
self.assertEqual(called, [42])
|
||||
|
||||
|
||||
def suite():
|
||||
suite = unittest.TestSuite()
|
||||
if flask.json_available:
|
||||
suite.addTest(unittest.makeSuite(JSONTestCase))
|
||||
suite.addTest(unittest.makeSuite(SendfileTestCase))
|
||||
suite.addTest(unittest.makeSuite(LoggingTestCase))
|
||||
suite.addTest(unittest.makeSuite(NoImportsTestCase))
|
||||
suite.addTest(unittest.makeSuite(StreamingTestCase))
|
||||
return suite
|
116
lib/flask/testsuite/regression.py
Normal file
116
lib/flask/testsuite/regression.py
Normal file
|
@ -0,0 +1,116 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
flask.testsuite.regression
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Tests regressions.
|
||||
|
||||
:copyright: (c) 2011 by Armin Ronacher.
|
||||
:license: BSD, see LICENSE for more details.
|
||||
"""
|
||||
|
||||
import os
|
||||
import gc
|
||||
import sys
|
||||
import flask
|
||||
import threading
|
||||
import unittest
|
||||
from werkzeug.exceptions import NotFound
|
||||
from flask.testsuite import FlaskTestCase
|
||||
|
||||
|
||||
_gc_lock = threading.Lock()
|
||||
|
||||
|
||||
class _NoLeakAsserter(object):
|
||||
|
||||
def __init__(self, testcase):
|
||||
self.testcase = testcase
|
||||
|
||||
def __enter__(self):
|
||||
gc.disable()
|
||||
_gc_lock.acquire()
|
||||
loc = flask._request_ctx_stack._local
|
||||
|
||||
# Force Python to track this dictionary at all times.
|
||||
# This is necessary since Python only starts tracking
|
||||
# dicts if they contain mutable objects. It's a horrible,
|
||||
# horrible hack but makes this kinda testable.
|
||||
loc.__storage__['FOOO'] = [1, 2, 3]
|
||||
|
||||
gc.collect()
|
||||
self.old_objects = len(gc.get_objects())
|
||||
|
||||
def __exit__(self, exc_type, exc_value, tb):
|
||||
if not hasattr(sys, 'getrefcount'):
|
||||
gc.collect()
|
||||
new_objects = len(gc.get_objects())
|
||||
if new_objects > self.old_objects:
|
||||
self.testcase.fail('Example code leaked')
|
||||
_gc_lock.release()
|
||||
gc.enable()
|
||||
|
||||
|
||||
class MemoryTestCase(FlaskTestCase):
|
||||
|
||||
def assert_no_leak(self):
|
||||
return _NoLeakAsserter(self)
|
||||
|
||||
def test_memory_consumption(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template('simple_template.html', whiskey=42)
|
||||
|
||||
def fire():
|
||||
with app.test_client() as c:
|
||||
rv = c.get('/')
|
||||
self.assert_equal(rv.status_code, 200)
|
||||
self.assert_equal(rv.data, b'<h1>42</h1>')
|
||||
|
||||
# Trigger caches
|
||||
fire()
|
||||
|
||||
# This test only works on CPython 2.7.
|
||||
if sys.version_info >= (2, 7) and \
|
||||
not hasattr(sys, 'pypy_translation_info'):
|
||||
with self.assert_no_leak():
|
||||
for x in range(10):
|
||||
fire()
|
||||
|
||||
def test_safe_join_toplevel_pardir(self):
|
||||
from flask.helpers import safe_join
|
||||
with self.assert_raises(NotFound):
|
||||
safe_join('/foo', '..')
|
||||
|
||||
|
||||
class ExceptionTestCase(FlaskTestCase):
|
||||
|
||||
def test_aborting(self):
|
||||
class Foo(Exception):
|
||||
whatever = 42
|
||||
app = flask.Flask(__name__)
|
||||
app.testing = True
|
||||
@app.errorhandler(Foo)
|
||||
def handle_foo(e):
|
||||
return str(e.whatever)
|
||||
@app.route('/')
|
||||
def index():
|
||||
raise flask.abort(flask.redirect(flask.url_for('test')))
|
||||
@app.route('/test')
|
||||
def test():
|
||||
raise Foo()
|
||||
|
||||
with app.test_client() as c:
|
||||
rv = c.get('/')
|
||||
self.assertEqual(rv.headers['Location'], 'http://localhost/test')
|
||||
rv = c.get('/test')
|
||||
self.assertEqual(rv.data, b'42')
|
||||
|
||||
|
||||
def suite():
|
||||
suite = unittest.TestSuite()
|
||||
if os.environ.get('RUN_FLASK_MEMORY_TESTS') == '1':
|
||||
suite.addTest(unittest.makeSuite(MemoryTestCase))
|
||||
suite.addTest(unittest.makeSuite(ExceptionTestCase))
|
||||
return suite
|
185
lib/flask/testsuite/reqctx.py
Normal file
185
lib/flask/testsuite/reqctx.py
Normal file
|
@ -0,0 +1,185 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
flask.testsuite.reqctx
|
||||
~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Tests the request context.
|
||||
|
||||
:copyright: (c) 2012 by Armin Ronacher.
|
||||
:license: BSD, see LICENSE for more details.
|
||||
"""
|
||||
|
||||
import flask
|
||||
import unittest
|
||||
try:
|
||||
from greenlet import greenlet
|
||||
except ImportError:
|
||||
greenlet = None
|
||||
from flask.testsuite import FlaskTestCase
|
||||
|
||||
|
||||
class RequestContextTestCase(FlaskTestCase):
|
||||
|
||||
def test_teardown_on_pop(self):
|
||||
buffer = []
|
||||
app = flask.Flask(__name__)
|
||||
@app.teardown_request
|
||||
def end_of_request(exception):
|
||||
buffer.append(exception)
|
||||
|
||||
ctx = app.test_request_context()
|
||||
ctx.push()
|
||||
self.assert_equal(buffer, [])
|
||||
ctx.pop()
|
||||
self.assert_equal(buffer, [None])
|
||||
|
||||
def test_proper_test_request_context(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.config.update(
|
||||
SERVER_NAME='localhost.localdomain:5000'
|
||||
)
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
return None
|
||||
|
||||
@app.route('/', subdomain='foo')
|
||||
def sub():
|
||||
return None
|
||||
|
||||
with app.test_request_context('/'):
|
||||
self.assert_equal(flask.url_for('index', _external=True), 'http://localhost.localdomain:5000/')
|
||||
|
||||
with app.test_request_context('/'):
|
||||
self.assert_equal(flask.url_for('sub', _external=True), 'http://foo.localhost.localdomain:5000/')
|
||||
|
||||
try:
|
||||
with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}):
|
||||
pass
|
||||
except Exception as e:
|
||||
self.assert_true(isinstance(e, ValueError))
|
||||
self.assert_equal(str(e), "the server name provided " +
|
||||
"('localhost.localdomain:5000') does not match the " + \
|
||||
"server name from the WSGI environment ('localhost')")
|
||||
|
||||
try:
|
||||
app.config.update(SERVER_NAME='localhost')
|
||||
with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}):
|
||||
pass
|
||||
except ValueError as e:
|
||||
raise ValueError(
|
||||
"No ValueError exception should have been raised \"%s\"" % e
|
||||
)
|
||||
|
||||
try:
|
||||
app.config.update(SERVER_NAME='localhost:80')
|
||||
with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}):
|
||||
pass
|
||||
except ValueError as e:
|
||||
raise ValueError(
|
||||
"No ValueError exception should have been raised \"%s\"" % e
|
||||
)
|
||||
|
||||
def test_context_binding(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.route('/')
|
||||
def index():
|
||||
return 'Hello %s!' % flask.request.args['name']
|
||||
@app.route('/meh')
|
||||
def meh():
|
||||
return flask.request.url
|
||||
|
||||
with app.test_request_context('/?name=World'):
|
||||
self.assert_equal(index(), 'Hello World!')
|
||||
with app.test_request_context('/meh'):
|
||||
self.assert_equal(meh(), 'http://localhost/meh')
|
||||
self.assert_true(flask._request_ctx_stack.top is None)
|
||||
|
||||
def test_context_test(self):
|
||||
app = flask.Flask(__name__)
|
||||
self.assert_false(flask.request)
|
||||
self.assert_false(flask.has_request_context())
|
||||
ctx = app.test_request_context()
|
||||
ctx.push()
|
||||
try:
|
||||
self.assert_true(flask.request)
|
||||
self.assert_true(flask.has_request_context())
|
||||
finally:
|
||||
ctx.pop()
|
||||
|
||||
def test_manual_context_binding(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.route('/')
|
||||
def index():
|
||||
return 'Hello %s!' % flask.request.args['name']
|
||||
|
||||
ctx = app.test_request_context('/?name=World')
|
||||
ctx.push()
|
||||
self.assert_equal(index(), 'Hello World!')
|
||||
ctx.pop()
|
||||
try:
|
||||
index()
|
||||
except RuntimeError:
|
||||
pass
|
||||
else:
|
||||
self.assert_true(0, 'expected runtime error')
|
||||
|
||||
def test_greenlet_context_copying(self):
|
||||
app = flask.Flask(__name__)
|
||||
greenlets = []
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
reqctx = flask._request_ctx_stack.top.copy()
|
||||
def g():
|
||||
self.assert_false(flask.request)
|
||||
self.assert_false(flask.current_app)
|
||||
with reqctx:
|
||||
self.assert_true(flask.request)
|
||||
self.assert_equal(flask.current_app, app)
|
||||
self.assert_equal(flask.request.path, '/')
|
||||
self.assert_equal(flask.request.args['foo'], 'bar')
|
||||
self.assert_false(flask.request)
|
||||
return 42
|
||||
greenlets.append(greenlet(g))
|
||||
return 'Hello World!'
|
||||
|
||||
rv = app.test_client().get('/?foo=bar')
|
||||
self.assert_equal(rv.data, b'Hello World!')
|
||||
|
||||
result = greenlets[0].run()
|
||||
self.assert_equal(result, 42)
|
||||
|
||||
def test_greenlet_context_copying_api(self):
|
||||
app = flask.Flask(__name__)
|
||||
greenlets = []
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
reqctx = flask._request_ctx_stack.top.copy()
|
||||
@flask.copy_current_request_context
|
||||
def g():
|
||||
self.assert_true(flask.request)
|
||||
self.assert_equal(flask.current_app, app)
|
||||
self.assert_equal(flask.request.path, '/')
|
||||
self.assert_equal(flask.request.args['foo'], 'bar')
|
||||
return 42
|
||||
greenlets.append(greenlet(g))
|
||||
return 'Hello World!'
|
||||
|
||||
rv = app.test_client().get('/?foo=bar')
|
||||
self.assert_equal(rv.data, b'Hello World!')
|
||||
|
||||
result = greenlets[0].run()
|
||||
self.assert_equal(result, 42)
|
||||
|
||||
# Disable test if we don't have greenlets available
|
||||
if greenlet is None:
|
||||
test_greenlet_context_copying = None
|
||||
test_greenlet_context_copying_api = None
|
||||
|
||||
|
||||
def suite():
|
||||
suite = unittest.TestSuite()
|
||||
suite.addTest(unittest.makeSuite(RequestContextTestCase))
|
||||
return suite
|
153
lib/flask/testsuite/signals.py
Normal file
153
lib/flask/testsuite/signals.py
Normal file
|
@ -0,0 +1,153 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
flask.testsuite.signals
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Signalling.
|
||||
|
||||
:copyright: (c) 2011 by Armin Ronacher.
|
||||
:license: BSD, see LICENSE for more details.
|
||||
"""
|
||||
|
||||
import flask
|
||||
import unittest
|
||||
from flask.testsuite import FlaskTestCase
|
||||
|
||||
|
||||
class SignalsTestCase(FlaskTestCase):
|
||||
|
||||
def test_template_rendered(self):
|
||||
app = flask.Flask(__name__)
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template('simple_template.html', whiskey=42)
|
||||
|
||||
recorded = []
|
||||
def record(sender, template, context):
|
||||
recorded.append((template, context))
|
||||
|
||||
flask.template_rendered.connect(record, app)
|
||||
try:
|
||||
app.test_client().get('/')
|
||||
self.assert_equal(len(recorded), 1)
|
||||
template, context = recorded[0]
|
||||
self.assert_equal(template.name, 'simple_template.html')
|
||||
self.assert_equal(context['whiskey'], 42)
|
||||
finally:
|
||||
flask.template_rendered.disconnect(record, app)
|
||||
|
||||
def test_request_signals(self):
|
||||
app = flask.Flask(__name__)
|
||||
calls = []
|
||||
|
||||
def before_request_signal(sender):
|
||||
calls.append('before-signal')
|
||||
|
||||
def after_request_signal(sender, response):
|
||||
self.assert_equal(response.data, b'stuff')
|
||||
calls.append('after-signal')
|
||||
|
||||
@app.before_request
|
||||
def before_request_handler():
|
||||
calls.append('before-handler')
|
||||
|
||||
@app.after_request
|
||||
def after_request_handler(response):
|
||||
calls.append('after-handler')
|
||||
response.data = 'stuff'
|
||||
return response
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
calls.append('handler')
|
||||
return 'ignored anyway'
|
||||
|
||||
flask.request_started.connect(before_request_signal, app)
|
||||
flask.request_finished.connect(after_request_signal, app)
|
||||
|
||||
try:
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_equal(rv.data, b'stuff')
|
||||
|
||||
self.assert_equal(calls, ['before-signal', 'before-handler',
|
||||
'handler', 'after-handler',
|
||||
'after-signal'])
|
||||
finally:
|
||||
flask.request_started.disconnect(before_request_signal, app)
|
||||
flask.request_finished.disconnect(after_request_signal, app)
|
||||
|
||||
def test_request_exception_signal(self):
|
||||
app = flask.Flask(__name__)
|
||||
recorded = []
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
1 // 0
|
||||
|
||||
def record(sender, exception):
|
||||
recorded.append(exception)
|
||||
|
||||
flask.got_request_exception.connect(record, app)
|
||||
try:
|
||||
self.assert_equal(app.test_client().get('/').status_code, 500)
|
||||
self.assert_equal(len(recorded), 1)
|
||||
self.assert_true(isinstance(recorded[0], ZeroDivisionError))
|
||||
finally:
|
||||
flask.got_request_exception.disconnect(record, app)
|
||||
|
||||
def test_appcontext_signals(self):
|
||||
app = flask.Flask(__name__)
|
||||
recorded = []
|
||||
def record_push(sender, **kwargs):
|
||||
recorded.append('push')
|
||||
def record_pop(sender, **kwargs):
|
||||
recorded.append('push')
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
return 'Hello'
|
||||
|
||||
flask.appcontext_pushed.connect(record_push, app)
|
||||
flask.appcontext_popped.connect(record_pop, app)
|
||||
try:
|
||||
with app.test_client() as c:
|
||||
rv = c.get('/')
|
||||
self.assert_equal(rv.data, b'Hello')
|
||||
self.assert_equal(recorded, ['push'])
|
||||
self.assert_equal(recorded, ['push', 'pop'])
|
||||
finally:
|
||||
flask.appcontext_pushed.disconnect(record_push, app)
|
||||
flask.appcontext_popped.disconnect(record_pop, app)
|
||||
|
||||
def test_flash_signal(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.config['SECRET_KEY'] = 'secret'
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
flask.flash('This is a flash message', category='notice')
|
||||
return flask.redirect('/other')
|
||||
|
||||
recorded = []
|
||||
def record(sender, message, category):
|
||||
recorded.append((message, category))
|
||||
|
||||
flask.message_flashed.connect(record, app)
|
||||
try:
|
||||
client = app.test_client()
|
||||
with client.session_transaction():
|
||||
client.get('/')
|
||||
self.assert_equal(len(recorded), 1)
|
||||
message, category = recorded[0]
|
||||
self.assert_equal(message, 'This is a flash message')
|
||||
self.assert_equal(category, 'notice')
|
||||
finally:
|
||||
flask.message_flashed.disconnect(record, app)
|
||||
|
||||
|
||||
def suite():
|
||||
suite = unittest.TestSuite()
|
||||
if flask.signals_available:
|
||||
suite.addTest(unittest.makeSuite(SignalsTestCase))
|
||||
return suite
|
1
lib/flask/testsuite/static/index.html
Normal file
1
lib/flask/testsuite/static/index.html
Normal file
|
@ -0,0 +1 @@
|
|||
<h1>Hello World!</h1>
|
46
lib/flask/testsuite/subclassing.py
Normal file
46
lib/flask/testsuite/subclassing.py
Normal file
|
@ -0,0 +1,46 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
flask.testsuite.subclassing
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Test that certain behavior of flask can be customized by
|
||||
subclasses.
|
||||
|
||||
:copyright: (c) 2011 by Armin Ronacher.
|
||||
:license: BSD, see LICENSE for more details.
|
||||
"""
|
||||
import flask
|
||||
import unittest
|
||||
from logging import StreamHandler
|
||||
from flask.testsuite import FlaskTestCase
|
||||
from flask._compat import StringIO
|
||||
|
||||
|
||||
class FlaskSubclassingTestCase(FlaskTestCase):
|
||||
|
||||
def test_suppressed_exception_logging(self):
|
||||
class SuppressedFlask(flask.Flask):
|
||||
def log_exception(self, exc_info):
|
||||
pass
|
||||
|
||||
out = StringIO()
|
||||
app = SuppressedFlask(__name__)
|
||||
app.logger_name = 'flask_tests/test_suppressed_exception_logging'
|
||||
app.logger.addHandler(StreamHandler(out))
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
1 // 0
|
||||
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_equal(rv.status_code, 500)
|
||||
self.assert_in(b'Internal Server Error', rv.data)
|
||||
|
||||
err = out.getvalue()
|
||||
self.assert_equal(err, '')
|
||||
|
||||
|
||||
def suite():
|
||||
suite = unittest.TestSuite()
|
||||
suite.addTest(unittest.makeSuite(FlaskSubclassingTestCase))
|
||||
return suite
|
1
lib/flask/testsuite/templates/_macro.html
Normal file
1
lib/flask/testsuite/templates/_macro.html
Normal file
|
@ -0,0 +1 @@
|
|||
{% macro hello(name) %}Hello {{ name }}!{% endmacro %}
|
1
lib/flask/testsuite/templates/context_template.html
Normal file
1
lib/flask/testsuite/templates/context_template.html
Normal file
|
@ -0,0 +1 @@
|
|||
<p>{{ value }}|{{ injected_value }}
|
6
lib/flask/testsuite/templates/escaping_template.html
Normal file
6
lib/flask/testsuite/templates/escaping_template.html
Normal file
|
@ -0,0 +1,6 @@
|
|||
{{ text }}
|
||||
{{ html }}
|
||||
{% autoescape false %}{{ text }}
|
||||
{{ html }}{% endautoescape %}
|
||||
{% autoescape true %}{{ text }}
|
||||
{{ html }}{% endautoescape %}
|
1
lib/flask/testsuite/templates/mail.txt
Normal file
1
lib/flask/testsuite/templates/mail.txt
Normal file
|
@ -0,0 +1 @@
|
|||
{{ foo}} Mail
|
1
lib/flask/testsuite/templates/nested/nested.txt
Normal file
1
lib/flask/testsuite/templates/nested/nested.txt
Normal file
|
@ -0,0 +1 @@
|
|||
I'm nested
|
1
lib/flask/testsuite/templates/simple_template.html
Normal file
1
lib/flask/testsuite/templates/simple_template.html
Normal file
|
@ -0,0 +1 @@
|
|||
<h1>{{ whiskey }}</h1>
|
1
lib/flask/testsuite/templates/template_filter.html
Normal file
1
lib/flask/testsuite/templates/template_filter.html
Normal file
|
@ -0,0 +1 @@
|
|||
{{ value|super_reverse }}
|
3
lib/flask/testsuite/templates/template_test.html
Normal file
3
lib/flask/testsuite/templates/template_test.html
Normal file
|
@ -0,0 +1,3 @@
|
|||
{% if value is boolean %}
|
||||
Success!
|
||||
{% endif %}
|
302
lib/flask/testsuite/templating.py
Normal file
302
lib/flask/testsuite/templating.py
Normal file
|
@ -0,0 +1,302 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
flask.testsuite.templating
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Template functionality
|
||||
|
||||
:copyright: (c) 2011 by Armin Ronacher.
|
||||
:license: BSD, see LICENSE for more details.
|
||||
"""
|
||||
|
||||
import flask
|
||||
import unittest
|
||||
from flask.testsuite import FlaskTestCase
|
||||
|
||||
|
||||
class TemplatingTestCase(FlaskTestCase):
|
||||
|
||||
def test_context_processing(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.context_processor
|
||||
def context_processor():
|
||||
return {'injected_value': 42}
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template('context_template.html', value=23)
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_equal(rv.data, b'<p>23|42')
|
||||
|
||||
def test_original_win(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template_string('{{ config }}', config=42)
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_equal(rv.data, b'42')
|
||||
|
||||
def test_request_less_rendering(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.config['WORLD_NAME'] = 'Special World'
|
||||
@app.context_processor
|
||||
def context_processor():
|
||||
return dict(foo=42)
|
||||
|
||||
with app.app_context():
|
||||
rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} '
|
||||
'{{ foo }}')
|
||||
self.assert_equal(rv, 'Hello Special World 42')
|
||||
|
||||
def test_standard_context(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.secret_key = 'development key'
|
||||
@app.route('/')
|
||||
def index():
|
||||
flask.g.foo = 23
|
||||
flask.session['test'] = 'aha'
|
||||
return flask.render_template_string('''
|
||||
{{ request.args.foo }}
|
||||
{{ g.foo }}
|
||||
{{ config.DEBUG }}
|
||||
{{ session.test }}
|
||||
''')
|
||||
rv = app.test_client().get('/?foo=42')
|
||||
self.assert_equal(rv.data.split(), [b'42', b'23', b'False', b'aha'])
|
||||
|
||||
def test_escaping(self):
|
||||
text = '<p>Hello World!'
|
||||
app = flask.Flask(__name__)
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template('escaping_template.html', text=text,
|
||||
html=flask.Markup(text))
|
||||
lines = app.test_client().get('/').data.splitlines()
|
||||
self.assert_equal(lines, [
|
||||
b'<p>Hello World!',
|
||||
b'<p>Hello World!',
|
||||
b'<p>Hello World!',
|
||||
b'<p>Hello World!',
|
||||
b'<p>Hello World!',
|
||||
b'<p>Hello World!'
|
||||
])
|
||||
|
||||
def test_no_escaping(self):
|
||||
app = flask.Flask(__name__)
|
||||
with app.test_request_context():
|
||||
self.assert_equal(flask.render_template_string('{{ foo }}',
|
||||
foo='<test>'), '<test>')
|
||||
self.assert_equal(flask.render_template('mail.txt', foo='<test>'),
|
||||
'<test> Mail')
|
||||
|
||||
def test_macros(self):
|
||||
app = flask.Flask(__name__)
|
||||
with app.test_request_context():
|
||||
macro = flask.get_template_attribute('_macro.html', 'hello')
|
||||
self.assert_equal(macro('World'), 'Hello World!')
|
||||
|
||||
def test_template_filter(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.template_filter()
|
||||
def my_reverse(s):
|
||||
return s[::-1]
|
||||
self.assert_in('my_reverse', app.jinja_env.filters.keys())
|
||||
self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)
|
||||
self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba')
|
||||
|
||||
def test_add_template_filter(self):
|
||||
app = flask.Flask(__name__)
|
||||
def my_reverse(s):
|
||||
return s[::-1]
|
||||
app.add_template_filter(my_reverse)
|
||||
self.assert_in('my_reverse', app.jinja_env.filters.keys())
|
||||
self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)
|
||||
self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba')
|
||||
|
||||
def test_template_filter_with_name(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.template_filter('strrev')
|
||||
def my_reverse(s):
|
||||
return s[::-1]
|
||||
self.assert_in('strrev', app.jinja_env.filters.keys())
|
||||
self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)
|
||||
self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba')
|
||||
|
||||
def test_add_template_filter_with_name(self):
|
||||
app = flask.Flask(__name__)
|
||||
def my_reverse(s):
|
||||
return s[::-1]
|
||||
app.add_template_filter(my_reverse, 'strrev')
|
||||
self.assert_in('strrev', app.jinja_env.filters.keys())
|
||||
self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)
|
||||
self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba')
|
||||
|
||||
def test_template_filter_with_template(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.template_filter()
|
||||
def super_reverse(s):
|
||||
return s[::-1]
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template('template_filter.html', value='abcd')
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_equal(rv.data, b'dcba')
|
||||
|
||||
def test_add_template_filter_with_template(self):
|
||||
app = flask.Flask(__name__)
|
||||
def super_reverse(s):
|
||||
return s[::-1]
|
||||
app.add_template_filter(super_reverse)
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template('template_filter.html', value='abcd')
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_equal(rv.data, b'dcba')
|
||||
|
||||
def test_template_filter_with_name_and_template(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.template_filter('super_reverse')
|
||||
def my_reverse(s):
|
||||
return s[::-1]
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template('template_filter.html', value='abcd')
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_equal(rv.data, b'dcba')
|
||||
|
||||
def test_add_template_filter_with_name_and_template(self):
|
||||
app = flask.Flask(__name__)
|
||||
def my_reverse(s):
|
||||
return s[::-1]
|
||||
app.add_template_filter(my_reverse, 'super_reverse')
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template('template_filter.html', value='abcd')
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_equal(rv.data, b'dcba')
|
||||
|
||||
def test_template_test(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.template_test()
|
||||
def boolean(value):
|
||||
return isinstance(value, bool)
|
||||
self.assert_in('boolean', app.jinja_env.tests.keys())
|
||||
self.assert_equal(app.jinja_env.tests['boolean'], boolean)
|
||||
self.assert_true(app.jinja_env.tests['boolean'](False))
|
||||
|
||||
def test_add_template_test(self):
|
||||
app = flask.Flask(__name__)
|
||||
def boolean(value):
|
||||
return isinstance(value, bool)
|
||||
app.add_template_test(boolean)
|
||||
self.assert_in('boolean', app.jinja_env.tests.keys())
|
||||
self.assert_equal(app.jinja_env.tests['boolean'], boolean)
|
||||
self.assert_true(app.jinja_env.tests['boolean'](False))
|
||||
|
||||
def test_template_test_with_name(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.template_test('boolean')
|
||||
def is_boolean(value):
|
||||
return isinstance(value, bool)
|
||||
self.assert_in('boolean', app.jinja_env.tests.keys())
|
||||
self.assert_equal(app.jinja_env.tests['boolean'], is_boolean)
|
||||
self.assert_true(app.jinja_env.tests['boolean'](False))
|
||||
|
||||
def test_add_template_test_with_name(self):
|
||||
app = flask.Flask(__name__)
|
||||
def is_boolean(value):
|
||||
return isinstance(value, bool)
|
||||
app.add_template_test(is_boolean, 'boolean')
|
||||
self.assert_in('boolean', app.jinja_env.tests.keys())
|
||||
self.assert_equal(app.jinja_env.tests['boolean'], is_boolean)
|
||||
self.assert_true(app.jinja_env.tests['boolean'](False))
|
||||
|
||||
def test_template_test_with_template(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.template_test()
|
||||
def boolean(value):
|
||||
return isinstance(value, bool)
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template('template_test.html', value=False)
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_in(b'Success!', rv.data)
|
||||
|
||||
def test_add_template_test_with_template(self):
|
||||
app = flask.Flask(__name__)
|
||||
def boolean(value):
|
||||
return isinstance(value, bool)
|
||||
app.add_template_test(boolean)
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template('template_test.html', value=False)
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_in(b'Success!', rv.data)
|
||||
|
||||
def test_template_test_with_name_and_template(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.template_test('boolean')
|
||||
def is_boolean(value):
|
||||
return isinstance(value, bool)
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template('template_test.html', value=False)
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_in(b'Success!', rv.data)
|
||||
|
||||
def test_add_template_test_with_name_and_template(self):
|
||||
app = flask.Flask(__name__)
|
||||
def is_boolean(value):
|
||||
return isinstance(value, bool)
|
||||
app.add_template_test(is_boolean, 'boolean')
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template('template_test.html', value=False)
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_in(b'Success!', rv.data)
|
||||
|
||||
def test_add_template_global(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.template_global()
|
||||
def get_stuff():
|
||||
return 42
|
||||
self.assert_in('get_stuff', app.jinja_env.globals.keys())
|
||||
self.assert_equal(app.jinja_env.globals['get_stuff'], get_stuff)
|
||||
self.assert_true(app.jinja_env.globals['get_stuff'](), 42)
|
||||
with app.app_context():
|
||||
rv = flask.render_template_string('{{ get_stuff() }}')
|
||||
self.assert_equal(rv, '42')
|
||||
|
||||
def test_custom_template_loader(self):
|
||||
class MyFlask(flask.Flask):
|
||||
def create_global_jinja_loader(self):
|
||||
from jinja2 import DictLoader
|
||||
return DictLoader({'index.html': 'Hello Custom World!'})
|
||||
app = MyFlask(__name__)
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template('index.html')
|
||||
c = app.test_client()
|
||||
rv = c.get('/')
|
||||
self.assert_equal(rv.data, b'Hello Custom World!')
|
||||
|
||||
def test_iterable_loader(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.context_processor
|
||||
def context_processor():
|
||||
return {'whiskey': 'Jameson'}
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.render_template(
|
||||
['no_template.xml', # should skip this one
|
||||
'simple_template.html', # should render this
|
||||
'context_template.html'],
|
||||
value=23)
|
||||
|
||||
rv = app.test_client().get('/')
|
||||
self.assert_equal(rv.data, b'<h1>Jameson</h1>')
|
||||
|
||||
|
||||
def suite():
|
||||
suite = unittest.TestSuite()
|
||||
suite.addTest(unittest.makeSuite(TemplatingTestCase))
|
||||
return suite
|
7
lib/flask/testsuite/test_apps/blueprintapp/__init__.py
Normal file
7
lib/flask/testsuite/test_apps/blueprintapp/__init__.py
Normal file
|
@ -0,0 +1,7 @@
|
|||
from flask import Flask
|
||||
|
||||
app = Flask(__name__)
|
||||
from blueprintapp.apps.admin import admin
|
||||
from blueprintapp.apps.frontend import frontend
|
||||
app.register_blueprint(admin)
|
||||
app.register_blueprint(frontend)
|
|
@ -0,0 +1,15 @@
|
|||
from flask import Blueprint, render_template
|
||||
|
||||
admin = Blueprint('admin', __name__, url_prefix='/admin',
|
||||
template_folder='templates',
|
||||
static_folder='static')
|
||||
|
||||
|
||||
@admin.route('/')
|
||||
def index():
|
||||
return render_template('admin/index.html')
|
||||
|
||||
|
||||
@admin.route('/index2')
|
||||
def index2():
|
||||
return render_template('./admin/index.html')
|
|
@ -0,0 +1 @@
|
|||
/* nested file */
|
|
@ -0,0 +1 @@
|
|||
Admin File
|
|
@ -0,0 +1 @@
|
|||
Hello from the Admin
|
|
@ -0,0 +1,8 @@
|
|||
from flask import Blueprint, render_template
|
||||
|
||||
frontend = Blueprint('frontend', __name__, template_folder='templates')
|
||||
|
||||
|
||||
@frontend.route('/')
|
||||
def index():
|
||||
return render_template('frontend/index.html')
|
|
@ -0,0 +1 @@
|
|||
Hello from the Frontend
|
4
lib/flask/testsuite/test_apps/config_module_app.py
Normal file
4
lib/flask/testsuite/test_apps/config_module_app.py
Normal file
|
@ -0,0 +1,4 @@
|
|||
import os
|
||||
import flask
|
||||
here = os.path.abspath(os.path.dirname(__file__))
|
||||
app = flask.Flask(__name__)
|
|
@ -0,0 +1,4 @@
|
|||
import os
|
||||
import flask
|
||||
here = os.path.abspath(os.path.dirname(__file__))
|
||||
app = flask.Flask(__name__)
|
2
lib/flask/testsuite/test_apps/flask_broken/__init__.py
Normal file
2
lib/flask/testsuite/test_apps/flask_broken/__init__.py
Normal file
|
@ -0,0 +1,2 @@
|
|||
import flask.ext.broken.b
|
||||
import missing_module
|
0
lib/flask/testsuite/test_apps/flask_broken/b.py
Normal file
0
lib/flask/testsuite/test_apps/flask_broken/b.py
Normal file
|
@ -0,0 +1 @@
|
|||
ext_id = 'newext_package'
|
|
@ -0,0 +1,2 @@
|
|||
def test_function():
|
||||
return 42
|
1
lib/flask/testsuite/test_apps/flask_newext_simple.py
Normal file
1
lib/flask/testsuite/test_apps/flask_newext_simple.py
Normal file
|
@ -0,0 +1 @@
|
|||
ext_id = 'newext_simple'
|
0
lib/flask/testsuite/test_apps/flaskext/__init__.py
Normal file
0
lib/flask/testsuite/test_apps/flaskext/__init__.py
Normal file
|
@ -0,0 +1 @@
|
|||
ext_id = 'oldext_package'
|
|
@ -0,0 +1,2 @@
|
|||
def test_function():
|
||||
return 42
|
1
lib/flask/testsuite/test_apps/flaskext/oldext_simple.py
Normal file
1
lib/flask/testsuite/test_apps/flaskext/oldext_simple.py
Normal file
|
@ -0,0 +1 @@
|
|||
ext_id = 'oldext_simple'
|
2
lib/flask/testsuite/test_apps/importerror.py
Normal file
2
lib/flask/testsuite/test_apps/importerror.py
Normal file
|
@ -0,0 +1,2 @@
|
|||
# NoImportsTestCase
|
||||
raise NotImplementedError
|
Binary file not shown.
|
@ -0,0 +1,3 @@
|
|||
import flask
|
||||
|
||||
app = flask.Flask(__name__)
|
|
@ -0,0 +1,3 @@
|
|||
import flask
|
||||
|
||||
app = flask.Flask(__name__)
|
4
lib/flask/testsuite/test_apps/main_app.py
Normal file
4
lib/flask/testsuite/test_apps/main_app.py
Normal file
|
@ -0,0 +1,4 @@
|
|||
import flask
|
||||
|
||||
# Test Flask initialization with main module.
|
||||
app = flask.Flask('__main__')
|
7
lib/flask/testsuite/test_apps/moduleapp/__init__.py
Normal file
7
lib/flask/testsuite/test_apps/moduleapp/__init__.py
Normal file
|
@ -0,0 +1,7 @@
|
|||
from flask import Flask
|
||||
|
||||
app = Flask(__name__)
|
||||
from moduleapp.apps.admin import admin
|
||||
from moduleapp.apps.frontend import frontend
|
||||
app.register_module(admin)
|
||||
app.register_module(frontend)
|
0
lib/flask/testsuite/test_apps/moduleapp/apps/__init__.py
Normal file
0
lib/flask/testsuite/test_apps/moduleapp/apps/__init__.py
Normal file
|
@ -0,0 +1,14 @@
|
|||
from flask import Module, render_template
|
||||
|
||||
|
||||
admin = Module(__name__, url_prefix='/admin')
|
||||
|
||||
|
||||
@admin.route('/')
|
||||
def index():
|
||||
return render_template('admin/index.html')
|
||||
|
||||
|
||||
@admin.route('/index2')
|
||||
def index2():
|
||||
return render_template('./admin/index.html')
|
|
@ -0,0 +1 @@
|
|||
/* nested file */
|
|
@ -0,0 +1 @@
|
|||
Admin File
|
|
@ -0,0 +1 @@
|
|||
Hello from the Admin
|
|
@ -0,0 +1,9 @@
|
|||
from flask import Module, render_template
|
||||
|
||||
|
||||
frontend = Module(__name__)
|
||||
|
||||
|
||||
@frontend.route('/')
|
||||
def index():
|
||||
return render_template('frontend/index.html')
|
|
@ -0,0 +1 @@
|
|||
Hello from the Frontend
|
|
@ -0,0 +1,3 @@
|
|||
import flask
|
||||
|
||||
app = flask.Flask(__name__)
|
|
@ -0,0 +1,4 @@
|
|||
from flask import Module
|
||||
|
||||
|
||||
mod = Module(__name__, 'foo', subdomain='foo')
|
|
@ -0,0 +1 @@
|
|||
Hello Subdomain
|
242
lib/flask/testsuite/testing.py
Normal file
242
lib/flask/testsuite/testing.py
Normal file
|
@ -0,0 +1,242 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
flask.testsuite.testing
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Test client and more.
|
||||
|
||||
:copyright: (c) 2011 by Armin Ronacher.
|
||||
:license: BSD, see LICENSE for more details.
|
||||
"""
|
||||
|
||||
import flask
|
||||
import unittest
|
||||
from flask.testsuite import FlaskTestCase
|
||||
from flask._compat import text_type
|
||||
|
||||
|
||||
class TestToolsTestCase(FlaskTestCase):
|
||||
|
||||
def test_environ_defaults_from_config(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.testing = True
|
||||
app.config['SERVER_NAME'] = 'example.com:1234'
|
||||
app.config['APPLICATION_ROOT'] = '/foo'
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.request.url
|
||||
|
||||
ctx = app.test_request_context()
|
||||
self.assert_equal(ctx.request.url, 'http://example.com:1234/foo/')
|
||||
with app.test_client() as c:
|
||||
rv = c.get('/')
|
||||
self.assert_equal(rv.data, b'http://example.com:1234/foo/')
|
||||
|
||||
def test_environ_defaults(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.testing = True
|
||||
@app.route('/')
|
||||
def index():
|
||||
return flask.request.url
|
||||
|
||||
ctx = app.test_request_context()
|
||||
self.assert_equal(ctx.request.url, 'http://localhost/')
|
||||
with app.test_client() as c:
|
||||
rv = c.get('/')
|
||||
self.assert_equal(rv.data, b'http://localhost/')
|
||||
|
||||
def test_redirect_keep_session(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.secret_key = 'testing'
|
||||
|
||||
@app.route('/', methods=['GET', 'POST'])
|
||||
def index():
|
||||
if flask.request.method == 'POST':
|
||||
return flask.redirect('/getsession')
|
||||
flask.session['data'] = 'foo'
|
||||
return 'index'
|
||||
|
||||
@app.route('/getsession')
|
||||
def get_session():
|
||||
return flask.session.get('data', '<missing>')
|
||||
|
||||
with app.test_client() as c:
|
||||
rv = c.get('/getsession')
|
||||
assert rv.data == b'<missing>'
|
||||
|
||||
rv = c.get('/')
|
||||
assert rv.data == b'index'
|
||||
assert flask.session.get('data') == 'foo'
|
||||
rv = c.post('/', data={}, follow_redirects=True)
|
||||
assert rv.data == b'foo'
|
||||
|
||||
# This support requires a new Werkzeug version
|
||||
if not hasattr(c, 'redirect_client'):
|
||||
assert flask.session.get('data') == 'foo'
|
||||
|
||||
rv = c.get('/getsession')
|
||||
assert rv.data == b'foo'
|
||||
|
||||
def test_session_transactions(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.testing = True
|
||||
app.secret_key = 'testing'
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
return text_type(flask.session['foo'])
|
||||
|
||||
with app.test_client() as c:
|
||||
with c.session_transaction() as sess:
|
||||
self.assert_equal(len(sess), 0)
|
||||
sess['foo'] = [42]
|
||||
self.assert_equal(len(sess), 1)
|
||||
rv = c.get('/')
|
||||
self.assert_equal(rv.data, b'[42]')
|
||||
with c.session_transaction() as sess:
|
||||
self.assert_equal(len(sess), 1)
|
||||
self.assert_equal(sess['foo'], [42])
|
||||
|
||||
def test_session_transactions_no_null_sessions(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.testing = True
|
||||
|
||||
with app.test_client() as c:
|
||||
try:
|
||||
with c.session_transaction() as sess:
|
||||
pass
|
||||
except RuntimeError as e:
|
||||
self.assert_in('Session backend did not open a session', str(e))
|
||||
else:
|
||||
self.fail('Expected runtime error')
|
||||
|
||||
def test_session_transactions_keep_context(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.testing = True
|
||||
app.secret_key = 'testing'
|
||||
|
||||
with app.test_client() as c:
|
||||
rv = c.get('/')
|
||||
req = flask.request._get_current_object()
|
||||
self.assert_true(req is not None)
|
||||
with c.session_transaction():
|
||||
self.assert_true(req is flask.request._get_current_object())
|
||||
|
||||
def test_session_transaction_needs_cookies(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.testing = True
|
||||
c = app.test_client(use_cookies=False)
|
||||
try:
|
||||
with c.session_transaction() as s:
|
||||
pass
|
||||
except RuntimeError as e:
|
||||
self.assert_in('cookies', str(e))
|
||||
else:
|
||||
self.fail('Expected runtime error')
|
||||
|
||||
def test_test_client_context_binding(self):
|
||||
app = flask.Flask(__name__)
|
||||
@app.route('/')
|
||||
def index():
|
||||
flask.g.value = 42
|
||||
return 'Hello World!'
|
||||
|
||||
@app.route('/other')
|
||||
def other():
|
||||
1 // 0
|
||||
|
||||
with app.test_client() as c:
|
||||
resp = c.get('/')
|
||||
self.assert_equal(flask.g.value, 42)
|
||||
self.assert_equal(resp.data, b'Hello World!')
|
||||
self.assert_equal(resp.status_code, 200)
|
||||
|
||||
resp = c.get('/other')
|
||||
self.assert_false(hasattr(flask.g, 'value'))
|
||||
self.assert_in(b'Internal Server Error', resp.data)
|
||||
self.assert_equal(resp.status_code, 500)
|
||||
flask.g.value = 23
|
||||
|
||||
try:
|
||||
flask.g.value
|
||||
except (AttributeError, RuntimeError):
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('some kind of exception expected')
|
||||
|
||||
def test_reuse_client(self):
|
||||
app = flask.Flask(__name__)
|
||||
c = app.test_client()
|
||||
|
||||
with c:
|
||||
self.assert_equal(c.get('/').status_code, 404)
|
||||
|
||||
with c:
|
||||
self.assert_equal(c.get('/').status_code, 404)
|
||||
|
||||
def test_test_client_calls_teardown_handlers(self):
|
||||
app = flask.Flask(__name__)
|
||||
called = []
|
||||
@app.teardown_request
|
||||
def remember(error):
|
||||
called.append(error)
|
||||
|
||||
with app.test_client() as c:
|
||||
self.assert_equal(called, [])
|
||||
c.get('/')
|
||||
self.assert_equal(called, [])
|
||||
self.assert_equal(called, [None])
|
||||
|
||||
del called[:]
|
||||
with app.test_client() as c:
|
||||
self.assert_equal(called, [])
|
||||
c.get('/')
|
||||
self.assert_equal(called, [])
|
||||
c.get('/')
|
||||
self.assert_equal(called, [None])
|
||||
self.assert_equal(called, [None, None])
|
||||
|
||||
|
||||
class SubdomainTestCase(FlaskTestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.app = flask.Flask(__name__)
|
||||
self.app.config['SERVER_NAME'] = 'example.com'
|
||||
self.client = self.app.test_client()
|
||||
|
||||
self._ctx = self.app.test_request_context()
|
||||
self._ctx.push()
|
||||
|
||||
def tearDown(self):
|
||||
if self._ctx is not None:
|
||||
self._ctx.pop()
|
||||
|
||||
def test_subdomain(self):
|
||||
@self.app.route('/', subdomain='<company_id>')
|
||||
def view(company_id):
|
||||
return company_id
|
||||
|
||||
url = flask.url_for('view', company_id='xxx')
|
||||
response = self.client.get(url)
|
||||
|
||||
self.assert_equal(200, response.status_code)
|
||||
self.assert_equal(b'xxx', response.data)
|
||||
|
||||
|
||||
def test_nosubdomain(self):
|
||||
@self.app.route('/<company_id>')
|
||||
def view(company_id):
|
||||
return company_id
|
||||
|
||||
url = flask.url_for('view', company_id='xxx')
|
||||
response = self.client.get(url)
|
||||
|
||||
self.assert_equal(200, response.status_code)
|
||||
self.assert_equal(b'xxx', response.data)
|
||||
|
||||
|
||||
def suite():
|
||||
suite = unittest.TestSuite()
|
||||
suite.addTest(unittest.makeSuite(TestToolsTestCase))
|
||||
suite.addTest(unittest.makeSuite(SubdomainTestCase))
|
||||
return suite
|
169
lib/flask/testsuite/views.py
Normal file
169
lib/flask/testsuite/views.py
Normal file
|
@ -0,0 +1,169 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
flask.testsuite.views
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Pluggable views.
|
||||
|
||||
:copyright: (c) 2011 by Armin Ronacher.
|
||||
:license: BSD, see LICENSE for more details.
|
||||
"""
|
||||
|
||||
import flask
|
||||
import flask.views
|
||||
import unittest
|
||||
from flask.testsuite import FlaskTestCase
|
||||
from werkzeug.http import parse_set_header
|
||||
|
||||
class ViewTestCase(FlaskTestCase):
|
||||
|
||||
def common_test(self, app):
|
||||
c = app.test_client()
|
||||
|
||||
self.assert_equal(c.get('/').data, b'GET')
|
||||
self.assert_equal(c.post('/').data, b'POST')
|
||||
self.assert_equal(c.put('/').status_code, 405)
|
||||
meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])
|
||||
self.assert_equal(sorted(meths), ['GET', 'HEAD', 'OPTIONS', 'POST'])
|
||||
|
||||
def test_basic_view(self):
|
||||
app = flask.Flask(__name__)
|
||||
|
||||
class Index(flask.views.View):
|
||||
methods = ['GET', 'POST']
|
||||
def dispatch_request(self):
|
||||
return flask.request.method
|
||||
|
||||
app.add_url_rule('/', view_func=Index.as_view('index'))
|
||||
self.common_test(app)
|
||||
|
||||
def test_method_based_view(self):
|
||||
app = flask.Flask(__name__)
|
||||
|
||||
class Index(flask.views.MethodView):
|
||||
def get(self):
|
||||
return 'GET'
|
||||
def post(self):
|
||||
return 'POST'
|
||||
|
||||
app.add_url_rule('/', view_func=Index.as_view('index'))
|
||||
|
||||
self.common_test(app)
|
||||
|
||||
def test_view_patching(self):
|
||||
app = flask.Flask(__name__)
|
||||
|
||||
class Index(flask.views.MethodView):
|
||||
def get(self):
|
||||
1 // 0
|
||||
def post(self):
|
||||
1 // 0
|
||||
|
||||
class Other(Index):
|
||||
def get(self):
|
||||
return 'GET'
|
||||
def post(self):
|
||||
return 'POST'
|
||||
|
||||
view = Index.as_view('index')
|
||||
view.view_class = Other
|
||||
app.add_url_rule('/', view_func=view)
|
||||
self.common_test(app)
|
||||
|
||||
def test_view_inheritance(self):
|
||||
app = flask.Flask(__name__)
|
||||
|
||||
class Index(flask.views.MethodView):
|
||||
def get(self):
|
||||
return 'GET'
|
||||
def post(self):
|
||||
return 'POST'
|
||||
|
||||
class BetterIndex(Index):
|
||||
def delete(self):
|
||||
return 'DELETE'
|
||||
|
||||
app.add_url_rule('/', view_func=BetterIndex.as_view('index'))
|
||||
c = app.test_client()
|
||||
|
||||
meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])
|
||||
self.assert_equal(sorted(meths), ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST'])
|
||||
|
||||
def test_view_decorators(self):
|
||||
app = flask.Flask(__name__)
|
||||
|
||||
def add_x_parachute(f):
|
||||
def new_function(*args, **kwargs):
|
||||
resp = flask.make_response(f(*args, **kwargs))
|
||||
resp.headers['X-Parachute'] = 'awesome'
|
||||
return resp
|
||||
return new_function
|
||||
|
||||
class Index(flask.views.View):
|
||||
decorators = [add_x_parachute]
|
||||
def dispatch_request(self):
|
||||
return 'Awesome'
|
||||
|
||||
app.add_url_rule('/', view_func=Index.as_view('index'))
|
||||
c = app.test_client()
|
||||
rv = c.get('/')
|
||||
self.assert_equal(rv.headers['X-Parachute'], 'awesome')
|
||||
self.assert_equal(rv.data, b'Awesome')
|
||||
|
||||
def test_implicit_head(self):
|
||||
app = flask.Flask(__name__)
|
||||
|
||||
class Index(flask.views.MethodView):
|
||||
def get(self):
|
||||
return flask.Response('Blub', headers={
|
||||
'X-Method': flask.request.method
|
||||
})
|
||||
|
||||
app.add_url_rule('/', view_func=Index.as_view('index'))
|
||||
c = app.test_client()
|
||||
rv = c.get('/')
|
||||
self.assert_equal(rv.data, b'Blub')
|
||||
self.assert_equal(rv.headers['X-Method'], 'GET')
|
||||
rv = c.head('/')
|
||||
self.assert_equal(rv.data, b'')
|
||||
self.assert_equal(rv.headers['X-Method'], 'HEAD')
|
||||
|
||||
def test_explicit_head(self):
|
||||
app = flask.Flask(__name__)
|
||||
|
||||
class Index(flask.views.MethodView):
|
||||
def get(self):
|
||||
return 'GET'
|
||||
def head(self):
|
||||
return flask.Response('', headers={'X-Method': 'HEAD'})
|
||||
|
||||
app.add_url_rule('/', view_func=Index.as_view('index'))
|
||||
c = app.test_client()
|
||||
rv = c.get('/')
|
||||
self.assert_equal(rv.data, b'GET')
|
||||
rv = c.head('/')
|
||||
self.assert_equal(rv.data, b'')
|
||||
self.assert_equal(rv.headers['X-Method'], 'HEAD')
|
||||
|
||||
def test_endpoint_override(self):
|
||||
app = flask.Flask(__name__)
|
||||
app.debug = True
|
||||
|
||||
class Index(flask.views.View):
|
||||
methods = ['GET', 'POST']
|
||||
def dispatch_request(self):
|
||||
return flask.request.method
|
||||
|
||||
app.add_url_rule('/', view_func=Index.as_view('index'))
|
||||
|
||||
with self.assert_raises(AssertionError):
|
||||
app.add_url_rule('/', view_func=Index.as_view('index'))
|
||||
|
||||
# But these tests should still pass. We just log a warning.
|
||||
self.common_test(app)
|
||||
|
||||
|
||||
def suite():
|
||||
suite = unittest.TestSuite()
|
||||
suite.addTest(unittest.makeSuite(ViewTestCase))
|
||||
return suite
|
Loading…
Add table
Add a link
Reference in a new issue