Merge remote-tracking branch 'mitsuhiko/master'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Pedro Algarvio · committed by Pedro Algarvio · parents 03a71e0, ccf4641 · Browse files · 93 files·+3657 added−2827 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
93 files+3657 added−2827 removed
- tests:+0 added−2709 removed
- other:+3657 added−118 removed
Provenance
- Commit
a9e09ec- Tree
89493b7- Author
Pedro Algarvio <pedro@algarvio.me>- Committer
Pedro Algarvio <pedro@algarvio.me>- Parent 1
03a71e0- Parent 2
ccf4641
93 files changed+3657 added−2827 removed
modified:docs/patterns/sqlite3.rst+9 added-1 removed
22 unmodified lines23 g.db = connect_db()24 25 @app.teardown_request26 def teardown_request(exception):27+ if hasattr(g, 'db'):27- g.db.close()28+ g.db.close()29 30+.. note::31+32+ Please keep in mind that the teardown request functions are always33+ executed, even if a before-request handler failed or was never34+ executed. Because of this we have to make sure here that the database35+ is there before we close it.36+37 Connect on Demand38 -----------------39 40 The downside of this approach is that this will only work if Flask79 unmodified linesmodified:docs/api.rst+9 added
216 unmodified lines217 .. autoclass:: SessionMixin218 :members:219 220 221+Test Client222+-----------223+224+.. currentmodule:: flask.testing225+226+.. autoclass:: FlaskClient227+ :members:228+229+230 Application Globals231 -------------------232 233 .. currentmodule:: flask270 unmodified linesmodified:docs/config.rst+45 added-9 removed
68 unmodified lines69 debug production applications (but also70 very risky).71 ``SECRET_KEY`` the secret key72 ``SESSION_COOKIE_NAME`` the name of the session cookie73+``SESSION_COOKIE_DOMAIN`` the domain for the session cookie. If74+ this is not set, the cookie will be75+ valid for all subdomains of76+ ``SERVER_NAME``.77+``SESSION_COOKIE_PATH`` the path for the session cookie. If78+ this is not set the cookie will be valid79+ for all of ``APPLICATION_ROOT`` or if80+ that is not set for ``'/'``.81+``SESSION_COOKIE_HTTPONLY`` controls if the cookie should be set82+ with the httponly flag. Defaults to83+ `True`.84+``SESSION_COOKIE_SECURE`` controls if the cookie should be set85+ with the secure flag. Defaults to86+ `False`.87 ``PERMANENT_SESSION_LIFETIME`` the lifetime of a permanent session as88 :class:`datetime.timedelta` object.89 ``USE_X_SENDFILE`` enable/disable x-sendfile90 ``LOGGER_NAME`` the name of the logger91 ``SERVER_NAME`` the name and port number of the server.92 Required for subdomain support (e.g.:93 ``'localhost:5000'``)94+``APPLICATION_ROOT`` If the application does not occupy95+ a whole domain or subdomain this can96+ be set to the path where the application97+ is configured to live. This is for98+ session cookie as path value. If99+ domains are used, this should be100+ ``None``.101 ``MAX_CONTENT_LENGTH`` If set to a value in bytes, Flask will102 reject incoming requests with a103 content length greater than this by104 returning a 413 status code.49 unmodified lines154 .. versionadded:: 0.7155 ``PROPAGATE_EXCEPTIONS``, ``PRESERVE_CONTEXT_ON_EXCEPTION``156 157 .. versionadded:: 0.8137- ``TRAP_BAD_REQUEST_ERRORS``, ``TRAP_HTTP_EXCEPTIONS``158+ ``TRAP_BAD_REQUEST_ERRORS``, ``TRAP_HTTP_EXCEPTIONS``,159+ ``APPLICATION_ROOT``, ``SESSION_COOKIE_DOMAIN``,160+ ``SESSION_COOKIE_PATH``, ``SESSION_COOKIE_HTTPONLY``,161+ ``SESSION_COOKIE_SECURE``162 163 Configuring from Files164 ----------------------165 148 unmodified lines314 “instance folder”. The instance folder is designed to not be under315 version control and be deployment specific. It's the perfect place to316 drop things that either change at runtime or configuration files.317 294-To make it easier to put this folder into an ignore list for your version295-control system it's called ``instance`` and placed directly next to your296-package or module by default. This path can be overridden by specifying297-the `instance_path` parameter to your application::318+You can either explicitly provide the path of the instance folder when319+creating the Flask application or you can let Flask autodetect the320+instance folder. For explicit configuration use the `instance_path`321+parameter::322 323 app = Flask(__name__, instance_path='/path/to/instance/folder')324 301-Default locations::325+Please keep in mind that this path *must* be absolute when provided.326 303- Module situation:327+If the `instance_path` parameter is not provided the following default328+locations are used:329+330+- Uninstalled module::331+332 /myapp.py333 /instance334 307- Package situation:335+- Uninstalled package::336+337 /myapp338 /__init__.py339 /instance340 312-Please keep in mind that this path *must* be absolute when provided.341+- Installed module or package::342 343+ $PREFIX/lib/python2.X/site-packages/myapp344+ $PREFIX/var/myapp-instance345+346+ ``$PREFIX`` is the prefix of your Python installation. This can be347+ ``/usr`` or the path to your virtualenv. You can print the value of348+ ``sys.prefix`` to see what the prefix is set to.349+350 Since the config object provided loading of configuration files from351 relative filenames we made it possible to change the loading via filenames352 to be relative to the instance path if wanted. The behavior of relative353 paths in config files can be flipped between “relative to the application26 unmodified linesmodified:docs/design.rst+16 added
77 unmodified lines78 Furthermore this design makes it possible to use a factory function to79 create the application which is very helpful for unittesting and similar80 things (:ref:`app-factories`).81 82+The Routing System83+------------------84+85+Flask uses the Werkzeug routing system which has was designed to86+automatically order routes by complexity. This means that you can declare87+routes in arbitrary order and they will still work as expected. This is a88+requirement if you want to properly implement decorator based routing89+since decorators could be fired in undefined order when the application is90+split into multiple modules.91+92+Another design decision with the Werkzeug routing system is that routes93+in Werkzeug try to ensure that there is that URLs are unique. Werkzeug94+will go quite far with that in that it will automatically redirect to a95+canonical URL if a route is ambiguous.96+97+98 One Template Engine99 -------------------100 101 Flask decides on one template engine: Jinja2. Why doesn't Flask have a90 unmodified linesmodified:docs/foreword.rst+23 added-27 removed
7 unmodified lines8 What does "micro" mean?9 -----------------------10 11 To me, the "micro" in microframework refers not only to the simplicity and12-small size of the framework, but also to the typically limited complexity13-and size of applications that are written with the framework. Also the14-fact that you can have an entire application in a single Python file. To15-be approachable and concise, a microframework sacrifices a few features16-that may be necessary in larger or more complex applications.12+small size of the framework, but also the fact that it does not make much13+decisions for you. While Flask does pick a templating engine for you, we14+won't make such decisions for your datastore or other parts.15 18-For example, Flask uses thread-local objects internally so that you don't19-have to pass objects around from function to function within a request in20-order to stay threadsafe. While this is a really easy approach and saves21-you a lot of time, it might also cause some troubles for very large22-applications because changes on these thread-local objects can happen23-anywhere in the same thread.16+For us however the term “micro” does not mean that the whole implementation17+has to fit into a single Python file.18 25-Flask provides some tools to deal with the downsides of this approach but26-it might be an issue for larger applications because in theory27-modifications on these objects might happen anywhere in the same thread.19+One of the design decisions with Flask was that simple tasks should be20+simple and not take up a lot of code and yet not limit yourself. Because21+of that we took a few design choices that some people might find22+surprising or unorthodox. For example, Flask uses thread-local objects23+internally so that you don't have to pass objects around from function to24+function within a request in order to stay threadsafe. While this is a25+really easy approach and saves you a lot of time, it might also cause some26+troubles for very large applications because changes on these thread-local27+objects can happen anywhere in the same thread. In order to solve these28+problems we don't hide the thread locals for you but instead embrace them29+and provide you with a lot of tools to make it as pleasant as possible to30+work with them.31 32 Flask is also based on convention over configuration, which means that33 many things are preconfigured. For example, by convention, templates and34 static files are in subdirectories within the Python source tree of the32-application.35+application. While this can be changed you usually don't have to.36 37 The main reason however why Flask is called a "microframework" is the idea38 to keep the core simple but extensible. There is no database abstraction39 layer, no form validation or anything else where different libraries2 unmodified lines42 was implemented in Flask itself. There are currently extensions for43 object relational mappers, form validation, upload handling, various open44 authentication technologies and more.45 43-However Flask is not much code and it is built on a very solid foundation44-and with that it is very easy to adapt for large applications. If you are45-interested in that, check out the :ref:`becomingbig` chapter.46+Since Flask is based on a very solid foundation there is not a lot of code47+in Flask itself. As such it's easy to adapt even for lage applications48+and we are making sure that you can either configure it as much as49+possible by subclassing things or by forking the entire codebase. If you50+are interested in that, check out the :ref:`becomingbig` chapter.51 52 If you are curious about the Flask design principles, head over to the53 section about :ref:`design`.54 50-A Framework and an Example51---------------------------52-53-Flask is not only a microframework; it is also an example. Based on54-Flask, there will be a series of blog posts that explain how to create a55-framework. Flask itself is just one way to implement a framework on top56-of existing libraries. Unlike many other microframeworks, Flask does not57-try to implement everything on its own; it reuses existing code.58-55 Web Development is Dangerous56 ----------------------------57 58 I'm not joking. Well, maybe a little. If you write a web42 unmodified linesmodified:docs/reqcontext.rst+9 added-1 removed
129 unmodified lines130 functions which have the chance to replace it or modify it in place.131 132 4. At the end of the request the :meth:`~flask.Flask.teardown_request`133 functions are executed. This always happens, even in case of an134- unhandled exception down the road.134+ unhandled exception down the road or if a before-request handler was135+ not executed yet or at all (for example in test environments sometimes136+ you might want to not execute before-request callbacks).137 138 Now what happens on errors? In production mode if an exception is not139 caught, the 500 internal server handler is called. In development mode140 however the exception is not further processed and bubbles up to the WSGI43 unmodified lines184 >>> ctx.pop()185 this runs after request186 >>>187 188+Keep in mind that teardown callbacks are always executed, even if189+before-request callbacks were not executed yet but an exception happened.190+Certain parts of the test system might also temporarily create a request191+context without calling the before-request handlers. Make sure to write192+your teardown-request handlers in a way that they will never fail.193+194 .. _notes-on-proxies:195 196 Notes On Proxies197 ----------------42 unmodified linesmodified:docs/testing.rst+32 added
271 unmodified lines272 is no longer available (because you are trying to use it outside of the actual request).273 However, keep in mind that any :meth:`~flask.Flask.after_request` functions274 are already called at this point so your database connection and275 everything involved is probably already closed down.276+277+278+Accessing and Modifying Sessions279+--------------------------------280+281+.. versionadded:: 0.8282+283+Sometimes it can be very helpful to access or modify the sessions from the284+test client. Generally there are two ways for this. If you just want to285+ensure that a session has certain keys set to certain values you can just286+keep the context around and access :data:`flask.session`::287+288+ with app.test_client() as c:289+ rv = c.get('/')290+ assert flask.session['foo'] == 42291+292+This however does not make it possible to also modify the session or to293+access the session before a request was fired. Starting with Flask 0.8 we294+provide a so called “session transaction” which simulates the appropriate295+calls to open a session in the context of the test client and to modify296+it. At the end of the transaction the session is stored. This works297+independently of the session backend used::298+299+ with app.test_client() as c:300+ with c.session_transaction() as sess:301+ sess['a_key'] = 'a value'302+303+ # once this is reached the session was stored304+305+Note that in this case you have to use the ``sess`` object instead of the306+:data:`flask.session` proxy. The object however itself will provide the307+same interface.modified:docs/upgrading.rst+7 added-1 removed
34 unmodified lines35 longer have to handle that error to avoid an internal server error showing36 up for the user. If you were catching this down explicitly in the past37 as `ValueError` you will need to change this.38 39+Due to a bug in the test client Flask 0.7 did not trigger teardown40+handlers when the test client was used in a with statement. This was41+since fixed but might require some changes in your testsuites if you42+relied on this behavior.43+44 Version 0.745 -----------46 47 In Flask 0.7 we cleaned up the code base internally a lot and did some98 unmodified lines146 You are now encouraged to use this instead::147 148 @app.teardown_request149 def after_request(exception):150+ if hasattr(g, 'db'):145- g.db.close()151+ g.db.close()152 153 On the upside this change greatly improves the internal code flow and154 makes it easier to customize the dispatching and error handling. This155 makes it now a lot easier to write unit tests as you can prevent closing169 unmodified linesmodified:docs/views.rst+21 added
133 unmodified lines134 135 That way you also don't have to provide the136 :attr:`~flask.views.View.methods` attribute. It's automatically set based137 on the methods defined in the class.138+139+Decorating Views140+----------------141+142+Since the view class itself is not the view function that is added to the143+routing system it does not make much sense to decorate the class itself.144+Instead you either have to decorate the return value of145+:meth:`~flask.views.View.as_view` by hand::146+147+ view = rate_limited(UserAPI.as_view('users'))148+ app.add_url_rule('/users/', view_func=view)149+150+Starting with Flask 0.8 there is also an alternative way where you can151+specify a list of decorators to apply in the class declaration::152+153+ class UserAPI(MethodView):154+ decorators = [rate_limited]155+156+Due to the implicit self from the caller's perspective you cannot use157+regular view decorators on the individual methods of the view however,158+keep this in mind.modified:examples/flaskr/flaskr.py+2 added-1 removed
48 unmodified lines49 50 @app.teardown_request51 def teardown_request(exception):52 """Closes the database again at the end of the request."""53+ if hasattr(g, 'db'):53- g.db.close()54+ g.db.close()55 56 57 @app.route('/')58 def show_entries():40 unmodified linesmodified:examples/minitwit/minitwit.py+2 added-1 removed
83 unmodified lines84 85 @app.teardown_request86 def teardown_request(exception):87 """Closes the database again at the end of the request."""88+ if hasattr(g, 'db'):88- g.db.close()89+ g.db.close()90 91 92 @app.route('/')93 def timeline():155 unmodified linesadded:flask/testsuite/static/index.html+1 added
1+<h1>Hello World!</h1>added:flask/testsuite/templates/nested/nested.txt+1 added
1+I'm nestedadded:flask/testsuite/templates/_macro.html+1 added
1+{% macro hello(name) %}Hello {{ name }}!{% endmacro %}added:flask/testsuite/templates/context_template.html+1 added
1+<p>{{ value }}|{{ injected_value }}added:flask/testsuite/templates/escaping_template.html+6 added
1+{{ text }}2+{{ html }}3+{% autoescape false %}{{ text }}4+{{ html }}{% endautoescape %}5+{% autoescape true %}{{ text }}6+{{ html }}{% endautoescape %}added:flask/testsuite/templates/mail.txt+1 added
1+{{ foo}} Mailadded:flask/testsuite/templates/simple_template.html+1 added
1+<h1>{{ whiskey }}</h1>added:flask/testsuite/templates/template_filter.html+1 added
1+{{ value|super_reverse }}added:flask/testsuite/test_apps/blueprintapp/apps/admin/static/css/test.css+1 added
1+/* nested file */added:flask/testsuite/test_apps/blueprintapp/apps/admin/static/test.txt+1 added
1+Admin Fileadded:flask/testsuite/test_apps/blueprintapp/apps/admin/templates/admin/index.html+1 added
1+Hello from the Adminadded:flask/testsuite/test_apps/blueprintapp/apps/admin/__init__.py+15 added
1+from flask import Blueprint, render_template2+3+admin = Blueprint('admin', __name__, url_prefix='/admin',4+ template_folder='templates',5+ static_folder='static')6+7+8+@admin.route('/')9+def index():10+ return render_template('admin/index.html')11+12+13+@admin.route('/index2')14+def index2():15+ return render_template('./admin/index.html')added:flask/testsuite/test_apps/blueprintapp/apps/frontend/templates/frontend/index.html+1 added
1+Hello from the Frontendadded:flask/testsuite/test_apps/blueprintapp/apps/frontend/__init__.py+8 added
1+from flask import Blueprint, render_template2+3+frontend = Blueprint('frontend', __name__, template_folder='templates')4+5+6+@frontend.route('/')7+def index():8+ return render_template('frontend/index.html')added:flask/testsuite/test_apps/blueprintapp/apps/__init__.py
added:flask/testsuite/test_apps/blueprintapp/__init__.py+7 added
1+from flask import Flask2+3+app = Flask(__name__)4+from blueprintapp.apps.admin import admin5+from blueprintapp.apps.frontend import frontend6+app.register_blueprint(admin)7+app.register_blueprint(frontend)added:flask/testsuite/test_apps/config_package_app/__init__.py+4 added
1+import os2+import flask3+here = os.path.abspath(os.path.dirname(__file__))4+app = flask.Flask(__name__)added:flask/testsuite/test_apps/moduleapp/apps/admin/static/css/test.css+1 added
1+/* nested file */added:flask/testsuite/test_apps/moduleapp/apps/admin/static/test.txt+1 added
1+Admin Fileadded:flask/testsuite/test_apps/moduleapp/apps/admin/templates/index.html+1 added
1+Hello from the Adminadded:flask/testsuite/test_apps/moduleapp/apps/admin/__init__.py+14 added
1+from flask import Module, render_template2+3+4+admin = Module(__name__, url_prefix='/admin')5+6+7+@admin.route('/')8+def index():9+ return render_template('admin/index.html')10+11+12+@admin.route('/index2')13+def index2():14+ return render_template('./admin/index.html')added:flask/testsuite/test_apps/moduleapp/apps/frontend/templates/index.html+1 added
1+Hello from the Frontendadded:flask/testsuite/test_apps/moduleapp/apps/frontend/__init__.py+9 added
1+from flask import Module, render_template2+3+4+frontend = Module(__name__)5+6+7+@frontend.route('/')8+def index():9+ return render_template('frontend/index.html')added:flask/testsuite/test_apps/moduleapp/apps/__init__.py
added:flask/testsuite/test_apps/moduleapp/__init__.py+7 added
1+from flask import Flask2+3+app = Flask(__name__)4+from moduleapp.apps.admin import admin5+from moduleapp.apps.frontend import frontend6+app.register_module(admin)7+app.register_module(frontend)added:flask/testsuite/test_apps/subdomaintestmodule/static/hello.txt+1 added
1+Hello Subdomainadded:flask/testsuite/test_apps/subdomaintestmodule/__init__.py+4 added
1+from flask import Module2+3+4+mod = Module(__name__, 'foo', subdomain='foo')added:flask/testsuite/test_apps/config_module_app.py+4 added
1+import os2+import flask3+here = os.path.abspath(os.path.dirname(__file__))4+app = flask.Flask(__name__)added:flask/testsuite/__init__.py+194 added
1+# -*- coding: utf-8 -*-2+"""3+ flask.testsuite4+ ~~~~~~~~~~~~~~~5+6+ Tests Flask itself. The majority of Flask is already tested7+ as part of Werkzeug.8+9+ :copyright: (c) 2011 by Armin Ronacher.10+ :license: BSD, see LICENSE for more details.11+"""12+import os13+import sys14+import flask15+import warnings16+import unittest17+from StringIO import StringIO18+from functools import update_wrapper19+from contextlib import contextmanager20+from werkzeug.utils import import_string, find_modules21+22+23+def add_to_path(path):24+ """Adds an entry to sys.path_info if it's not already there."""25+ if not os.path.isdir(path):26+ raise RuntimeError('Tried to add nonexisting path')27+28+ def _samefile(x, y):29+ try:30+ return os.path.samefile(x, y)31+ except (IOError, OSError):32+ return False33+ for entry in sys.path:34+ try:35+ if os.path.samefile(path, entry):36+ return37+ except (OSError, IOError):38+ pass39+ sys.path.append(path)40+41+42+def iter_suites():43+ """Yields all testsuites."""44+ for module in find_modules(__name__):45+ mod = import_string(module)46+ if hasattr(mod, 'suite'):47+ yield mod.suite()48+49+50+def find_all_tests(suite):51+ """Yields all the tests and their names from a given suite."""52+ suites = [suite]53+ while suites:54+ s = suites.pop()55+ try:56+ suites.extend(s)57+ except TypeError:58+ yield s, '%s.%s.%s' % (59+ s.__class__.__module__,60+ s.__class__.__name__,61+ s._testMethodName62+ )63+64+65+@contextmanager66+def catch_warnings():67+ """Catch warnings in a with block in a list"""68+ # make sure deprecation warnings are active in tests69+ warnings.simplefilter('default', category=DeprecationWarning)70+71+ filters = warnings.filters72+ warnings.filters = filters[:]73+ old_showwarning = warnings.showwarning74+ log = []75+ def showwarning(message, category, filename, lineno, file=None, line=None):76+ log.append(locals())77+ try:78+ warnings.showwarning = showwarning79+ yield log80+ finally:81+ warnings.filters = filters82+ warnings.showwarning = old_showwarning83+84+85+@contextmanager86+def catch_stderr():87+ """Catch stderr in a StringIO"""88+ old_stderr = sys.stderr89+ sys.stderr = rv = StringIO()90+ try:91+ yield rv92+ finally:93+ sys.stderr = old_stderr94+95+96+def emits_module_deprecation_warning(f):97+ def new_f(self, *args, **kwargs):98+ with catch_warnings() as log:99+ f(self, *args, **kwargs)100+ self.assert_(log, 'expected deprecation warning')101+ for entry in log:102+ self.assert_('Modules are deprecated' in str(entry['message']))103+ return update_wrapper(new_f, f)104+105+106+class FlaskTestCase(unittest.TestCase):107+ """Baseclass for all the tests that Flask uses. Use these methods108+ for testing instead of the camelcased ones in the baseclass for109+ consistency.110+ """111+112+ def ensure_clean_request_context(self):113+ # make sure we're not leaking a request context since we are114+ # testing flask internally in debug mode in a few cases115+ self.assert_equal(flask._request_ctx_stack.top, None)116+117+ def setup(self):118+ pass119+120+ def teardown(self):121+ pass122+123+ def setUp(self):124+ self.setup()125+126+ def tearDown(self):127+ unittest.TestCase.tearDown(self)128+ self.ensure_clean_request_context()129+ self.teardown()130+131+ def assert_equal(self, x, y):132+ return self.assertEqual(x, y)133+134+135+class BetterLoader(unittest.TestLoader):136+ """A nicer loader that solves two problems. First of all we are setting137+ up tests from different sources and we're doing this programmatically138+ which breaks the default loading logic so this is required anyways.139+ Secondly this loader has a nicer interpolation for test names than the140+ default one so you can just do ``run-tests.py ViewTestCase`` and it141+ will work.142+ """143+144+ def getRootSuite(self):145+ return suite()146+147+ def loadTestsFromName(self, name, module=None):148+ root = self.getRootSuite()149+ if name == 'suite':150+ return root151+152+ all_tests = []153+ for testcase, testname in find_all_tests(root):154+ if testname == name or \155+ testname.endswith('.' + name) or \156+ ('.' + name + '.') in testname or \157+ testname.startswith(name + '.'):158+ all_tests.append(testcase)159+160+ if not all_tests:161+ raise LookupError('could not find test case for "%s"' % name)162+163+ if len(all_tests) == 1:164+ return all_tests[0]165+ rv = unittest.TestSuite()166+ for test in all_tests:167+ rv.addTest(test)168+ return rv169+170+171+def setup_path():172+ add_to_path(os.path.abspath(os.path.join(173+ os.path.dirname(__file__), 'test_apps')))174+175+176+def suite():177+ """A testsuite that has all the Flask tests. You can use this178+ function to integrate the Flask tests into your own testsuite179+ in case you want to test that monkeypatches to Flask do not180+ break it.181+ """182+ setup_path()183+ suite = unittest.TestSuite()184+ for other_suite in iter_suites():185+ suite.addTest(other_suite)186+ return suite187+188+189+def main():190+ """Runs the testsuite as command line application."""191+ try:192+ unittest.main(testLoader=BetterLoader(), defaultTest='suite')193+ except Exception, e:194+ print 'Error: %s' % eadded:flask/testsuite/basic.py+1051 added
1+# -*- coding: utf-8 -*-2+"""3+ flask.testsuite.basic4+ ~~~~~~~~~~~~~~~~~~~~~5+6+ The basic functionality.7+8+ :copyright: (c) 2011 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+import re12+import flask13+import unittest14+from datetime import datetime15+from threading import Thread16+from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning17+from werkzeug.exceptions import BadRequest, NotFound18+from werkzeug.http import parse_date19+20+21+class BasicFunctionalityTestCase(FlaskTestCase):22+23+ def test_options_work(self):24+ app = flask.Flask(__name__)25+ @app.route('/', methods=['GET', 'POST'])26+ def index():27+ return 'Hello World'28+ rv = app.test_client().open('/', method='OPTIONS')29+ self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST'])30+ self.assert_equal(rv.data, '')31+32+ def test_options_on_multiple_rules(self):33+ app = flask.Flask(__name__)34+ @app.route('/', methods=['GET', 'POST'])35+ def index():36+ return 'Hello World'37+ @app.route('/', methods=['PUT'])38+ def index_put():39+ return 'Aha!'40+ rv = app.test_client().open('/', method='OPTIONS')41+ self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'])42+43+ def test_options_handling_disabled(self):44+ app = flask.Flask(__name__)45+ def index():46+ return 'Hello World!'47+ index.provide_automatic_options = False48+ app.route('/')(index)49+ rv = app.test_client().open('/', method='OPTIONS')50+ self.assert_equal(rv.status_code, 405)51+52+ app = flask.Flask(__name__)53+ def index2():54+ return 'Hello World!'55+ index2.provide_automatic_options = True56+ app.route('/', methods=['OPTIONS'])(index2)57+ rv = app.test_client().open('/', method='OPTIONS')58+ self.assert_equal(sorted(rv.allow), ['OPTIONS'])59+60+ def test_request_dispatching(self):61+ app = flask.Flask(__name__)62+ @app.route('/')63+ def index():64+ return flask.request.method65+ @app.route('/more', methods=['GET', 'POST'])66+ def more():67+ return flask.request.method68+69+ c = app.test_client()70+ self.assert_equal(c.get('/').data, 'GET')71+ rv = c.post('/')72+ self.assert_equal(rv.status_code, 405)73+ self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS'])74+ rv = c.head('/')75+ self.assert_equal(rv.status_code, 200)76+ self.assert_(not rv.data) # head truncates77+ self.assert_equal(c.post('/more').data, 'POST')78+ self.assert_equal(c.get('/more').data, 'GET')79+ rv = c.delete('/more')80+ self.assert_equal(rv.status_code, 405)81+ self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST'])82+83+ def test_url_mapping(self):84+ app = flask.Flask(__name__)85+ def index():86+ return flask.request.method87+ def more():88+ return flask.request.method89+90+ app.add_url_rule('/', 'index', index)91+ app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])92+93+ c = app.test_client()94+ self.assert_equal(c.get('/').data, 'GET')95+ rv = c.post('/')96+ self.assert_equal(rv.status_code, 405)97+ self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS'])98+ rv = c.head('/')99+ self.assert_equal(rv.status_code, 200)100+ self.assert_(not rv.data) # head truncates101+ self.assert_equal(c.post('/more').data, 'POST')102+ self.assert_equal(c.get('/more').data, 'GET')103+ rv = c.delete('/more')104+ self.assert_equal(rv.status_code, 405)105+ self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST'])106+107+ def test_werkzeug_routing(self):108+ from werkzeug.routing import Submount, Rule109+ app = flask.Flask(__name__)110+ app.url_map.add(Submount('/foo', [111+ Rule('/bar', endpoint='bar'),112+ Rule('/', endpoint='index')113+ ]))114+ def bar():115+ return 'bar'116+ def index():117+ return 'index'118+ app.view_functions['bar'] = bar119+ app.view_functions['index'] = index120+121+ c = app.test_client()122+ self.assert_equal(c.get('/foo/').data, 'index')123+ self.assert_equal(c.get('/foo/bar').data, 'bar')124+125+ def test_endpoint_decorator(self):126+ from werkzeug.routing import Submount, Rule127+ app = flask.Flask(__name__)128+ app.url_map.add(Submount('/foo', [129+ Rule('/bar', endpoint='bar'),130+ Rule('/', endpoint='index')131+ ]))132+133+ @app.endpoint('bar')134+ def bar():135+ return 'bar'136+137+ @app.endpoint('index')138+ def index():139+ return 'index'140+141+ c = app.test_client()142+ self.assert_equal(c.get('/foo/').data, 'index')143+ self.assert_equal(c.get('/foo/bar').data, 'bar')144+145+ def test_session(self):146+ app = flask.Flask(__name__)147+ app.secret_key = 'testkey'148+ @app.route('/set', methods=['POST'])149+ def set():150+ flask.session['value'] = flask.request.form['value']151+ return 'value set'152+ @app.route('/get')153+ def get():154+ return flask.session['value']155+156+ c = app.test_client()157+ self.assert_equal(c.post('/set', data={'value': '42'}).data, 'value set')158+ self.assert_equal(c.get('/get').data, '42')159+160+ def test_session_using_server_name(self):161+ app = flask.Flask(__name__)162+ app.config.update(163+ SECRET_KEY='foo',164+ SERVER_NAME='example.com'165+ )166+ @app.route('/')167+ def index():168+ flask.session['testing'] = 42169+ return 'Hello World'170+ rv = app.test_client().get('/', 'http://example.com/')171+ self.assert_('domain=.example.com' in rv.headers['set-cookie'].lower())172+ self.assert_('httponly' in rv.headers['set-cookie'].lower())173+174+ def test_session_using_server_name_and_port(self):175+ app = flask.Flask(__name__)176+ app.config.update(177+ SECRET_KEY='foo',178+ SERVER_NAME='example.com:8080'179+ )180+ @app.route('/')181+ def index():182+ flask.session['testing'] = 42183+ return 'Hello World'184+ rv = app.test_client().get('/', 'http://example.com:8080/')185+ self.assert_('domain=.example.com' in rv.headers['set-cookie'].lower())186+ self.assert_('httponly' in rv.headers['set-cookie'].lower())187+188+ def test_session_using_application_root(self):189+ class PrefixPathMiddleware(object):190+ def __init__(self, app, prefix):191+ self.app = app192+ self.prefix = prefix193+ def __call__(self, environ, start_response):194+ environ['SCRIPT_NAME'] = self.prefix195+ return self.app(environ, start_response)196+197+ app = flask.Flask(__name__)198+ app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar')199+ app.config.update(200+ SECRET_KEY='foo',201+ APPLICATION_ROOT='/bar'202+ )203+ @app.route('/')204+ def index():205+ flask.session['testing'] = 42206+ return 'Hello World'207+ rv = app.test_client().get('/', 'http://example.com:8080/')208+ self.assert_('path=/bar' in rv.headers['set-cookie'].lower())209+210+ def test_session_using_session_settings(self):211+ app = flask.Flask(__name__)212+ app.config.update(213+ SECRET_KEY='foo',214+ SERVER_NAME='www.example.com:8080',215+ APPLICATION_ROOT='/test',216+ SESSION_COOKIE_DOMAIN='.example.com',217+ SESSION_COOKIE_HTTPONLY=False,218+ SESSION_COOKIE_SECURE=True,219+ SESSION_COOKIE_PATH='/'220+ )221+ @app.route('/')222+ def index():223+ flask.session['testing'] = 42224+ return 'Hello World'225+ rv = app.test_client().get('/', 'http://www.example.com:8080/test/')226+ cookie = rv.headers['set-cookie'].lower()227+ self.assert_('domain=.example.com' in cookie)228+ self.assert_('path=/;' in cookie)229+ self.assert_('secure' in cookie)230+ self.assert_('httponly' not in cookie)231+232+ def test_missing_session(self):233+ app = flask.Flask(__name__)234+ def expect_exception(f, *args, **kwargs):235+ try:236+ f(*args, **kwargs)237+ except RuntimeError, e:238+ self.assert_(e.args and 'session is unavailable' in e.args[0])239+ else:240+ self.assert_(False, 'expected exception')241+ with app.test_request_context():242+ self.assert_(flask.session.get('missing_key') is None)243+ expect_exception(flask.session.__setitem__, 'foo', 42)244+ expect_exception(flask.session.pop, 'foo')245+246+ def test_session_expiration(self):247+ permanent = True248+ app = flask.Flask(__name__)249+ app.secret_key = 'testkey'250+ @app.route('/')251+ def index():252+ flask.session['test'] = 42253+ flask.session.permanent = permanent254+ return ''255+256+ @app.route('/test')257+ def test():258+ return unicode(flask.session.permanent)259+260+ client = app.test_client()261+ rv = client.get('/')262+ self.assert_('set-cookie' in rv.headers)263+ match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])264+ expires = parse_date(match.group())265+ expected = datetime.utcnow() + app.permanent_session_lifetime266+ self.assert_equal(expires.year, expected.year)267+ self.assert_equal(expires.month, expected.month)268+ self.assert_equal(expires.day, expected.day)269+270+ rv = client.get('/test')271+ self.assert_equal(rv.data, 'True')272+273+ permanent = False274+ rv = app.test_client().get('/')275+ self.assert_('set-cookie' in rv.headers)276+ match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])277+ self.assert_(match is None)278+279+ def test_flashes(self):280+ app = flask.Flask(__name__)281+ app.secret_key = 'testkey'282+283+ with app.test_request_context():284+ self.assert_(not flask.session.modified)285+ flask.flash('Zap')286+ flask.session.modified = False287+ flask.flash('Zip')288+ self.assert_(flask.session.modified)289+ self.assert_equal(list(flask.get_flashed_messages()), ['Zap', 'Zip'])290+291+ def test_extended_flashing(self):292+ app = flask.Flask(__name__)293+ app.secret_key = 'testkey'294+295+ @app.route('/')296+ def index():297+ flask.flash(u'Hello World')298+ flask.flash(u'Hello World', 'error')299+ flask.flash(flask.Markup(u'<em>Testing</em>'), 'warning')300+ return ''301+302+ @app.route('/test')303+ def test():304+ messages = flask.get_flashed_messages(with_categories=True)305+ self.assert_equal(len(messages), 3)306+ self.assert_equal(messages[0], ('message', u'Hello World'))307+ self.assert_equal(messages[1], ('error', u'Hello World'))308+ self.assert_equal(messages[2], ('warning', flask.Markup(u'<em>Testing</em>')))309+ return ''310+ messages = flask.get_flashed_messages()311+ self.assert_equal(len(messages), 3)312+ self.assert_equal(messages[0], u'Hello World')313+ self.assert_equal(messages[1], u'Hello World')314+ self.assert_equal(messages[2], flask.Markup(u'<em>Testing</em>'))315+316+ c = app.test_client()317+ c.get('/')318+ c.get('/test')319+320+ def test_request_processing(self):321+ app = flask.Flask(__name__)322+ evts = []323+ @app.before_request324+ def before_request():325+ evts.append('before')326+ @app.after_request327+ def after_request(response):328+ response.data += '|after'329+ evts.append('after')330+ return response331+ @app.route('/')332+ def index():333+ self.assert_('before' in evts)334+ self.assert_('after' not in evts)335+ return 'request'336+ self.assert_('after' not in evts)337+ rv = app.test_client().get('/').data338+ self.assert_('after' in evts)339+ self.assert_equal(rv, 'request|after')340+341+ def test_teardown_request_handler(self):342+ called = []343+ app = flask.Flask(__name__)344+ @app.teardown_request345+ def teardown_request(exc):346+ called.append(True)347+ return "Ignored"348+ @app.route('/')349+ def root():350+ return "Response"351+ rv = app.test_client().get('/')352+ self.assert_equal(rv.status_code, 200)353+ self.assert_('Response' in rv.data)354+ self.assert_equal(len(called), 1)355+356+ def test_teardown_request_handler_debug_mode(self):357+ called = []358+ app = flask.Flask(__name__)359+ app.testing = True360+ @app.teardown_request361+ def teardown_request(exc):362+ called.append(True)363+ return "Ignored"364+ @app.route('/')365+ def root():366+ return "Response"367+ rv = app.test_client().get('/')368+ self.assert_equal(rv.status_code, 200)369+ self.assert_('Response' in rv.data)370+ self.assert_equal(len(called), 1)371+372+ def test_teardown_request_handler_error(self):373+ called = []374+ app = flask.Flask(__name__)375+ @app.teardown_request376+ def teardown_request1(exc):377+ self.assert_equal(type(exc), ZeroDivisionError)378+ called.append(True)379+ # This raises a new error and blows away sys.exc_info(), so we can380+ # test that all teardown_requests get passed the same original381+ # exception.382+ try:383+ raise TypeError384+ except:385+ pass386+ @app.teardown_request387+ def teardown_request2(exc):388+ self.assert_equal(type(exc), ZeroDivisionError)389+ called.append(True)390+ # This raises a new error and blows away sys.exc_info(), so we can391+ # test that all teardown_requests get passed the same original392+ # exception.393+ try:394+ raise TypeError395+ except:396+ pass397+ @app.route('/')398+ def fails():399+ 1/0400+ rv = app.test_client().get('/')401+ self.assert_equal(rv.status_code, 500)402+ self.assert_('Internal Server Error' in rv.data)403+ self.assert_equal(len(called), 2)404+405+ def test_before_after_request_order(self):406+ called = []407+ app = flask.Flask(__name__)408+ @app.before_request409+ def before1():410+ called.append(1)411+ @app.before_request412+ def before2():413+ called.append(2)414+ @app.after_request415+ def after1(response):416+ called.append(4)417+ return response418+ @app.after_request419+ def after2(response):420+ called.append(3)421+ return response422+ @app.teardown_request423+ def finish1(exc):424+ called.append(6)425+ @app.teardown_request426+ def finish2(exc):427+ called.append(5)428+ @app.route('/')429+ def index():430+ return '42'431+ rv = app.test_client().get('/')432+ self.assert_equal(rv.data, '42')433+ self.assert_equal(called, [1, 2, 3, 4, 5, 6])434+435+ def test_error_handling(self):436+ app = flask.Flask(__name__)437+ @app.errorhandler(404)438+ def not_found(e):439+ return 'not found', 404440+ @app.errorhandler(500)441+ def internal_server_error(e):442+ return 'internal server error', 500443+ @app.route('/')444+ def index():445+ flask.abort(404)446+ @app.route('/error')447+ def error():448+ 1 // 0449+ c = app.test_client()450+ rv = c.get('/')451+ self.assert_equal(rv.status_code, 404)452+ self.assert_equal(rv.data, 'not found')453+ rv = c.get('/error')454+ self.assert_equal(rv.status_code, 500)455+ self.assert_equal('internal server error', rv.data)456+457+ def test_before_request_and_routing_errors(self):458+ app = flask.Flask(__name__)459+ @app.before_request460+ def attach_something():461+ flask.g.something = 'value'462+ @app.errorhandler(404)463+ def return_something(error):464+ return flask.g.something, 404465+ rv = app.test_client().get('/')466+ self.assert_equal(rv.status_code, 404)467+ self.assert_equal(rv.data, 'value')468+469+ def test_user_error_handling(self):470+ class MyException(Exception):471+ pass472+473+ app = flask.Flask(__name__)474+ @app.errorhandler(MyException)475+ def handle_my_exception(e):476+ self.assert_(isinstance(e, MyException))477+ return '42'478+ @app.route('/')479+ def index():480+ raise MyException()481+482+ c = app.test_client()483+ self.assert_equal(c.get('/').data, '42')484+485+ def test_trapping_of_bad_request_key_errors(self):486+ app = flask.Flask(__name__)487+ app.testing = True488+ @app.route('/fail')489+ def fail():490+ flask.request.form['missing_key']491+ c = app.test_client()492+ self.assert_equal(c.get('/fail').status_code, 400)493+494+ app.config['TRAP_BAD_REQUEST_ERRORS'] = True495+ c = app.test_client()496+ try:497+ c.get('/fail')498+ except KeyError, e:499+ self.assert_(isinstance(e, BadRequest))500+ else:501+ self.fail('Expected exception')502+503+ def test_trapping_of_all_http_exceptions(self):504+ app = flask.Flask(__name__)505+ app.testing = True506+ app.config['TRAP_HTTP_EXCEPTIONS'] = True507+ @app.route('/fail')508+ def fail():509+ flask.abort(404)510+511+ c = app.test_client()512+ try:513+ c.get('/fail')514+ except NotFound, e:515+ pass516+ else:517+ self.fail('Expected exception')518+519+ def test_enctype_debug_helper(self):520+ from flask.debughelpers import DebugFilesKeyError521+ app = flask.Flask(__name__)522+ app.debug = True523+ @app.route('/fail', methods=['POST'])524+ def index():525+ return flask.request.files['foo'].filename526+527+ # with statement is important because we leave an exception on the528+ # stack otherwise and we want to ensure that this is not the case529+ # to not negatively affect other tests.530+ with app.test_client() as c:531+ try:532+ c.post('/fail', data={'foo': 'index.txt'})533+ except DebugFilesKeyError, e:534+ self.assert_('no file contents were transmitted' in str(e))535+ self.assert_('This was submitted: "index.txt"' in str(e))536+ else:537+ self.fail('Expected exception')538+539+ def test_teardown_on_pop(self):540+ buffer = []541+ app = flask.Flask(__name__)542+ @app.teardown_request543+ def end_of_request(exception):544+ buffer.append(exception)545+546+ ctx = app.test_request_context()547+ ctx.push()548+ self.assert_equal(buffer, [])549+ ctx.pop()550+ self.assert_equal(buffer, [None])551+552+ def test_response_creation(self):553+ app = flask.Flask(__name__)554+ @app.route('/unicode')555+ def from_unicode():556+ return u'Hällo Wörld'557+ @app.route('/string')558+ def from_string():559+ return u'Hällo Wörld'.encode('utf-8')560+ @app.route('/args')561+ def from_tuple():562+ return 'Meh', 400, {'X-Foo': 'Testing'}, 'text/plain'563+ c = app.test_client()564+ self.assert_equal(c.get('/unicode').data, u'Hällo Wörld'.encode('utf-8'))565+ self.assert_equal(c.get('/string').data, u'Hällo Wörld'.encode('utf-8'))566+ rv = c.get('/args')567+ self.assert_equal(rv.data, 'Meh')568+ self.assert_equal(rv.headers['X-Foo'], 'Testing')569+ self.assert_equal(rv.status_code, 400)570+ self.assert_equal(rv.mimetype, 'text/plain')571+572+ def test_make_response(self):573+ app = flask.Flask(__name__)574+ with app.test_request_context():575+ rv = flask.make_response()576+ self.assert_equal(rv.status_code, 200)577+ self.assert_equal(rv.data, '')578+ self.assert_equal(rv.mimetype, 'text/html')579+580+ rv = flask.make_response('Awesome')581+ self.assert_equal(rv.status_code, 200)582+ self.assert_equal(rv.data, 'Awesome')583+ self.assert_equal(rv.mimetype, 'text/html')584+585+ rv = flask.make_response('W00t', 404)586+ self.assert_equal(rv.status_code, 404)587+ self.assert_equal(rv.data, 'W00t')588+ self.assert_equal(rv.mimetype, 'text/html')589+590+ def test_url_generation(self):591+ app = flask.Flask(__name__)592+ @app.route('/hello/<name>', methods=['POST'])593+ def hello():594+ pass595+ with app.test_request_context():596+ self.assert_equal(flask.url_for('hello', name='test x'), '/hello/test%20x')597+ self.assert_equal(flask.url_for('hello', name='test x', _external=True),598+ 'http://localhost/hello/test%20x')599+600+ def test_custom_converters(self):601+ from werkzeug.routing import BaseConverter602+ class ListConverter(BaseConverter):603+ def to_python(self, value):604+ return value.split(',')605+ def to_url(self, value):606+ base_to_url = super(ListConverter, self).to_url607+ return ','.join(base_to_url(x) for x in value)608+ app = flask.Flask(__name__)609+ app.url_map.converters['list'] = ListConverter610+ @app.route('/<list:args>')611+ def index(args):612+ return '|'.join(args)613+ c = app.test_client()614+ self.assert_equal(c.get('/1,2,3').data, '1|2|3')615+616+ def test_static_files(self):617+ app = flask.Flask(__name__)618+ rv = app.test_client().get('/static/index.html')619+ self.assert_equal(rv.status_code, 200)620+ self.assert_equal(rv.data.strip(), '<h1>Hello World!</h1>')621+ with app.test_request_context():622+ self.assert_equal(flask.url_for('static', filename='index.html'),623+ '/static/index.html')624+625+ def test_none_response(self):626+ app = flask.Flask(__name__)627+ @app.route('/')628+ def test():629+ return None630+ try:631+ app.test_client().get('/')632+ except ValueError, e:633+ self.assert_equal(str(e), 'View function did not return a response')634+ pass635+ else:636+ self.assert_("Expected ValueError")637+638+ def test_request_locals(self):639+ self.assert_equal(repr(flask.g), '<LocalProxy unbound>')640+ self.assertFalse(flask.g)641+642+ def test_proper_test_request_context(self):643+ app = flask.Flask(__name__)644+ app.config.update(645+ SERVER_NAME='localhost.localdomain:5000'646+ )647+648+ @app.route('/')649+ def index():650+ return None651+652+ @app.route('/', subdomain='foo')653+ def sub():654+ return None655+656+ with app.test_request_context('/'):657+ self.assert_equal(flask.url_for('index', _external=True), 'http://localhost.localdomain:5000/')658+659+ with app.test_request_context('/'):660+ self.assert_equal(flask.url_for('sub', _external=True), 'http://foo.localhost.localdomain:5000/')661+662+ try:663+ with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}):664+ pass665+ except Exception, e:666+ self.assert_(isinstance(e, ValueError))667+ self.assert_equal(str(e), "the server name provided " +668+ "('localhost.localdomain:5000') does not match the " + \669+ "server name from the WSGI environment ('localhost')")670+671+ try:672+ app.config.update(SERVER_NAME='localhost')673+ with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}):674+ pass675+ except ValueError, e:676+ raise ValueError(677+ "No ValueError exception should have been raised \"%s\"" % e678+ )679+680+ try:681+ app.config.update(SERVER_NAME='localhost:80')682+ with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}):683+ pass684+ except ValueError, e:685+ raise ValueError(686+ "No ValueError exception should have been raised \"%s\"" % e687+ )688+689+ def test_test_app_proper_environ(self):690+ app = flask.Flask(__name__)691+ app.config.update(692+ SERVER_NAME='localhost.localdomain:5000'693+ )694+ @app.route('/')695+ def index():696+ return 'Foo'697+698+ @app.route('/', subdomain='foo')699+ def subdomain():700+ return 'Foo SubDomain'701+702+ try:703+ rv = app.test_client().get('/')704+ self.assert_equal(rv.data, 'Foo')705+ except ValueError, e:706+ raise ValueError(707+ "No ValueError exception should have been raised \"%s\"" % e708+ )709+710+ try:711+ rv = app.test_client().get('/', 'http://localhost.localdomain:5000')712+ self.assert_equal(rv.data, 'Foo')713+ except ValueError, e:714+ raise ValueError(715+ "No ValueError exception should have been raised \"%s\"" % e716+ )717+718+ try:719+ rv = app.test_client().get('/', 'https://localhost.localdomain:5000')720+ self.assert_equal(rv.data, 'Foo')721+ except ValueError, e:722+ raise ValueError(723+ "No ValueError exception should have been raised \"%s\"" % e724+ )725+726+ try:727+ app.config.update(SERVER_NAME='localhost.localdomain')728+ rv = app.test_client().get('/', 'https://localhost.localdomain')729+ self.assert_equal(rv.data, 'Foo')730+ except ValueError, e:731+ raise ValueError(732+ "No ValueError exception should have been raised \"%s\"" % e733+ )734+735+ try:736+ app.config.update(SERVER_NAME='localhost.localdomain:443')737+ rv = app.test_client().get('/', 'https://localhost.localdomain')738+ self.assert_equal(rv.data, 'Foo')739+ except ValueError, e:740+ self.assert_equal(str(e), "the server name provided " +741+ "('localhost.localdomain:443') does not match the " + \742+ "server name from the WSGI environment ('localhost.localdomain')")743+744+ try:745+ app.config.update(SERVER_NAME='localhost.localdomain')746+ app.test_client().get('/', 'http://foo.localhost')747+ except ValueError, e:748+ self.assert_equal(str(e), "the server name provided " + \749+ "('localhost.localdomain') does not match the " + \750+ "server name from the WSGI environment ('foo.localhost')")751+752+ try:753+ rv = app.test_client().get('/', 'http://foo.localhost.localdomain')754+ self.assert_equal(rv.data, 'Foo SubDomain')755+ except ValueError, e:756+ raise ValueError(757+ "No ValueError exception should have been raised \"%s\"" % e758+ )759+760+ def test_exception_propagation(self):761+ def apprunner(configkey):762+ app = flask.Flask(__name__)763+ @app.route('/')764+ def index():765+ 1/0766+ c = app.test_client()767+ if config_key is not None:768+ app.config[config_key] = True769+ try:770+ resp = c.get('/')771+ except Exception:772+ pass773+ else:774+ self.fail('expected exception')775+ else:776+ self.assert_equal(c.get('/').status_code, 500)777+778+ # we have to run this test in an isolated thread because if the779+ # debug flag is set to true and an exception happens the context is780+ # not torn down. This causes other tests that run after this fail781+ # when they expect no exception on the stack.782+ for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None:783+ t = Thread(target=apprunner, args=(config_key,))784+ t.start()785+ t.join()786+787+ def test_max_content_length(self):788+ app = flask.Flask(__name__)789+ app.config['MAX_CONTENT_LENGTH'] = 64790+ @app.before_request791+ def always_first():792+ flask.request.form['myfile']793+ self.assert_(False)794+ @app.route('/accept', methods=['POST'])795+ def accept_file():796+ flask.request.form['myfile']797+ self.assert_(False)798+ @app.errorhandler(413)799+ def catcher(error):800+ return '42'801+802+ c = app.test_client()803+ rv = c.post('/accept', data={'myfile': 'foo' * 100})804+ self.assert_equal(rv.data, '42')805+806+ def test_url_processors(self):807+ app = flask.Flask(__name__)808+809+ @app.url_defaults810+ def add_language_code(endpoint, values):811+ if flask.g.lang_code is not None and \812+ app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):813+ values.setdefault('lang_code', flask.g.lang_code)814+815+ @app.url_value_preprocessor816+ def pull_lang_code(endpoint, values):817+ flask.g.lang_code = values.pop('lang_code', None)818+819+ @app.route('/<lang_code>/')820+ def index():821+ return flask.url_for('about')822+823+ @app.route('/<lang_code>/about')824+ def about():825+ return flask.url_for('something_else')826+827+ @app.route('/foo')828+ def something_else():829+ return flask.url_for('about', lang_code='en')830+831+ c = app.test_client()832+833+ self.assert_equal(c.get('/de/').data, '/de/about')834+ self.assert_equal(c.get('/de/about').data, '/foo')835+ self.assert_equal(c.get('/foo').data, '/en/about')836+837+ def test_debug_mode_complains_after_first_request(self):838+ app = flask.Flask(__name__)839+ app.debug = True840+ @app.route('/')841+ def index():842+ return 'Awesome'843+ self.assert_(not app.got_first_request)844+ self.assert_equal(app.test_client().get('/').data, 'Awesome')845+ try:846+ @app.route('/foo')847+ def broken():848+ return 'Meh'849+ except AssertionError, e:850+ self.assert_('A setup function was called' in str(e))851+ else:852+ self.fail('Expected exception')853+854+ app.debug = False855+ @app.route('/foo')856+ def working():857+ return 'Meh'858+ self.assert_equal(app.test_client().get('/foo').data, 'Meh')859+ self.assert_(app.got_first_request)860+861+ def test_before_first_request_functions(self):862+ got = []863+ app = flask.Flask(__name__)864+ @app.before_first_request865+ def foo():866+ got.append(42)867+ c = app.test_client()868+ c.get('/')869+ self.assert_equal(got, [42])870+ c.get('/')871+ self.assert_equal(got, [42])872+ self.assert_(app.got_first_request)873+874+ def test_routing_redirect_debugging(self):875+ app = flask.Flask(__name__)876+ app.debug = True877+ @app.route('/foo/', methods=['GET', 'POST'])878+ def foo():879+ return 'success'880+ with app.test_client() as c:881+ try:882+ c.post('/foo', data={})883+ except AssertionError, e:884+ self.assert_('http://localhost/foo/' in str(e))885+ self.assert_('Make sure to directly send your POST-request '886+ 'to this URL' in str(e))887+ else:888+ self.fail('Expected exception')889+890+ rv = c.get('/foo', data={}, follow_redirects=True)891+ self.assert_equal(rv.data, 'success')892+893+ app.debug = False894+ with app.test_client() as c:895+ rv = c.post('/foo', data={}, follow_redirects=True)896+ self.assert_equal(rv.data, 'success')897+898+ def test_route_decorator_custom_endpoint(self):899+ app = flask.Flask(__name__)900+ app.debug = True901+902+ @app.route('/foo/')903+ def foo():904+ return flask.request.endpoint905+906+ @app.route('/bar/', endpoint='bar')907+ def for_bar():908+ return flask.request.endpoint909+910+ @app.route('/bar/123', endpoint='123')911+ def for_bar_foo():912+ return flask.request.endpoint913+914+ with app.test_request_context():915+ assert flask.url_for('foo') == '/foo/'916+ assert flask.url_for('bar') == '/bar/'917+ assert flask.url_for('123') == '/bar/123'918+919+ c = app.test_client()920+ self.assertEqual(c.get('/foo/').data, 'foo')921+ self.assertEqual(c.get('/bar/').data, 'bar')922+ self.assertEqual(c.get('/bar/123').data, '123')923+924+925+class ContextTestCase(FlaskTestCase):926+927+ def test_context_binding(self):928+ app = flask.Flask(__name__)929+ @app.route('/')930+ def index():931+ return 'Hello %s!' % flask.request.args['name']932+ @app.route('/meh')933+ def meh():934+ return flask.request.url935+936+ with app.test_request_context('/?name=World'):937+ self.assert_equal(index(), 'Hello World!')938+ with app.test_request_context('/meh'):939+ self.assert_equal(meh(), 'http://localhost/meh')940+ self.assert_(flask._request_ctx_stack.top is None)941+942+ def test_context_test(self):943+ app = flask.Flask(__name__)944+ self.assert_(not flask.request)945+ self.assert_(not flask.has_request_context())946+ ctx = app.test_request_context()947+ ctx.push()948+ try:949+ self.assert_(flask.request)950+ self.assert_(flask.has_request_context())951+ finally:952+ ctx.pop()953+954+ def test_manual_context_binding(self):955+ app = flask.Flask(__name__)956+ @app.route('/')957+ def index():958+ return 'Hello %s!' % flask.request.args['name']959+960+ ctx = app.test_request_context('/?name=World')961+ ctx.push()962+ self.assert_equal(index(), 'Hello World!')963+ ctx.pop()964+ try:965+ index()966+ except RuntimeError:967+ pass968+ else:969+ self.assert_(0, 'expected runtime error')970+971+972+class SubdomainTestCase(FlaskTestCase):973+974+ def test_basic_support(self):975+ app = flask.Flask(__name__)976+ app.config['SERVER_NAME'] = 'localhost'977+ @app.route('/')978+ def normal_index():979+ return 'normal index'980+ @app.route('/', subdomain='test')981+ def test_index():982+ return 'test index'983+984+ c = app.test_client()985+ rv = c.get('/', 'http://localhost/')986+ self.assert_equal(rv.data, 'normal index')987+988+ rv = c.get('/', 'http://test.localhost/')989+ self.assert_equal(rv.data, 'test index')990+991+ @emits_module_deprecation_warning992+ def test_module_static_path_subdomain(self):993+ app = flask.Flask(__name__)994+ app.config['SERVER_NAME'] = 'example.com'995+ from subdomaintestmodule import mod996+ app.register_module(mod)997+ c = app.test_client()998+ rv = c.get('/static/hello.txt', 'http://foo.example.com/')999+ self.assert_equal(rv.data.strip(), 'Hello Subdomain')1000+1001+ def test_subdomain_matching(self):1002+ app = flask.Flask(__name__)1003+ app.config['SERVER_NAME'] = 'localhost'1004+ @app.route('/', subdomain='<user>')1005+ def index(user):1006+ return 'index for %s' % user1007+1008+ c = app.test_client()1009+ rv = c.get('/', 'http://mitsuhiko.localhost/')1010+ self.assert_equal(rv.data, 'index for mitsuhiko')1011+1012+ def test_subdomain_matching_with_ports(self):1013+ app = flask.Flask(__name__)1014+ app.config['SERVER_NAME'] = 'localhost:3000'1015+ @app.route('/', subdomain='<user>')1016+ def index(user):1017+ return 'index for %s' % user1018+1019+ c = app.test_client()1020+ rv = c.get('/', 'http://mitsuhiko.localhost:3000/')1021+ self.assert_equal(rv.data, 'index for mitsuhiko')1022+1023+ @emits_module_deprecation_warning1024+ def test_module_subdomain_support(self):1025+ app = flask.Flask(__name__)1026+ mod = flask.Module(__name__, 'test', subdomain='testing')1027+ app.config['SERVER_NAME'] = 'localhost'1028+1029+ @mod.route('/test')1030+ def test():1031+ return 'Test'1032+1033+ @mod.route('/outside', subdomain='xtesting')1034+ def bar():1035+ return 'Outside'1036+1037+ app.register_module(mod)1038+1039+ c = app.test_client()1040+ rv = c.get('/test', 'http://testing.localhost/')1041+ self.assert_equal(rv.data, 'Test')1042+ rv = c.get('/outside', 'http://xtesting.localhost/')1043+ self.assert_equal(rv.data, 'Outside')1044+1045+1046+def suite():1047+ suite = unittest.TestSuite()1048+ suite.addTest(unittest.makeSuite(BasicFunctionalityTestCase))1049+ suite.addTest(unittest.makeSuite(ContextTestCase))1050+ suite.addTest(unittest.makeSuite(SubdomainTestCase))1051+ return suiteadded:flask/testsuite/blueprints.py+509 added
1+# -*- coding: utf-8 -*-2+"""3+ flask.testsuite.blueprints4+ ~~~~~~~~~~~~~~~~~~~~~~~~~~5+6+ Blueprints (and currently modules)7+8+ :copyright: (c) 2011 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+import flask12+import unittest13+import warnings14+from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning15+from werkzeug.exceptions import NotFound16+from jinja2 import TemplateNotFound17+18+19+# import moduleapp here because it uses deprecated features and we don't20+# want to see the warnings21+warnings.simplefilter('ignore', DeprecationWarning)22+from moduleapp import app as moduleapp23+warnings.simplefilter('default', DeprecationWarning)24+25+26+class ModuleTestCase(FlaskTestCase):27+28+ @emits_module_deprecation_warning29+ def test_basic_module(self):30+ app = flask.Flask(__name__)31+ admin = flask.Module(__name__, 'admin', url_prefix='/admin')32+ @admin.route('/')33+ def admin_index():34+ return 'admin index'35+ @admin.route('/login')36+ def admin_login():37+ return 'admin login'38+ @admin.route('/logout')39+ def admin_logout():40+ return 'admin logout'41+ @app.route('/')42+ def index():43+ return 'the index'44+ app.register_module(admin)45+ c = app.test_client()46+ self.assert_equal(c.get('/').data, 'the index')47+ self.assert_equal(c.get('/admin/').data, 'admin index')48+ self.assert_equal(c.get('/admin/login').data, 'admin login')49+ self.assert_equal(c.get('/admin/logout').data, 'admin logout')50+51+ @emits_module_deprecation_warning52+ def test_default_endpoint_name(self):53+ app = flask.Flask(__name__)54+ mod = flask.Module(__name__, 'frontend')55+ def index():56+ return 'Awesome'57+ mod.add_url_rule('/', view_func=index)58+ app.register_module(mod)59+ rv = app.test_client().get('/')60+ self.assert_equal(rv.data, 'Awesome')61+ with app.test_request_context():62+ self.assert_equal(flask.url_for('frontend.index'), '/')63+64+ @emits_module_deprecation_warning65+ def test_request_processing(self):66+ catched = []67+ app = flask.Flask(__name__)68+ admin = flask.Module(__name__, 'admin', url_prefix='/admin')69+ @admin.before_request70+ def before_admin_request():71+ catched.append('before-admin')72+ @admin.after_request73+ def after_admin_request(response):74+ catched.append('after-admin')75+ return response76+ @admin.route('/')77+ def admin_index():78+ return 'the admin'79+ @app.before_request80+ def before_request():81+ catched.append('before-app')82+ @app.after_request83+ def after_request(response):84+ catched.append('after-app')85+ return response86+ @app.route('/')87+ def index():88+ return 'the index'89+ app.register_module(admin)90+ c = app.test_client()91+92+ self.assert_equal(c.get('/').data, 'the index')93+ self.assert_equal(catched, ['before-app', 'after-app'])94+ del catched[:]95+96+ self.assert_equal(c.get('/admin/').data, 'the admin')97+ self.assert_equal(catched, ['before-app', 'before-admin',98+ 'after-admin', 'after-app'])99+100+ @emits_module_deprecation_warning101+ def test_context_processors(self):102+ app = flask.Flask(__name__)103+ admin = flask.Module(__name__, 'admin', url_prefix='/admin')104+ @app.context_processor105+ def inject_all_regualr():106+ return {'a': 1}107+ @admin.context_processor108+ def inject_admin():109+ return {'b': 2}110+ @admin.app_context_processor111+ def inject_all_module():112+ return {'c': 3}113+ @app.route('/')114+ def index():115+ return flask.render_template_string('{{ a }}{{ b }}{{ c }}')116+ @admin.route('/')117+ def admin_index():118+ return flask.render_template_string('{{ a }}{{ b }}{{ c }}')119+ app.register_module(admin)120+ c = app.test_client()121+ self.assert_equal(c.get('/').data, '13')122+ self.assert_equal(c.get('/admin/').data, '123')123+124+ @emits_module_deprecation_warning125+ def test_late_binding(self):126+ app = flask.Flask(__name__)127+ admin = flask.Module(__name__, 'admin')128+ @admin.route('/')129+ def index():130+ return '42'131+ app.register_module(admin, url_prefix='/admin')132+ self.assert_equal(app.test_client().get('/admin/').data, '42')133+134+ @emits_module_deprecation_warning135+ def test_error_handling(self):136+ app = flask.Flask(__name__)137+ admin = flask.Module(__name__, 'admin')138+ @admin.app_errorhandler(404)139+ def not_found(e):140+ return 'not found', 404141+ @admin.app_errorhandler(500)142+ def internal_server_error(e):143+ return 'internal server error', 500144+ @admin.route('/')145+ def index():146+ flask.abort(404)147+ @admin.route('/error')148+ def error():149+ 1 // 0150+ app.register_module(admin)151+ c = app.test_client()152+ rv = c.get('/')153+ self.assert_equal(rv.status_code, 404)154+ self.assert_equal(rv.data, 'not found')155+ rv = c.get('/error')156+ self.assert_equal(rv.status_code, 500)157+ self.assert_equal('internal server error', rv.data)158+159+ def test_templates_and_static(self):160+ app = moduleapp161+ app.testing = True162+ c = app.test_client()163+164+ rv = c.get('/')165+ self.assert_equal(rv.data, 'Hello from the Frontend')166+ rv = c.get('/admin/')167+ self.assert_equal(rv.data, 'Hello from the Admin')168+ rv = c.get('/admin/index2')169+ self.assert_equal(rv.data, 'Hello from the Admin')170+ rv = c.get('/admin/static/test.txt')171+ self.assert_equal(rv.data.strip(), 'Admin File')172+ rv = c.get('/admin/static/css/test.css')173+ self.assert_equal(rv.data.strip(), '/* nested file */')174+175+ with app.test_request_context():176+ self.assert_equal(flask.url_for('admin.static', filename='test.txt'),177+ '/admin/static/test.txt')178+179+ with app.test_request_context():180+ try:181+ flask.render_template('missing.html')182+ except TemplateNotFound, e:183+ self.assert_equal(e.name, 'missing.html')184+ else:185+ self.assert_(0, 'expected exception')186+187+ with flask.Flask(__name__).test_request_context():188+ self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested')189+190+ def test_safe_access(self):191+ app = moduleapp192+193+ with app.test_request_context():194+ f = app.view_functions['admin.static']195+196+ try:197+ f('/etc/passwd')198+ except NotFound:199+ pass200+ else:201+ self.assert_(0, 'expected exception')202+ try:203+ f('../__init__.py')204+ except NotFound:205+ pass206+ else:207+ self.assert_(0, 'expected exception')208+209+ # testcase for a security issue that may exist on windows systems210+ import os211+ import ntpath212+ old_path = os.path213+ os.path = ntpath214+ try:215+ try:216+ f('..\\__init__.py')217+ except NotFound:218+ pass219+ else:220+ self.assert_(0, 'expected exception')221+ finally:222+ os.path = old_path223+224+ @emits_module_deprecation_warning225+ def test_endpoint_decorator(self):226+ from werkzeug.routing import Submount, Rule227+ from flask import Module228+229+ app = flask.Flask(__name__)230+ app.testing = True231+ app.url_map.add(Submount('/foo', [232+ Rule('/bar', endpoint='bar'),233+ Rule('/', endpoint='index')234+ ]))235+ module = Module(__name__, __name__)236+237+ @module.endpoint('bar')238+ def bar():239+ return 'bar'240+241+ @module.endpoint('index')242+ def index():243+ return 'index'244+245+ app.register_module(module)246+247+ c = app.test_client()248+ self.assert_equal(c.get('/foo/').data, 'index')249+ self.assert_equal(c.get('/foo/bar').data, 'bar')250+251+252+class BlueprintTestCase(FlaskTestCase):253+254+ def test_blueprint_specific_error_handling(self):255+ frontend = flask.Blueprint('frontend', __name__)256+ backend = flask.Blueprint('backend', __name__)257+ sideend = flask.Blueprint('sideend', __name__)258+259+ @frontend.errorhandler(403)260+ def frontend_forbidden(e):261+ return 'frontend says no', 403262+263+ @frontend.route('/frontend-no')264+ def frontend_no():265+ flask.abort(403)266+267+ @backend.errorhandler(403)268+ def backend_forbidden(e):269+ return 'backend says no', 403270+271+ @backend.route('/backend-no')272+ def backend_no():273+ flask.abort(403)274+275+ @sideend.route('/what-is-a-sideend')276+ def sideend_no():277+ flask.abort(403)278+279+ app = flask.Flask(__name__)280+ app.register_blueprint(frontend)281+ app.register_blueprint(backend)282+ app.register_blueprint(sideend)283+284+ @app.errorhandler(403)285+ def app_forbidden(e):286+ return 'application itself says no', 403287+288+ c = app.test_client()289+290+ self.assert_equal(c.get('/frontend-no').data, 'frontend says no')291+ self.assert_equal(c.get('/backend-no').data, 'backend says no')292+ self.assert_equal(c.get('/what-is-a-sideend').data, 'application itself says no')293+294+ def test_blueprint_url_definitions(self):295+ bp = flask.Blueprint('test', __name__)296+297+ @bp.route('/foo', defaults={'baz': 42})298+ def foo(bar, baz):299+ return '%s/%d' % (bar, baz)300+301+ @bp.route('/bar')302+ def bar(bar):303+ return unicode(bar)304+305+ app = flask.Flask(__name__)306+ app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23})307+ app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19})308+309+ c = app.test_client()310+ self.assert_equal(c.get('/1/foo').data, u'23/42')311+ self.assert_equal(c.get('/2/foo').data, u'19/42')312+ self.assert_equal(c.get('/1/bar').data, u'23')313+ self.assert_equal(c.get('/2/bar').data, u'19')314+315+ def test_blueprint_url_processors(self):316+ bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')317+318+ @bp.url_defaults319+ def add_language_code(endpoint, values):320+ values.setdefault('lang_code', flask.g.lang_code)321+322+ @bp.url_value_preprocessor323+ def pull_lang_code(endpoint, values):324+ flask.g.lang_code = values.pop('lang_code')325+326+ @bp.route('/')327+ def index():328+ return flask.url_for('.about')329+330+ @bp.route('/about')331+ def about():332+ return flask.url_for('.index')333+334+ app = flask.Flask(__name__)335+ app.register_blueprint(bp)336+337+ c = app.test_client()338+339+ self.assert_equal(c.get('/de/').data, '/de/about')340+ self.assert_equal(c.get('/de/about').data, '/de/')341+342+ def test_templates_and_static(self):343+ from blueprintapp import app344+ c = app.test_client()345+346+ rv = c.get('/')347+ self.assert_equal(rv.data, 'Hello from the Frontend')348+ rv = c.get('/admin/')349+ self.assert_equal(rv.data, 'Hello from the Admin')350+ rv = c.get('/admin/index2')351+ self.assert_equal(rv.data, 'Hello from the Admin')352+ rv = c.get('/admin/static/test.txt')353+ self.assert_equal(rv.data.strip(), 'Admin File')354+ rv = c.get('/admin/static/css/test.css')355+ self.assert_equal(rv.data.strip(), '/* nested file */')356+357+ with app.test_request_context():358+ self.assert_equal(flask.url_for('admin.static', filename='test.txt'),359+ '/admin/static/test.txt')360+361+ with app.test_request_context():362+ try:363+ flask.render_template('missing.html')364+ except TemplateNotFound, e:365+ self.assert_equal(e.name, 'missing.html')366+ else:367+ self.assert_(0, 'expected exception')368+369+ with flask.Flask(__name__).test_request_context():370+ self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested')371+372+ def test_templates_list(self):373+ from blueprintapp import app374+ templates = sorted(app.jinja_env.list_templates())375+ self.assert_equal(templates, ['admin/index.html',376+ 'frontend/index.html'])377+378+ def test_dotted_names(self):379+ frontend = flask.Blueprint('myapp.frontend', __name__)380+ backend = flask.Blueprint('myapp.backend', __name__)381+382+ @frontend.route('/fe')383+ def frontend_index():384+ return flask.url_for('myapp.backend.backend_index')385+386+ @frontend.route('/fe2')387+ def frontend_page2():388+ return flask.url_for('.frontend_index')389+390+ @backend.route('/be')391+ def backend_index():392+ return flask.url_for('myapp.frontend.frontend_index')393+394+ app = flask.Flask(__name__)395+ app.register_blueprint(frontend)396+ app.register_blueprint(backend)397+398+ c = app.test_client()399+ self.assert_equal(c.get('/fe').data.strip(), '/be')400+ self.assert_equal(c.get('/fe2').data.strip(), '/fe')401+ self.assert_equal(c.get('/be').data.strip(), '/fe')402+403+ def test_empty_url_defaults(self):404+ bp = flask.Blueprint('bp', __name__)405+406+ @bp.route('/', defaults={'page': 1})407+ @bp.route('/page/<int:page>')408+ def something(page):409+ return str(page)410+411+ app = flask.Flask(__name__)412+ app.register_blueprint(bp)413+414+ c = app.test_client()415+ self.assert_equal(c.get('/').data, '1')416+ self.assert_equal(c.get('/page/2').data, '2')417+418+ def test_route_decorator_custom_endpoint(self):419+420+ bp = flask.Blueprint('bp', __name__)421+422+ @bp.route('/foo')423+ def foo():424+ return flask.request.endpoint425+426+ @bp.route('/bar', endpoint='bar')427+ def foo_bar():428+ return flask.request.endpoint429+430+ @bp.route('/bar/123', endpoint='123')431+ def foo_bar_foo():432+ return flask.request.endpoint433+434+ @bp.route('/bar/foo')435+ def bar_foo():436+ return flask.request.endpoint437+438+ app = flask.Flask(__name__)439+ app.register_blueprint(bp, url_prefix='/py')440+441+ @app.route('/')442+ def index():443+ return flask.request.endpoint444+445+ c = app.test_client()446+ self.assertEqual(c.get('/').data, 'index')447+ self.assertEqual(c.get('/py/foo').data, 'bp.foo')448+ self.assertEqual(c.get('/py/bar').data, 'bp.bar')449+ self.assertEqual(c.get('/py/bar/123').data, 'bp.123')450+ self.assertEqual(c.get('/py/bar/foo').data, 'bp.bar_foo')451+452+ def test_route_decorator_custom_endpoint_with_dots(self):453+ bp = flask.Blueprint('bp', __name__)454+455+ @bp.route('/foo')456+ def foo():457+ return flask.request.endpoint458+459+ try:460+ @bp.route('/bar', endpoint='bar.bar')461+ def foo_bar():462+ return flask.request.endpoint463+ except AssertionError:464+ pass465+ else:466+ raise AssertionError('expected AssertionError not raised')467+468+ try:469+ @bp.route('/bar/123', endpoint='bar.123')470+ def foo_bar_foo():471+ return flask.request.endpoint472+ except AssertionError:473+ pass474+ else:475+ raise AssertionError('expected AssertionError not raised')476+477+ def foo_foo_foo():478+ pass479+480+ self.assertRaises(481+ AssertionError,482+ lambda: bp.add_url_rule(483+ '/bar/123', endpoint='bar.123', view_func=foo_foo_foo484+ )485+ )486+487+ self.assertRaises(488+ AssertionError,489+ bp.route('/bar/123', endpoint='bar.123'),490+ lambda: None491+ )492+493+ app = flask.Flask(__name__)494+ app.register_blueprint(bp, url_prefix='/py')495+496+ c = app.test_client()497+ self.assertEqual(c.get('/py/foo').data, 'bp.foo')498+ # The rule's din't actually made it through499+ rv = c.get('/py/bar')500+ assert rv.status_code == 404501+ rv = c.get('/py/bar/123')502+ assert rv.status_code == 404503+504+505+def suite():506+ suite = unittest.TestSuite()507+ suite.addTest(unittest.makeSuite(BlueprintTestCase))508+ suite.addTest(unittest.makeSuite(ModuleTestCase))509+ return suiteadded:flask/testsuite/config.py+177 added
1+# -*- coding: utf-8 -*-2+"""3+ flask.testsuite.config4+ ~~~~~~~~~~~~~~~~~~~~~~5+6+ Configuration and instances.7+8+ :copyright: (c) 2011 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+import os12+import sys13+import flask14+import unittest15+from flask.testsuite import FlaskTestCase16+17+18+# config keys used for the ConfigTestCase19+TEST_KEY = 'foo'20+SECRET_KEY = 'devkey'21+22+23+class ConfigTestCase(FlaskTestCase):24+25+ def common_object_test(self, app):26+ self.assert_equal(app.secret_key, 'devkey')27+ self.assert_equal(app.config['TEST_KEY'], 'foo')28+ self.assert_('ConfigTestCase' not in app.config)29+30+ def test_config_from_file(self):31+ app = flask.Flask(__name__)32+ app.config.from_pyfile(__file__.rsplit('.', 1)[0] + '.py')33+ self.common_object_test(app)34+35+ def test_config_from_object(self):36+ app = flask.Flask(__name__)37+ app.config.from_object(__name__)38+ self.common_object_test(app)39+40+ def test_config_from_class(self):41+ class Base(object):42+ TEST_KEY = 'foo'43+ class Test(Base):44+ SECRET_KEY = 'devkey'45+ app = flask.Flask(__name__)46+ app.config.from_object(Test)47+ self.common_object_test(app)48+49+ def test_config_from_envvar(self):50+ env = os.environ51+ try:52+ os.environ = {}53+ app = flask.Flask(__name__)54+ try:55+ app.config.from_envvar('FOO_SETTINGS')56+ except RuntimeError, e:57+ self.assert_("'FOO_SETTINGS' is not set" in str(e))58+ else:59+ self.assert_(0, 'expected exception')60+ self.assert_(not app.config.from_envvar('FOO_SETTINGS', silent=True))61+62+ os.environ = {'FOO_SETTINGS': __file__.rsplit('.', 1)[0] + '.py'}63+ self.assert_(app.config.from_envvar('FOO_SETTINGS'))64+ self.common_object_test(app)65+ finally:66+ os.environ = env67+68+ def test_config_missing(self):69+ app = flask.Flask(__name__)70+ try:71+ app.config.from_pyfile('missing.cfg')72+ except IOError, e:73+ msg = str(e)74+ self.assert_(msg.startswith('[Errno 2] Unable to load configuration '75+ 'file (No such file or directory):'))76+ self.assert_(msg.endswith("missing.cfg'"))77+ else:78+ self.assert_(0, 'expected config')79+ self.assert_(not app.config.from_pyfile('missing.cfg', silent=True))80+81+82+class InstanceTestCase(FlaskTestCase):83+84+ def test_explicit_instance_paths(self):85+ here = os.path.abspath(os.path.dirname(__file__))86+ try:87+ flask.Flask(__name__, instance_path='instance')88+ except ValueError, e:89+ self.assert_('must be absolute' in str(e))90+ else:91+ self.fail('Expected value error')92+93+ app = flask.Flask(__name__, instance_path=here)94+ self.assert_equal(app.instance_path, here)95+96+ def test_uninstalled_module_paths(self):97+ from config_module_app import app98+ here = os.path.abspath(os.path.dirname(__file__))99+ self.assert_equal(app.instance_path, os.path.join(here, 'test_apps', 'instance'))100+101+ def test_uninstalled_package_paths(self):102+ from config_package_app import app103+ here = os.path.abspath(os.path.dirname(__file__))104+ self.assert_equal(app.instance_path, os.path.join(here, 'test_apps', 'instance'))105+106+ def test_installed_module_paths(self):107+ import types108+ expected_prefix = os.path.abspath('foo')109+ mod = types.ModuleType('myapp')110+ mod.__file__ = os.path.join(expected_prefix, 'lib', 'python2.5',111+ 'site-packages', 'myapp.py')112+ sys.modules['myapp'] = mod113+ try:114+ mod.app = flask.Flask(mod.__name__)115+ self.assert_equal(mod.app.instance_path,116+ os.path.join(expected_prefix, 'var',117+ 'myapp-instance'))118+ finally:119+ sys.modules['myapp'] = None120+121+ def test_installed_package_paths(self):122+ import types123+ expected_prefix = os.path.abspath('foo')124+ package_path = os.path.join(expected_prefix, 'lib', 'python2.5',125+ 'site-packages', 'myapp')126+ mod = types.ModuleType('myapp')127+ mod.__path__ = [package_path]128+ mod.__file__ = os.path.join(package_path, '__init__.py')129+ sys.modules['myapp'] = mod130+ try:131+ mod.app = flask.Flask(mod.__name__)132+ self.assert_equal(mod.app.instance_path,133+ os.path.join(expected_prefix, 'var',134+ 'myapp-instance'))135+ finally:136+ sys.modules['myapp'] = None137+138+ def test_prefix_installed_paths(self):139+ import types140+ expected_prefix = os.path.abspath(sys.prefix)141+ package_path = os.path.join(expected_prefix, 'lib', 'python2.5',142+ 'site-packages', 'myapp')143+ mod = types.ModuleType('myapp')144+ mod.__path__ = [package_path]145+ mod.__file__ = os.path.join(package_path, '__init__.py')146+ sys.modules['myapp'] = mod147+ try:148+ mod.app = flask.Flask(mod.__name__)149+ self.assert_equal(mod.app.instance_path,150+ os.path.join(expected_prefix, 'var',151+ 'myapp-instance'))152+ finally:153+ sys.modules['myapp'] = None154+155+ def test_egg_installed_paths(self):156+ import types157+ expected_prefix = os.path.abspath(sys.prefix)158+ package_path = os.path.join(expected_prefix, 'lib', 'python2.5',159+ 'site-packages', 'MyApp.egg', 'myapp')160+ mod = types.ModuleType('myapp')161+ mod.__path__ = [package_path]162+ mod.__file__ = os.path.join(package_path, '__init__.py')163+ sys.modules['myapp'] = mod164+ try:165+ mod.app = flask.Flask(mod.__name__)166+ self.assert_equal(mod.app.instance_path,167+ os.path.join(expected_prefix, 'var',168+ 'myapp-instance'))169+ finally:170+ sys.modules['myapp'] = None171+172+173+def suite():174+ suite = unittest.TestSuite()175+ suite.addTest(unittest.makeSuite(ConfigTestCase))176+ suite.addTest(unittest.makeSuite(InstanceTestCase))177+ return suiteadded:flask/testsuite/deprecations.py+38 added
1+# -*- coding: utf-8 -*-2+"""3+ flask.testsuite.deprecations4+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~5+6+ Tests deprecation support.7+8+ :copyright: (c) 2011 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+import flask12+import unittest13+from flask.testsuite import FlaskTestCase, catch_warnings14+15+16+class DeprecationsTestCase(FlaskTestCase):17+18+ def test_init_jinja_globals(self):19+ class MyFlask(flask.Flask):20+ def init_jinja_globals(self):21+ self.jinja_env.globals['foo'] = '42'22+23+ with catch_warnings() as log:24+ app = MyFlask(__name__)25+ @app.route('/')26+ def foo():27+ return app.jinja_env.globals['foo']28+29+ c = app.test_client()30+ self.assert_equal(c.get('/').data, '42')31+ self.assert_equal(len(log), 1)32+ self.assert_('init_jinja_globals' in str(log[0]['message']))33+34+35+def suite():36+ suite = unittest.TestSuite()37+ suite.addTest(unittest.makeSuite(DeprecationsTestCase))38+ return suiteadded:flask/testsuite/examples.py+38 added
1+# -*- coding: utf-8 -*-2+"""3+ flask.testsuite.examples4+ ~~~~~~~~~~~~~~~~~~~~~~~~5+6+ Tests the examples.7+8+ :copyright: (c) 2011 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+import os12+import unittest13+from flask.testsuite import add_to_path14+15+16+def setup_path():17+ example_path = os.path.join(os.path.dirname(__file__),18+ os.pardir, os.pardir, 'examples')19+ add_to_path(os.path.join(example_path, 'flaskr'))20+ add_to_path(os.path.join(example_path, 'minitwit'))21+22+23+def suite():24+ setup_path()25+ suite = unittest.TestSuite()26+ try:27+ from minitwit_tests import MiniTwitTestCase28+ except ImportError:29+ pass30+ else:31+ suite.addTest(unittest.makeSuite(MiniTwitTestCase))32+ try:33+ from flaskr_tests import FlaskrTestCase34+ except ImportError:35+ pass36+ else:37+ suite.addTest(unittest.makeSuite(FlaskrTestCase))38+ return suiteadded:flask/testsuite/helpers.py+295 added
1+# -*- coding: utf-8 -*-2+"""3+ flask.testsuite.helpers4+ ~~~~~~~~~~~~~~~~~~~~~~~5+6+ Various helpers.7+8+ :copyright: (c) 2011 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+import os12+import flask13+import unittest14+from logging import StreamHandler15+from StringIO import StringIO16+from flask.testsuite import FlaskTestCase, catch_warnings, catch_stderr17+from werkzeug.http import parse_options_header18+19+20+def has_encoding(name):21+ try:22+ import codecs23+ codecs.lookup(name)24+ return True25+ except LookupError:26+ return False27+28+29+class JSONTestCase(FlaskTestCase):30+31+ def test_json_bad_requests(self):32+ app = flask.Flask(__name__)33+ @app.route('/json', methods=['POST'])34+ def return_json():35+ return unicode(flask.request.json)36+ c = app.test_client()37+ rv = c.post('/json', data='malformed', content_type='application/json')38+ self.assert_equal(rv.status_code, 400)39+40+ def test_json_body_encoding(self):41+ app = flask.Flask(__name__)42+ app.testing = True43+ @app.route('/')44+ def index():45+ return flask.request.json46+47+ c = app.test_client()48+ resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),49+ content_type='application/json; charset=iso-8859-15')50+ self.assert_equal(resp.data, u'Hällo Wörld'.encode('utf-8'))51+52+ def test_jsonify(self):53+ d = dict(a=23, b=42, c=[1, 2, 3])54+ app = flask.Flask(__name__)55+ @app.route('/kw')56+ def return_kwargs():57+ return flask.jsonify(**d)58+ @app.route('/dict')59+ def return_dict():60+ return flask.jsonify(d)61+ c = app.test_client()62+ for url in '/kw', '/dict':63+ rv = c.get(url)64+ self.assert_equal(rv.mimetype, 'application/json')65+ self.assert_equal(flask.json.loads(rv.data), d)66+67+ def test_json_attr(self):68+ app = flask.Flask(__name__)69+ @app.route('/add', methods=['POST'])70+ def add():71+ return unicode(flask.request.json['a'] + flask.request.json['b'])72+ c = app.test_client()73+ rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),74+ content_type='application/json')75+ self.assert_equal(rv.data, '3')76+77+ def test_template_escaping(self):78+ app = flask.Flask(__name__)79+ render = flask.render_template_string80+ with app.test_request_context():81+ rv = render('{{ "</script>"|tojson|safe }}')82+ self.assert_equal(rv, '"<\\/script>"')83+ rv = render('{{ "<\0/script>"|tojson|safe }}')84+ self.assert_equal(rv, '"<\\u0000\\/script>"')85+86+ def test_modified_url_encoding(self):87+ class ModifiedRequest(flask.Request):88+ url_charset = 'euc-kr'89+ app = flask.Flask(__name__)90+ app.request_class = ModifiedRequest91+ app.url_map.charset = 'euc-kr'92+93+ @app.route('/')94+ def index():95+ return flask.request.args['foo']96+97+ rv = app.test_client().get(u'/?foo=정상처리'.encode('euc-kr'))98+ self.assert_equal(rv.status_code, 200)99+ self.assert_equal(rv.data, u'정상처리'.encode('utf-8'))100+101+ if not has_encoding('euc-kr'):102+ test_modified_url_encoding = None103+104+105+class SendfileTestCase(FlaskTestCase):106+107+ def test_send_file_regular(self):108+ app = flask.Flask(__name__)109+ with app.test_request_context():110+ rv = flask.send_file('static/index.html')111+ self.assert_(rv.direct_passthrough)112+ self.assert_equal(rv.mimetype, 'text/html')113+ with app.open_resource('static/index.html') as f:114+ self.assert_equal(rv.data, f.read())115+116+ def test_send_file_xsendfile(self):117+ app = flask.Flask(__name__)118+ app.use_x_sendfile = True119+ with app.test_request_context():120+ rv = flask.send_file('static/index.html')121+ self.assert_(rv.direct_passthrough)122+ self.assert_('x-sendfile' in rv.headers)123+ self.assert_equal(rv.headers['x-sendfile'],124+ os.path.join(app.root_path, 'static/index.html'))125+ self.assert_equal(rv.mimetype, 'text/html')126+127+ def test_send_file_object(self):128+ app = flask.Flask(__name__)129+ with catch_warnings() as captured:130+ with app.test_request_context():131+ f = open(os.path.join(app.root_path, 'static/index.html'))132+ rv = flask.send_file(f)133+ with app.open_resource('static/index.html') as f:134+ self.assert_equal(rv.data, f.read())135+ self.assert_equal(rv.mimetype, 'text/html')136+ # mimetypes + etag137+ self.assert_equal(len(captured), 2)138+139+ app.use_x_sendfile = True140+ with catch_warnings() as captured:141+ with app.test_request_context():142+ f = open(os.path.join(app.root_path, 'static/index.html'))143+ rv = flask.send_file(f)144+ self.assert_equal(rv.mimetype, 'text/html')145+ self.assert_('x-sendfile' in rv.headers)146+ self.assert_equal(rv.headers['x-sendfile'],147+ os.path.join(app.root_path, 'static/index.html'))148+ # mimetypes + etag149+ self.assert_equal(len(captured), 2)150+151+ app.use_x_sendfile = False152+ with app.test_request_context():153+ with catch_warnings() as captured:154+ f = StringIO('Test')155+ rv = flask.send_file(f)156+ self.assert_equal(rv.data, 'Test')157+ self.assert_equal(rv.mimetype, 'application/octet-stream')158+ # etags159+ self.assert_equal(len(captured), 1)160+ with catch_warnings() as captured:161+ f = StringIO('Test')162+ rv = flask.send_file(f, mimetype='text/plain')163+ self.assert_equal(rv.data, 'Test')164+ self.assert_equal(rv.mimetype, 'text/plain')165+ # etags166+ self.assert_equal(len(captured), 1)167+168+ app.use_x_sendfile = True169+ with catch_warnings() as captured:170+ with app.test_request_context():171+ f = StringIO('Test')172+ rv = flask.send_file(f)173+ self.assert_('x-sendfile' not in rv.headers)174+ # etags175+ self.assert_equal(len(captured), 1)176+177+ def test_attachment(self):178+ app = flask.Flask(__name__)179+ with catch_warnings() as captured:180+ with app.test_request_context():181+ f = open(os.path.join(app.root_path, 'static/index.html'))182+ rv = flask.send_file(f, as_attachment=True)183+ value, options = parse_options_header(rv.headers['Content-Disposition'])184+ self.assert_equal(value, 'attachment')185+ # mimetypes + etag186+ self.assert_equal(len(captured), 2)187+188+ with app.test_request_context():189+ self.assert_equal(options['filename'], 'index.html')190+ rv = flask.send_file('static/index.html', as_attachment=True)191+ value, options = parse_options_header(rv.headers['Content-Disposition'])192+ self.assert_equal(value, 'attachment')193+ self.assert_equal(options['filename'], 'index.html')194+195+ with app.test_request_context():196+ rv = flask.send_file(StringIO('Test'), as_attachment=True,197+ attachment_filename='index.txt',198+ add_etags=False)199+ self.assert_equal(rv.mimetype, 'text/plain')200+ value, options = parse_options_header(rv.headers['Content-Disposition'])201+ self.assert_equal(value, 'attachment')202+ self.assert_equal(options['filename'], 'index.txt')203+204+205+class LoggingTestCase(FlaskTestCase):206+207+ def test_logger_cache(self):208+ app = flask.Flask(__name__)209+ logger1 = app.logger210+ self.assert_(app.logger is logger1)211+ self.assert_equal(logger1.name, __name__)212+ app.logger_name = __name__ + '/test_logger_cache'213+ self.assert_(app.logger is not logger1)214+215+ def test_debug_log(self):216+ app = flask.Flask(__name__)217+ app.debug = True218+219+ @app.route('/')220+ def index():221+ app.logger.warning('the standard library is dead')222+ app.logger.debug('this is a debug statement')223+ return ''224+225+ @app.route('/exc')226+ def exc():227+ 1/0228+229+ with app.test_client() as c:230+ with catch_stderr() as err:231+ c.get('/')232+ out = err.getvalue()233+ self.assert_('WARNING in helpers [' in out)234+ self.assert_(os.path.basename(__file__.rsplit('.', 1)[0] + '.py') in out)235+ self.assert_('the standard library is dead' in out)236+ self.assert_('this is a debug statement' in out)237+238+ with catch_stderr() as err:239+ try:240+ c.get('/exc')241+ except ZeroDivisionError:242+ pass243+ else:244+ self.assert_(False, 'debug log ate the exception')245+246+ def test_exception_logging(self):247+ out = StringIO()248+ app = flask.Flask(__name__)249+ app.logger_name = 'flask_tests/test_exception_logging'250+ app.logger.addHandler(StreamHandler(out))251+252+ @app.route('/')253+ def index():254+ 1/0255+256+ rv = app.test_client().get('/')257+ self.assert_equal(rv.status_code, 500)258+ self.assert_('Internal Server Error' in rv.data)259+260+ err = out.getvalue()261+ self.assert_('Exception on / [GET]' in err)262+ self.assert_('Traceback (most recent call last):' in err)263+ self.assert_('1/0' in err)264+ self.assert_('ZeroDivisionError:' in err)265+266+ def test_processor_exceptions(self):267+ app = flask.Flask(__name__)268+ @app.before_request269+ def before_request():270+ if trigger == 'before':271+ 1/0272+ @app.after_request273+ def after_request(response):274+ if trigger == 'after':275+ 1/0276+ return response277+ @app.route('/')278+ def index():279+ return 'Foo'280+ @app.errorhandler(500)281+ def internal_server_error(e):282+ return 'Hello Server Error', 500283+ for trigger in 'before', 'after':284+ rv = app.test_client().get('/')285+ self.assert_equal(rv.status_code, 500)286+ self.assert_equal(rv.data, 'Hello Server Error')287+288+289+def suite():290+ suite = unittest.TestSuite()291+ if flask.json_available:292+ suite.addTest(unittest.makeSuite(JSONTestCase))293+ suite.addTest(unittest.makeSuite(SendfileTestCase))294+ suite.addTest(unittest.makeSuite(LoggingTestCase))295+ return suiteadded:flask/testsuite/signals.py+103 added
1+# -*- coding: utf-8 -*-2+"""3+ flask.testsuite.signals4+ ~~~~~~~~~~~~~~~~~~~~~~~5+6+ Signalling.7+8+ :copyright: (c) 2011 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+import flask12+import unittest13+from flask.testsuite import FlaskTestCase14+15+16+class SignalsTestCase(FlaskTestCase):17+18+ def test_template_rendered(self):19+ app = flask.Flask(__name__)20+21+ @app.route('/')22+ def index():23+ return flask.render_template('simple_template.html', whiskey=42)24+25+ recorded = []26+ def record(sender, template, context):27+ recorded.append((template, context))28+29+ flask.template_rendered.connect(record, app)30+ try:31+ app.test_client().get('/')32+ self.assert_equal(len(recorded), 1)33+ template, context = recorded[0]34+ self.assert_equal(template.name, 'simple_template.html')35+ self.assert_equal(context['whiskey'], 42)36+ finally:37+ flask.template_rendered.disconnect(record, app)38+39+ def test_request_signals(self):40+ app = flask.Flask(__name__)41+ calls = []42+43+ def before_request_signal(sender):44+ calls.append('before-signal')45+46+ def after_request_signal(sender, response):47+ self.assert_equal(response.data, 'stuff')48+ calls.append('after-signal')49+50+ @app.before_request51+ def before_request_handler():52+ calls.append('before-handler')53+54+ @app.after_request55+ def after_request_handler(response):56+ calls.append('after-handler')57+ response.data = 'stuff'58+ return response59+60+ @app.route('/')61+ def index():62+ calls.append('handler')63+ return 'ignored anyway'64+65+ flask.request_started.connect(before_request_signal, app)66+ flask.request_finished.connect(after_request_signal, app)67+68+ try:69+ rv = app.test_client().get('/')70+ self.assert_equal(rv.data, 'stuff')71+72+ self.assert_equal(calls, ['before-signal', 'before-handler',73+ 'handler', 'after-handler',74+ 'after-signal'])75+ finally:76+ flask.request_started.disconnect(before_request_signal, app)77+ flask.request_finished.disconnect(after_request_signal, app)78+79+ def test_request_exception_signal(self):80+ app = flask.Flask(__name__)81+ recorded = []82+83+ @app.route('/')84+ def index():85+ 1/086+87+ def record(sender, exception):88+ recorded.append(exception)89+90+ flask.got_request_exception.connect(record, app)91+ try:92+ self.assert_equal(app.test_client().get('/').status_code, 500)93+ self.assert_equal(len(recorded), 1)94+ self.assert_(isinstance(recorded[0], ZeroDivisionError))95+ finally:96+ flask.got_request_exception.disconnect(record, app)97+98+99+def suite():100+ suite = unittest.TestSuite()101+ if flask.signals_available:102+ suite.addTest(unittest.makeSuite(SignalsTestCase))103+ return suiteadded:flask/testsuite/templating.py+141 added
1+# -*- coding: utf-8 -*-2+"""3+ flask.testsuite.templating4+ ~~~~~~~~~~~~~~~~~~~~~~~~~~5+6+ Template functionality7+8+ :copyright: (c) 2011 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+import flask12+import unittest13+from flask.testsuite import FlaskTestCase14+15+16+class TemplatingTestCase(FlaskTestCase):17+18+ def test_context_processing(self):19+ app = flask.Flask(__name__)20+ @app.context_processor21+ def context_processor():22+ return {'injected_value': 42}23+ @app.route('/')24+ def index():25+ return flask.render_template('context_template.html', value=23)26+ rv = app.test_client().get('/')27+ self.assert_equal(rv.data, '<p>23|42')28+29+ def test_original_win(self):30+ app = flask.Flask(__name__)31+ @app.route('/')32+ def index():33+ return flask.render_template_string('{{ config }}', config=42)34+ rv = app.test_client().get('/')35+ self.assert_equal(rv.data, '42')36+37+ def test_standard_context(self):38+ app = flask.Flask(__name__)39+ app.secret_key = 'development key'40+ @app.route('/')41+ def index():42+ flask.g.foo = 2343+ flask.session['test'] = 'aha'44+ return flask.render_template_string('''45+ {{ request.args.foo }}46+ {{ g.foo }}47+ {{ config.DEBUG }}48+ {{ session.test }}49+ ''')50+ rv = app.test_client().get('/?foo=42')51+ self.assert_equal(rv.data.split(), ['42', '23', 'False', 'aha'])52+53+ def test_escaping(self):54+ text = '<p>Hello World!'55+ app = flask.Flask(__name__)56+ @app.route('/')57+ def index():58+ return flask.render_template('escaping_template.html', text=text,59+ html=flask.Markup(text))60+ lines = app.test_client().get('/').data.splitlines()61+ self.assert_equal(lines, [62+ '<p>Hello World!',63+ '<p>Hello World!',64+ '<p>Hello World!',65+ '<p>Hello World!',66+ '<p>Hello World!',67+ '<p>Hello World!'68+ ])69+70+ def test_no_escaping(self):71+ app = flask.Flask(__name__)72+ with app.test_request_context():73+ self.assert_equal(flask.render_template_string('{{ foo }}',74+ foo='<test>'), '<test>')75+ self.assert_equal(flask.render_template('mail.txt', foo='<test>'),76+ '<test> Mail')77+78+ def test_macros(self):79+ app = flask.Flask(__name__)80+ with app.test_request_context():81+ macro = flask.get_template_attribute('_macro.html', 'hello')82+ self.assert_equal(macro('World'), 'Hello World!')83+84+ def test_template_filter(self):85+ app = flask.Flask(__name__)86+ @app.template_filter()87+ def my_reverse(s):88+ return s[::-1]89+ self.assert_('my_reverse' in app.jinja_env.filters.keys())90+ self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)91+ self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba')92+93+ def test_template_filter_with_name(self):94+ app = flask.Flask(__name__)95+ @app.template_filter('strrev')96+ def my_reverse(s):97+ return s[::-1]98+ self.assert_('strrev' in app.jinja_env.filters.keys())99+ self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)100+ self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba')101+102+ def test_template_filter_with_template(self):103+ app = flask.Flask(__name__)104+ @app.template_filter()105+ def super_reverse(s):106+ return s[::-1]107+ @app.route('/')108+ def index():109+ return flask.render_template('template_filter.html', value='abcd')110+ rv = app.test_client().get('/')111+ self.assert_equal(rv.data, 'dcba')112+113+ def test_template_filter_with_name_and_template(self):114+ app = flask.Flask(__name__)115+ @app.template_filter('super_reverse')116+ def my_reverse(s):117+ return s[::-1]118+ @app.route('/')119+ def index():120+ return flask.render_template('template_filter.html', value='abcd')121+ rv = app.test_client().get('/')122+ self.assert_equal(rv.data, 'dcba')123+124+ def test_custom_template_loader(self):125+ class MyFlask(flask.Flask):126+ def create_global_jinja_loader(self):127+ from jinja2 import DictLoader128+ return DictLoader({'index.html': 'Hello Custom World!'})129+ app = MyFlask(__name__)130+ @app.route('/')131+ def index():132+ return flask.render_template('index.html')133+ c = app.test_client()134+ rv = c.get('/')135+ self.assert_equal(rv.data, 'Hello Custom World!')136+137+138+def suite():139+ suite = unittest.TestSuite()140+ suite.addTest(unittest.makeSuite(TemplatingTestCase))141+ return suiteadded:flask/testsuite/testing.py+165 added
1+# -*- coding: utf-8 -*-2+"""3+ flask.testsuite.testing4+ ~~~~~~~~~~~~~~~~~~~~~~~5+6+ Test client and more.7+8+ :copyright: (c) 2011 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+import flask12+import unittest13+from flask.testsuite import FlaskTestCase14+15+16+class TestToolsTestCase(FlaskTestCase):17+18+ def test_environ_defaults_from_config(self):19+ app = flask.Flask(__name__)20+ app.testing = True21+ app.config['SERVER_NAME'] = 'example.com:1234'22+ app.config['APPLICATION_ROOT'] = '/foo'23+ @app.route('/')24+ def index():25+ return flask.request.url26+27+ ctx = app.test_request_context()28+ self.assert_equal(ctx.request.url, 'http://example.com:1234/foo/')29+ with app.test_client() as c:30+ rv = c.get('/')31+ self.assert_equal(rv.data, 'http://example.com:1234/foo/')32+33+ def test_environ_defaults(self):34+ app = flask.Flask(__name__)35+ app.testing = True36+ @app.route('/')37+ def index():38+ return flask.request.url39+40+ ctx = app.test_request_context()41+ self.assert_equal(ctx.request.url, 'http://localhost/')42+ with app.test_client() as c:43+ rv = c.get('/')44+ self.assert_equal(rv.data, 'http://localhost/')45+46+ def test_session_transactions(self):47+ app = flask.Flask(__name__)48+ app.testing = True49+ app.secret_key = 'testing'50+51+ @app.route('/')52+ def index():53+ return unicode(flask.session['foo'])54+55+ with app.test_client() as c:56+ with c.session_transaction() as sess:57+ self.assert_equal(len(sess), 0)58+ sess['foo'] = [42]59+ self.assert_equal(len(sess), 1)60+ rv = c.get('/')61+ self.assert_equal(rv.data, '[42]')62+63+ def test_session_transactions_no_null_sessions(self):64+ app = flask.Flask(__name__)65+ app.testing = True66+67+ with app.test_client() as c:68+ try:69+ with c.session_transaction() as sess:70+ pass71+ except RuntimeError, e:72+ self.assert_('Session backend did not open a session' in str(e))73+ else:74+ self.fail('Expected runtime error')75+76+ def test_session_transactions_keep_context(self):77+ app = flask.Flask(__name__)78+ app.testing = True79+ app.secret_key = 'testing'80+81+ with app.test_client() as c:82+ rv = c.get('/')83+ req = flask.request._get_current_object()84+ with c.session_transaction():85+ self.assert_(req is flask.request._get_current_object())86+87+ def test_session_transaction_needs_cookies(self):88+ app = flask.Flask(__name__)89+ app.testing = True90+ c = app.test_client(use_cookies=False)91+ try:92+ with c.session_transaction() as s:93+ pass94+ except RuntimeError, e:95+ self.assert_('cookies' in str(e))96+ else:97+ self.fail('Expected runtime error')98+99+ def test_test_client_context_binding(self):100+ app = flask.Flask(__name__)101+ @app.route('/')102+ def index():103+ flask.g.value = 42104+ return 'Hello World!'105+106+ @app.route('/other')107+ def other():108+ 1/0109+110+ with app.test_client() as c:111+ resp = c.get('/')112+ self.assert_equal(flask.g.value, 42)113+ self.assert_equal(resp.data, 'Hello World!')114+ self.assert_equal(resp.status_code, 200)115+116+ resp = c.get('/other')117+ self.assert_(not hasattr(flask.g, 'value'))118+ self.assert_('Internal Server Error' in resp.data)119+ self.assert_equal(resp.status_code, 500)120+ flask.g.value = 23121+122+ try:123+ flask.g.value124+ except (AttributeError, RuntimeError):125+ pass126+ else:127+ raise AssertionError('some kind of exception expected')128+129+ def test_reuse_client(self):130+ app = flask.Flask(__name__)131+ c = app.test_client()132+133+ with c:134+ self.assert_equal(c.get('/').status_code, 404)135+136+ with c:137+ self.assert_equal(c.get('/').status_code, 404)138+139+ def test_test_client_calls_teardown_handlers(self):140+ app = flask.Flask(__name__)141+ called = []142+ @app.teardown_request143+ def remember(error):144+ called.append(error)145+146+ with app.test_client() as c:147+ self.assert_equal(called, [])148+ c.get('/')149+ self.assert_equal(called, [])150+ self.assert_equal(called, [None])151+152+ del called[:]153+ with app.test_client() as c:154+ self.assert_equal(called, [])155+ c.get('/')156+ self.assert_equal(called, [])157+ c.get('/')158+ self.assert_equal(called, [None])159+ self.assert_equal(called, [None, None])160+161+162+def suite():163+ suite = unittest.TestSuite()164+ suite.addTest(unittest.makeSuite(TestToolsTestCase))165+ return suiteadded:flask/testsuite/views.py+117 added
1+# -*- coding: utf-8 -*-2+"""3+ flask.testsuite.views4+ ~~~~~~~~~~~~~~~~~~~~~5+6+ Pluggable views.7+8+ :copyright: (c) 2011 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+import flask12+import flask.views13+import unittest14+from flask.testsuite import FlaskTestCase15+from werkzeug.http import parse_set_header16+17+18+class ViewTestCase(FlaskTestCase):19+20+ def common_test(self, app):21+ c = app.test_client()22+23+ self.assert_equal(c.get('/').data, 'GET')24+ self.assert_equal(c.post('/').data, 'POST')25+ self.assert_equal(c.put('/').status_code, 405)26+ meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])27+ self.assert_equal(sorted(meths), ['GET', 'HEAD', 'OPTIONS', 'POST'])28+29+ def test_basic_view(self):30+ app = flask.Flask(__name__)31+32+ class Index(flask.views.View):33+ methods = ['GET', 'POST']34+ def dispatch_request(self):35+ return flask.request.method36+37+ app.add_url_rule('/', view_func=Index.as_view('index'))38+ self.common_test(app)39+40+ def test_method_based_view(self):41+ app = flask.Flask(__name__)42+43+ class Index(flask.views.MethodView):44+ def get(self):45+ return 'GET'46+ def post(self):47+ return 'POST'48+49+ app.add_url_rule('/', view_func=Index.as_view('index'))50+51+ self.common_test(app)52+53+ def test_view_patching(self):54+ app = flask.Flask(__name__)55+56+ class Index(flask.views.MethodView):57+ def get(self):58+ 1/059+ def post(self):60+ 1/061+62+ class Other(Index):63+ def get(self):64+ return 'GET'65+ def post(self):66+ return 'POST'67+68+ view = Index.as_view('index')69+ view.view_class = Other70+ app.add_url_rule('/', view_func=view)71+ self.common_test(app)72+73+ def test_view_inheritance(self):74+ app = flask.Flask(__name__)75+76+ class Index(flask.views.MethodView):77+ def get(self):78+ return 'GET'79+ def post(self):80+ return 'POST'81+82+ class BetterIndex(Index):83+ def delete(self):84+ return 'DELETE'85+86+ app.add_url_rule('/', view_func=BetterIndex.as_view('index'))87+ c = app.test_client()88+89+ meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])90+ self.assert_equal(sorted(meths), ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST'])91+92+ def test_view_decorators(self):93+ app = flask.Flask(__name__)94+95+ def add_x_parachute(f):96+ def new_function(*args, **kwargs):97+ resp = flask.make_response(f(*args, **kwargs))98+ resp.headers['X-Parachute'] = 'awesome'99+ return resp100+ return new_function101+102+ class Index(flask.views.View):103+ decorators = [add_x_parachute]104+ def dispatch_request(self):105+ return 'Awesome'106+107+ app.add_url_rule('/', view_func=Index.as_view('index'))108+ c = app.test_client()109+ rv = c.get('/')110+ self.assert_equal(rv.headers['X-Parachute'], 'awesome')111+ self.assert_equal(rv.data, 'Awesome')112+113+114+def suite():115+ suite = unittest.TestSuite()116+ suite.addTest(unittest.makeSuite(ViewTestCase))117+ return suitemodified:flask/app.py+42 added-31 removed
229 unmodified lines230 'TESTING': False,231 'PROPAGATE_EXCEPTIONS': None,232 'PRESERVE_CONTEXT_ON_EXCEPTION': None,233 'SECRET_KEY': None,234- 'SESSION_COOKIE_NAME': 'session',234 'PERMANENT_SESSION_LIFETIME': timedelta(days=31),235 'USE_X_SENDFILE': False,236 'LOGGER_NAME': None,237 'SERVER_NAME': None,238+ 'APPLICATION_ROOT': None,239+ 'SESSION_COOKIE_NAME': 'session',240+ 'SESSION_COOKIE_DOMAIN': None,241+ 'SESSION_COOKIE_PATH': None,242+ 'SESSION_COOKIE_HTTPONLY': True,243+ 'SESSION_COOKIE_SECURE': False,244 'MAX_CONTENT_LENGTH': None,245 'TRAP_BAD_REQUEST_ERRORS': False,246 'TRAP_HTTP_EXCEPTIONS': False247 })461 unmodified lines709 with app.test_client() as c:710 rv = c.get('/?vodka=42')711 assert request.args['vodka'] == '42'712 713+ See :class:`~flask.testing.FlaskClient` for more information.714+715 .. versionchanged:: 0.4716 added support for `with` block usage for the client.717 718 .. versionadded:: 0.7504 unmodified lines1223 raise exc_type, exc_value, tb1224 else:1225 raise e1226 1220- self.logger.exception('Exception on %s [%s]' % (1221- request.path,1222- request.method1223- ))1227+ self.log_exception((exc_type, exc_value, tb))1228 if handler is None:1229 return InternalServerError()1230 return handler(e)1231 1232+ def log_exception(self, exc_info):1233+ """Logs an exception. This is called by :meth:`handle_exception`1234+ if debugging is disabled and right before the handler is called.1235+ The default implementation logs the exception as error on the1236+ :attr:`logger`.1237+1238+ .. versionadded:: 0.81239+ """1240+ self.logger.error('Exception on %s [%s]' % (1241+ request.path,1242+ request.method1243+ ), exc_info=exc_info)1244+1245 def raise_routing_exception(self, request):1246 """Exceptions that are recording during routing are reraised with1247 this method. During debug we are not reraising redirect requests1248 for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising73 unmodified lines1322 behaviour of `OPTIONS` responses.1323 1324 .. versionadded:: 0.71325 """1326+ adapter = _request_ctx_stack.top.url_adapter1309- # This would be nicer in Werkzeug 0.7, which however currently1310- # is not released. Werkzeug 0.7 provides a method called1311- # allowed_methods() that returns all methods that are valid for1312- # a given path.1313- methods = []1314- try:1315- _request_ctx_stack.top.url_adapter.match(method='--')1316- except MethodNotAllowed, e:1317- methods = e.valid_methods1318- except HTTPException, e:1319- pass1327+ if hasattr(adapter, 'allowed_methods'):1328+ methods = adapter.allowed_methods()1329+ else:1330+ # fallback for Werkzeug < 0.71331+ methods = []1332+ try:1333+ adapter.match(method='--')1334+ except MethodNotAllowed, e:1335+ methods = e.valid_methods1336+ except HTTPException, e:1337+ pass1338 rv = self.response_class()1339 rv.allow.update(methods)1340 return rv1341 62 unmodified lines1404 1405 This also triggers the :meth:`url_value_processor` functions before1406 the actualy :meth:`before_request` functions are called.1407 """1390- bp = request.blueprint1408+ bp = _request_ctx_stack.top.request.blueprint1409 1410 funcs = self.url_value_preprocessors.get(None, ())1411 if bp is not None and bp in self.url_value_preprocessors:1412 funcs = chain(funcs, self.url_value_preprocessors[bp])41 unmodified lines1454 triggered when the request context is popped. That way we have a1455 tighter control over certain resources under testing environments.1456 """1457 funcs = reversed(self.teardown_request_funcs.get(None, ()))1440- bp = request.blueprint1458+ bp = _request_ctx_stack.top.request.blueprint1459 if bp is not None and bp in self.teardown_request_funcs:1460 funcs = chain(funcs, reversed(self.teardown_request_funcs[bp]))1461 exc = sys.exc_info()[1]1462 for func in funcs:36 unmodified lines1499 """Creates a WSGI environment from the given values (see1500 :func:`werkzeug.test.EnvironBuilder` for more information, this1501 function accepts the same arguments).1502 """1485- from werkzeug.test import create_environ1486- environ_overrides = kwargs.setdefault('environ_overrides', {})1487- if self.config.get('SERVER_NAME'):1488- server_name = self.config.get('SERVER_NAME')1489- if ':' not in server_name:1490- http_host, http_port = server_name, '80'1491- else:1492- http_host, http_port = server_name.split(':', 1)1503+ from flask.testing import make_test_environ_builder1504+ builder = make_test_environ_builder(self, *args, **kwargs)1505+ try:1506+ return self.request_context(builder.get_environ())1507+ finally:1508+ builder.close()1509 1494- environ_overrides.setdefault('SERVER_NAME', server_name)1495- environ_overrides.setdefault('HTTP_HOST', server_name)1496- environ_overrides.setdefault('SERVER_PORT', http_port)1497- return self.request_context(create_environ(*args, **kwargs))1498-1510 def wsgi_app(self, environ, start_response):1511 """The actual WSGI application. This is not implemented in1512 `__call__` so that middlewares can be applied without losing a1513 reference to the class. So instead of doing this::38 unmodified linesmodified:flask/ctx.py+1 added-1 removed
89 unmodified lines90 self.session = None91 92 self.match_request()93 94- # Support for deprecated functionality. This is doing away with94+ # XXX: Support for deprecated functionality. This is doing away with95 # Flask 1.096 blueprint = self.request.blueprint97 if blueprint is not None:98 # better safe than sorry, we don't want to break code that48 unmodified linesmodified:flask/debughelpers.py+2 added-1 removed
52 unmodified lines53 'without one.')54 55 buf.append(' Make sure to directly send your %s-request to this URL '56 'since we can\'t make browsers or HTTP clients redirect '57- 'with form data.' % request.method)57+ 'with form data reliably or without user interaction.' %58+ request.method)59 buf.append('\n\nNote: this exception is only raised in debug mode')60 AssertionError.__init__(self, ''.join(buf).encode('utf-8'))61 62 17 unmodified linesmodified:flask/helpers.py+10 added
143 unmodified lines144 code::145 146 response = make_response(render_template('not_found.html'), 404)147 148+ The other use case of this function is to force the return value of a149+ view function into a response which is helpful with view150+ decorators::151+152+ response = make_response(view_function())153+ response.headers['X-Parachutes'] = 'parachutes are cool'154+155 Internally this function does the following things:156 157 - if no arguments are passed, it creates a new response argument158 - if one argument is passed, :meth:`flask.Flask.make_response`324 unmodified lines483 try:484 directory = os.path.dirname(sys.modules[import_name].__file__)485 return os.path.abspath(directory)486 except AttributeError:487+ # this is necessary in case we are running from the interactive488+ # python shell. It will never be used for production code however489 return os.getcwd()490 491 492 def find_package(import_name):7 unmodified lines500 __import__(import_name)501 root_mod = sys.modules[import_name.split('.')[0]]502 package_path = getattr(root_mod, '__file__', None)503 if package_path is None:504+ # support for the interactive python shell505 package_path = os.getcwd()506 else:507 package_path = os.path.abspath(os.path.dirname(package_path))508 if hasattr(root_mod, '__path__'):141 unmodified linesmodified:flask/sessions.py+31 added-3 removed
121 unmodified lines122 def get_cookie_domain(self, app):123 """Helpful helper method that returns the cookie domain that should124 be used for the session cookie if session cookies are used.125 """126+ if app.config['SESSION_COOKIE_DOMAIN'] is not None:127+ return app.config['SESSION_COOKIE_DOMAIN']128 if app.config['SERVER_NAME'] is not None:129 # chop of the port which is usually not supported by browsers130 return '.' + app.config['SERVER_NAME'].rsplit(':', 1)[0]131 132+ def get_cookie_path(self, app):133+ """Returns the path for which the cookie should be valid. The134+ default implementation uses the value from the SESSION_COOKIE_PATH``135+ config var if it's set, and falls back to ``APPLICATION_ROOT`` or136+ uses ``/`` if it's `None`.137+ """138+ return app.config['SESSION_COOKIE_PATH'] or \139+ app.config['APPLICATION_ROOT'] or '/'140+141+ def get_cookie_httponly(self, app):142+ """Returns True if the session cookie should be httponly. This143+ currently just returns the value of the ``SESSION_COOKIE_HTTPONLY``144+ config var.145+ """146+ return app.config['SESSION_COOKIE_HTTPONLY']147+148+ def get_cookie_secure(self, app):149+ """Returns True if the cookie should be secure. This currently150+ just returns the value of the ``SESSION_COOKIE_SECURE`` setting.151+ """152+ return app.config['SESSION_COOKIE_SECURE']153+154 def get_expiration_time(self, app, session):155 """A helper method that returns an expiration date for the session156 or `None` if the session is linked to the browser session. The157 default implementation returns now + the permanent session34 unmodified lines192 193 def save_session(self, app, session, response):194 expires = self.get_expiration_time(app, session)195 domain = self.get_cookie_domain(app)196+ path = self.get_cookie_path(app)197+ httponly = self.get_cookie_httponly(app)198+ secure = self.get_cookie_secure(app)199 if session.modified and not session:173- response.delete_cookie(app.session_cookie_name,200+ response.delete_cookie(app.session_cookie_name, path=path,201 domain=domain)202 else:176- session.save_cookie(response, app.session_cookie_name,177- expires=expires, httponly=True, domain=domain)203+ session.save_cookie(response, app.session_cookie_name, path=path,204+ expires=expires, httponly=httponly,205+ secure=secure, domain=domain)modified:flask/signals.py+1 added-1 removed
32 unmodified lines33 'because the blinker library is '34 'not installed.')35 send = lambda *a, **kw: None36 connect = disconnect = has_receivers_for = receivers_for = \37- temporarily_connected_to = _fail37+ temporarily_connected_to = connected_to = _fail38 del _fail39 40 # the namespace for code signals. If you are not flask code, do41 # not put signals in here. Create your own namespace instead.10 unmodified linesmodified:flask/testing.py+78 added-22 removed
8 unmodified lines9 :copyright: (c) 2010 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11 """12 13+from contextlib import contextmanager14 from werkzeug.test import Client, EnvironBuilder15 from flask import _request_ctx_stack16 17 18+def make_test_environ_builder(app, path='/', base_url=None, *args, **kwargs):19+ """Creates a new test builder with some application defaults thrown in."""20+ http_host = app.config.get('SERVER_NAME')21+ app_root = app.config.get('APPLICATION_ROOT')22+ if base_url is None:23+ base_url = 'http://%s/' % (http_host or 'localhost')24+ if app_root:25+ base_url += app_root.lstrip('/')26+ return EnvironBuilder(path, base_url, *args, **kwargs)27+28+29 class FlaskClient(Client):18- """Works like a regular Werkzeug test client but has some19- knowledge about how Flask works to defer the cleanup of the20- request context stack to the end of a with body when used21- in a with statement.30+ """Works like a regular Werkzeug test client but has some knowledge about31+ how Flask works to defer the cleanup of the request context stack to the32+ end of a with body when used in a with statement. For general information33+ about how to use this class refer to :class:`werkzeug.test.Client`.34+35+ Basic usage is outlined in the :ref:`testing` chapter.36 """37 38 preserve_context = context_preserved = False39 40+ @contextmanager41+ def session_transaction(self, *args, **kwargs):42+ """When used in combination with a with statement this opens a43+ session transaction. This can be used to modify the session that44+ the test client uses. Once the with block is left the session is45+ stored back.46+47+ with client.session_transaction() as session:48+ session['value'] = 4249+50+ Internally this is implemented by going through a temporary test51+ request context and since session handling could depend on52+ request variables this function accepts the same arguments as53+ :meth:`~flask.Flask.test_request_context` which are directly54+ passed through.55+ """56+ if self.cookie_jar is None:57+ raise RuntimeError('Session transactions only make sense '58+ 'with cookies enabled.')59+ app = self.application60+ environ_overrides = kwargs.pop('environ_overrides', {})61+ self.cookie_jar.inject_wsgi(environ_overrides)62+ outer_reqctx = _request_ctx_stack.top63+ with app.test_request_context(*args, **kwargs) as c:64+ sess = app.open_session(c.request)65+ if sess is None:66+ raise RuntimeError('Session backend did not open a session. '67+ 'Check the configuration')68+69+ # Since we have to open a new request context for the session70+ # handling we want to make sure that we hide out own context71+ # from the caller. By pushing the original request context72+ # (or None) on top of this and popping it we get exactly that73+ # behavior. It's important to not use the push and pop74+ # methods of the actual request context object since that would75+ # mean that cleanup handlers are called76+ _request_ctx_stack.push(outer_reqctx)77+ try:78+ yield sess79+ finally:80+ _request_ctx_stack.pop()81+82+ resp = app.response_class()83+ if not app.session_interface.is_null_session(sess):84+ app.save_session(sess, resp)85+ headers = resp.get_wsgi_headers(c.request.environ)86+ self.cookie_jar.extract_wsgi(c.request.environ, headers)87+88 def open(self, *args, **kwargs):27- if self.context_preserved:28- _request_ctx_stack.pop()29- self.context_preserved = False89+ self._pop_reqctx_if_necessary()90 kwargs.setdefault('environ_overrides', {}) \91 ['flask._preserve_context'] = self.preserve_context92 93 as_tuple = kwargs.pop('as_tuple', False)94 buffered = kwargs.pop('buffered', False)95 follow_redirects = kwargs.pop('follow_redirects', False)96+ builder = make_test_environ_builder(self.application, *args, **kwargs)97 37- builder = EnvironBuilder(*args, **kwargs)38-39- if self.application.config.get('SERVER_NAME'):40- server_name = self.application.config.get('SERVER_NAME')41- if ':' not in server_name:42- http_host, http_port = server_name, None43- else:44- http_host, http_port = server_name.split(':', 1)45- if builder.base_url == 'http://localhost/':46- # Default Generated Base URL47- if http_port != None:48- builder.host = http_host + ':' + http_port49- else:50- builder.host = http_host98 old = _request_ctx_stack.top99 try:100 return Client.open(self, builder,101 as_tuple=as_tuple,2 unmodified lines104 finally:105 self.context_preserved = _request_ctx_stack.top is not old106 107 def __enter__(self):108+ if self.preserve_context:109+ raise RuntimeError('Cannot nest client invocations')110 self.preserve_context = True111 return self112 113 def __exit__(self, exc_type, exc_value, tb):114 self.preserve_context = False115+ self._pop_reqctx_if_necessary()116+117+ def _pop_reqctx_if_necessary(self):118 if self.context_preserved:119+ # we have to use _request_ctx_stack.top.pop instead of120+ # _request_ctx_stack.pop since we want teardown handlers121+ # to be executed.67- _request_ctx_stack.pop()122+ _request_ctx_stack.top.pop()123+ self.context_preserved = Falsemodified:flask/views.py+35 added
28 unmodified lines29 def dispatch_request(self, name):30 return 'Hello %s!' % name31 32 app.add_url_rule('/hello/<name>', view_func=MyView.as_view('myview'))33+34+ When you want to decorate a pluggable view you will have to either do that35+ when the view function is created (by wrapping the return value of36+ :meth:`as_view`) or you can use the :attr:`decorators` attribute::37+38+ class SecretView(View):39+ methods = ['GET']40+ decorators = [superuser_required]41+42+ def dispatch_request(self):43+ ...44+45+ The decorators stored in the decorators list are applied one after another46+ when the view function is created. Note that you can *not* use the class47+ based decorators since those would decorate the view class and not the48+ generated view function!49 """50 51+ #: A for which methods this pluggable view can handle.52 methods = None53 54+ #: The canonical way to decorate class based views is to decorate the55+ #: return value of as_view(). However since this moves parts of the56+ #: logic from the class declaration to the place where it's hooked57+ #: into the routing system.58+ #:59+ #: You can place one or more decorators in this list and whenever the60+ #: view function is created the result is automatically decorated.61+ #:62+ #: .. versionadded:: 0.863+ decorators = []64+65 def dispatch_request(self):66 """Subclasses have to override this method to implement the67 actual view functionc ode. This method is called with all68 the arguments from the URL rule.12 unmodified lines81 """82 def view(*args, **kwargs):83 self = view.view_class(*class_args, **class_kwargs)84 return self.dispatch_request(*args, **kwargs)85+86+ if cls.decorators:87+ view.__name__ = name88+ view.__module__ = cls.__module__89+ for decorator in cls.decorators:90+ view = decorator(view)91+92 # we attach the view class to the view function for two reasons:93 # first of all it allows us to easily figure out what class based94 # view this thing came from, secondly it's also used for instanciating95 # the view class so you can actually replace it with something else52 unmodified linesadded:scripts/flaskext_test.py+311 added
1+# -*- coding: utf-8 -*-2+"""3+ Flask Extension Tests4+ ~~~~~~~~~~~~~~~~~~~~~5+6+ Tests the Flask extensions.7+8+ :copyright: (c) 2010 by Ali Afshar.9+ :license: BSD, see LICENSE for more details.10+"""11+12+from __future__ import with_statement13+14+import os15+import sys16+import shutil17+import urllib218+import tempfile19+import subprocess20+import argparse21+22+from flask import json23+24+from setuptools.package_index import PackageIndex25+from setuptools.archive_util import unpack_archive26+27+flask_svc_url = 'http://flask.pocoo.org/extensions/'28+29+30+# OS X has awful paths when using mkstemp or gettempdir(). I don't31+# care about security or clashes here, so pick something that is32+# actually rememberable.33+if sys.platform == 'darwin':34+ _tempdir = '/private/tmp'35+else:36+ _tempdir = tempfile.gettempdir()37+tdir = _tempdir + '/flaskext-test'38+flaskdir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))39+40+41+# virtualenv hack *cough*42+os.environ['PYTHONDONTWRITEBYTECODE'] = ''43+44+45+RESULT_TEMPATE = u'''\46+<!doctype html>47+<title>Flask-Extension Test Results</title>48+<style type=text/css>49+ body { font-family: 'Georgia', serif; font-size: 17px; color: #000; }50+ a { color: #004B6B; }51+ a:hover { color: #6D4100; }52+ h1, h2, h3 { font-family: 'Garamond', 'Georgia', serif; font-weight: normal; }53+ h1 { font-size: 30px; margin: 15px 0 5px 0; }54+ h2 { font-size: 24px; margin: 15px 0 5px 0; }55+ h3 { font-size: 19px; margin: 15px 0 5px 0; }56+ textarea, code,57+ pre { font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono',58+ 'Bitstream Vera Sans Mono', monospace!important; font-size: 15px;59+ background: #eee; }60+ pre { padding: 7px 15px; line-height: 1.3; }61+ p { line-height: 1.4; }62+ table { border: 1px solid black; border-collapse: collapse;63+ margin: 15px 0; }64+ td, th { border: 1px solid black; padding: 4px 10px;65+ text-align: left; }66+ th { background: #eee; font-weight: normal; }67+ tr.success { background: #D3F5CC; }68+ tr.failed { background: #F5D2CB; }69+</style>70+<h1>Flask-Extension Test Results</h1>71+<p>72+ This page contains the detailed test results for the test run of73+ all {{ 'approved' if approved }} Flask extensions.74+<h2>Summary</h2>75+<table class=results>76+ <thead>77+ <tr>78+ <th>Extension79+ <th>Version80+ <th>Author81+ <th>License82+ <th>Outcome83+ {%- for iptr, _ in results[0].logs|dictsort %}84+ <th>{{ iptr }}85+ {%- endfor %}86+ </tr>87+ </thead>88+ <tbody>89+ {%- for result in results %}90+ {% set outcome = 'success' if result.success else 'failed' %}91+ <tr class={{ outcome }}>92+ <th>{{ result.name }}93+ <td>{{ result.version }}94+ <td>{{ result.author }}95+ <td>{{ result.license }}96+ <td>{{ outcome }}97+ {%- for iptr, _ in result.logs|dictsort %}98+ <td><a href="#{{ result.name }}-{{ iptr }}">see log</a>99+ {%- endfor %}100+ </tr>101+ {%- endfor %}102+ </tbody>103+</table>104+<h2>Test Logs</h2>105+<p>Detailed test logs for all tests on all platforms:106+{%- for result in results %}107+ {%- for iptr, log in result.logs|dictsort %}108+ <h3 id="{{ result.name }}-{{ iptr }}">109+ {{ result.name }} - {{ result.version }} [{{ iptr }}]</h3>110+ <pre>{{ log }}</pre>111+ {%- endfor %}112+{%- endfor %}113+'''114+115+116+def log(msg, *args):117+ print '[EXTTEST]', msg % args118+119+120+class TestResult(object):121+122+ def __init__(self, name, folder, statuscode, interpreters):123+ intrptr = os.path.join(folder, '.tox/%s/bin/python'124+ % interpreters[0])125+ self.statuscode = statuscode126+ self.folder = folder127+ self.success = statuscode == 0128+129+ def fetch(field):130+ try:131+ c = subprocess.Popen([intrptr, 'setup.py',132+ '--' + field], cwd=folder,133+ stdout=subprocess.PIPE)134+ return c.communicate()[0].strip()135+ except OSError:136+ return '?'137+ self.name = name138+ self.license = fetch('license')139+ self.author = fetch('author')140+ self.version = fetch('version')141+142+ self.logs = {}143+ for interpreter in interpreters:144+ logfile = os.path.join(folder, '.tox/%s/log/test.log'145+ % interpreter)146+ if os.path.isfile(logfile):147+ self.logs[interpreter] = open(logfile).read()148+ else:149+ self.logs[interpreter] = ''150+151+152+def create_tdir():153+ try:154+ shutil.rmtree(tdir)155+ except Exception:156+ pass157+ os.mkdir(tdir)158+159+160+def package_flask():161+ distfolder = tdir + '/.flask-dist'162+ c = subprocess.Popen(['python', 'setup.py', 'sdist', '--formats=gztar',163+ '--dist', distfolder], cwd=flaskdir)164+ c.wait()165+ return os.path.join(distfolder, os.listdir(distfolder)[0])166+167+168+def get_test_command(checkout_dir):169+ if os.path.isfile(checkout_dir + '/Makefile'):170+ return 'make test'171+ return 'python setup.py test'172+173+174+def fetch_extensions_list():175+ req = urllib2.Request(flask_svc_url, headers={'accept':'application/json'})176+ d = urllib2.urlopen(req).read()177+ data = json.loads(d)178+ for ext in data['extensions']:179+ yield ext180+181+182+def checkout_extension(name):183+ log('Downloading extension %s to temporary folder', name)184+ root = os.path.join(tdir, name)185+ os.mkdir(root)186+ checkout_path = PackageIndex().download(name, root)187+188+ unpack_archive(checkout_path, root)189+ path = None190+ for fn in os.listdir(root):191+ path = os.path.join(root, fn)192+ if os.path.isdir(path):193+ break194+ log('Downloaded to %s', path)195+ return path196+197+198+tox_template = """[tox]199+envlist=%(env)s200+201+[testenv]202+deps=203+ %(deps)s204+ distribute205+ py206+commands=bash flaskext-runtest.sh {envlogdir}/test.log207+downloadcache=%(cache)s208+"""209+210+211+def create_tox_ini(checkout_path, interpreters, flask_dep):212+ tox_path = os.path.join(checkout_path, 'tox-flask-test.ini')213+ if not os.path.exists(tox_path):214+ with open(tox_path, 'w') as f:215+ f.write(tox_template % {216+ 'env': ','.join(interpreters),217+ 'cache': tdir,218+ 'deps': flask_dep219+ })220+ return tox_path221+222+223+def iter_extensions(only_approved=True):224+ for ext in fetch_extensions_list():225+ if ext['approved'] or not only_approved:226+ yield ext['name']227+228+229+def test_extension(name, interpreters, flask_dep):230+ checkout_path = checkout_extension(name)231+ log('Running tests with tox in %s', checkout_path)232+233+ # figure out the test command and write a wrapper script. We234+ # can't write that directly into the tox ini because tox does235+ # not invoke the command from the shell so we have no chance236+ # to pipe the output into a logfile. The /dev/null hack is237+ # to trick py.test (if used) into not guessing widths from the238+ # invoking terminal.239+ test_command = get_test_command(checkout_path)240+ log('Test command: %s', test_command)241+ f = open(checkout_path + '/flaskext-runtest.sh', 'w')242+ f.write(test_command + ' &> "$1" < /dev/null\n')243+ f.close()244+245+ # if there is a tox.ini, remove it, it will cause troubles246+ # for us. Remove it if present, we are running tox ourselves247+ # afterall.248+249+ create_tox_ini(checkout_path, interpreters, flask_dep)250+ rv = subprocess.call(['tox', '-c', 'tox-flask-test.ini'], cwd=checkout_path)251+ return TestResult(name, checkout_path, rv, interpreters)252+253+254+def run_tests(extensions, interpreters):255+ results = {}256+ create_tdir()257+ log('Packaging Flask')258+ flask_dep = package_flask()259+ log('Running extension tests')260+ log('Temporary Environment: %s', tdir)261+ for name in extensions:262+ log('Testing %s', name)263+ result = test_extension(name, interpreters, flask_dep)264+ if result.success:265+ log('Extension test succeeded')266+ else:267+ log('Extension test failed')268+ results[name] = result269+ return results270+271+272+def render_results(results, approved):273+ from jinja2 import Template274+ items = results.values()275+ items.sort(key=lambda x: x.name.lower())276+ rv = Template(RESULT_TEMPATE, autoescape=True).render(results=items,277+ approved=approved)278+ fd, filename = tempfile.mkstemp(suffix='.html')279+ os.fdopen(fd, 'w').write(rv.encode('utf-8') + '\n')280+ return filename281+282+283+def main():284+ parser = argparse.ArgumentParser(description='Runs Flask extension tests')285+ parser.add_argument('--all', dest='all', action='store_true',286+ help='run against all extensions, not just approved')287+ parser.add_argument('--browse', dest='browse', action='store_true',288+ help='show browser with the result summary')289+ parser.add_argument('--env', dest='env', default='py25,py26,py27',290+ help='the tox environments to run against')291+ parser.add_argument('--extension=', dest='extension', default=None,292+ help='tests a single extension')293+ args = parser.parse_args()294+295+ if args.extension is not None:296+ only_approved = False297+ extensions = [args.extension]298+ else:299+ only_approved = not args.all300+ extensions = iter_extensions(only_approved)301+302+ results = run_tests(extensions, [x.strip() for x in args.env.split(',')])303+ filename = render_results(results, only_approved)304+ if args.browse:305+ import webbrowser306+ webbrowser.open('file:///' + filename.lstrip('/'))307+ print 'Results written to', filename308+309+310+if __name__ == '__main__':311+ main()deleted:tests/blueprintapp/apps/admin/static/css/test.css-1 removed
1-/* nested file */deleted:tests/blueprintapp/apps/admin/static/test.txt-1 removed
1-Admin Filedeleted:tests/blueprintapp/apps/admin/templates/admin/index.html-1 removed
1-Hello from the Admindeleted:tests/blueprintapp/apps/admin/__init__.py-15 removed
1-from flask import Blueprint, render_template2-3-admin = Blueprint('admin', __name__, url_prefix='/admin',4- template_folder='templates',5- static_folder='static')6-7-8-@admin.route('/')9-def index():10- return render_template('admin/index.html')11-12-13-@admin.route('/index2')14-def index2():15- return render_template('./admin/index.html')deleted:tests/blueprintapp/apps/frontend/templates/frontend/index.html-1 removed
1-Hello from the Frontenddeleted:tests/blueprintapp/apps/frontend/__init__.py-8 removed
1-from flask import Blueprint, render_template2-3-frontend = Blueprint('frontend', __name__, template_folder='templates')4-5-6-@frontend.route('/')7-def index():8- return render_template('frontend/index.html')deleted:tests/blueprintapp/apps/__init__.py
deleted:tests/blueprintapp/__init__.py-7 removed
1-from flask import Flask2-3-app = Flask(__name__)4-from blueprintapp.apps.admin import admin5-from blueprintapp.apps.frontend import frontend6-app.register_blueprint(admin)7-app.register_blueprint(frontend)deleted:tests/moduleapp/apps/admin/static/css/test.css-1 removed
1-/* nested file */deleted:tests/moduleapp/apps/admin/static/test.txt-1 removed
1-Admin Filedeleted:tests/moduleapp/apps/admin/templates/index.html-1 removed
1-Hello from the Admindeleted:tests/moduleapp/apps/admin/__init__.py-14 removed
1-from flask import Module, render_template2-3-4-admin = Module(__name__, url_prefix='/admin')5-6-7-@admin.route('/')8-def index():9- return render_template('admin/index.html')10-11-12-@admin.route('/index2')13-def index2():14- return render_template('./admin/index.html')deleted:tests/moduleapp/apps/frontend/templates/index.html-1 removed
1-Hello from the Frontenddeleted:tests/moduleapp/apps/frontend/__init__.py-9 removed
1-from flask import Module, render_template2-3-4-frontend = Module(__name__)5-6-7-@frontend.route('/')8-def index():9- return render_template('frontend/index.html')deleted:tests/moduleapp/apps/__init__.py
deleted:tests/moduleapp/__init__.py-7 removed
1-from flask import Flask2-3-app = Flask(__name__)4-from moduleapp.apps.admin import admin5-from moduleapp.apps.frontend import frontend6-app.register_module(admin)7-app.register_module(frontend)deleted:tests/static/index.html-1 removed
1-<h1>Hello World!</h1>deleted:tests/subdomaintestmodule/static/hello.txt-1 removed
1-Hello Subdomaindeleted:tests/subdomaintestmodule/__init__.py-4 removed
1-from flask import Module2-3-4-mod = Module(__name__, 'foo', subdomain='foo')deleted:tests/templates/nested/nested.txt-1 removed
1-I'm nesteddeleted:tests/templates/_macro.html-1 removed
1-{% macro hello(name) %}Hello {{ name }}!{% endmacro %}deleted:tests/templates/context_template.html-1 removed
1-<p>{{ value }}|{{ injected_value }}deleted:tests/templates/escaping_template.html-6 removed
1-{{ text }}2-{{ html }}3-{% autoescape false %}{{ text }}4-{{ html }}{% endautoescape %}5-{% autoescape true %}{{ text }}6-{{ html }}{% endautoescape %}deleted:tests/templates/mail.txt-1 removed
1-{{ foo}} Maildeleted:tests/templates/simple_template.html-1 removed
1-<h1>{{ whiskey }}</h1>deleted:tests/templates/template_filter.html-1 removed
1-{{ value|super_reverse }}deleted:tests/flask_tests.py-2312 removed
1-# -*- coding: utf-8 -*-2-"""3- Flask Tests4- ~~~~~~~~~~~5-6- Tests Flask itself. The majority of Flask is already tested7- as part of Werkzeug.8-9- :copyright: (c) 2010 by Armin Ronacher.10- :license: BSD, see LICENSE for more details.11-"""12-from __future__ import with_statement13-import os14-import re15-import sys16-import flask17-import flask.views18-import unittest19-import warnings20-from threading import Thread21-from logging import StreamHandler22-from contextlib import contextmanager23-from functools import update_wrapper24-from datetime import datetime25-from werkzeug import parse_date, parse_options_header26-from werkzeug.exceptions import NotFound, BadRequest27-from werkzeug.http import parse_set_header28-from jinja2 import TemplateNotFound29-from cStringIO import StringIO30-31-example_path = os.path.join(os.path.dirname(__file__), '..', 'examples')32-sys.path.append(os.path.join(example_path, 'flaskr'))33-sys.path.append(os.path.join(example_path, 'minitwit'))34-35-36-def has_encoding(name):37- try:38- import codecs39- codecs.lookup(name)40- return True41- except LookupError:42- return False43-44-45-# config keys used for the ConfigTestCase46-TEST_KEY = 'foo'47-SECRET_KEY = 'devkey'48-49-50-# import moduleapp here because it uses deprecated features and we don't51-# want to see the warnings52-warnings.simplefilter('ignore', DeprecationWarning)53-from moduleapp import app as moduleapp54-warnings.simplefilter('default', DeprecationWarning)55-56-57-@contextmanager58-def catch_warnings():59- """Catch warnings in a with block in a list"""60- # make sure deprecation warnings are active in tests61- warnings.simplefilter('default', category=DeprecationWarning)62-63- filters = warnings.filters64- warnings.filters = filters[:]65- old_showwarning = warnings.showwarning66- log = []67- def showwarning(message, category, filename, lineno, file=None, line=None):68- log.append(locals())69- try:70- warnings.showwarning = showwarning71- yield log72- finally:73- warnings.filters = filters74- warnings.showwarning = old_showwarning75-76-77-@contextmanager78-def catch_stderr():79- """Catch stderr in a StringIO"""80- old_stderr = sys.stderr81- sys.stderr = rv = StringIO()82- try:83- yield rv84- finally:85- sys.stderr = old_stderr86-87-88-def emits_module_deprecation_warning(f):89- def new_f(*args, **kwargs):90- with catch_warnings() as log:91- f(*args, **kwargs)92- assert log, 'expected deprecation warning'93- for entry in log:94- assert 'Modules are deprecated' in str(entry['message'])95- return update_wrapper(new_f, f)96-97-98-class ContextTestCase(unittest.TestCase):99-100- def test_context_binding(self):101- app = flask.Flask(__name__)102- @app.route('/')103- def index():104- return 'Hello %s!' % flask.request.args['name']105- @app.route('/meh')106- def meh():107- return flask.request.url108-109- with app.test_request_context('/?name=World'):110- assert index() == 'Hello World!'111- with app.test_request_context('/meh'):112- assert meh() == 'http://localhost/meh'113- assert flask._request_ctx_stack.top is None114-115- def test_context_test(self):116- app = flask.Flask(__name__)117- assert not flask.request118- assert not flask.has_request_context()119- ctx = app.test_request_context()120- ctx.push()121- try:122- assert flask.request123- assert flask.has_request_context()124- finally:125- ctx.pop()126-127- def test_manual_context_binding(self):128- app = flask.Flask(__name__)129- @app.route('/')130- def index():131- return 'Hello %s!' % flask.request.args['name']132-133- ctx = app.test_request_context('/?name=World')134- ctx.push()135- assert index() == 'Hello World!'136- ctx.pop()137- try:138- index()139- except RuntimeError:140- pass141- else:142- assert 0, 'expected runtime error'143-144- def test_test_client_context_binding(self):145- app = flask.Flask(__name__)146- @app.route('/')147- def index():148- flask.g.value = 42149- return 'Hello World!'150-151- @app.route('/other')152- def other():153- 1/0154-155- with app.test_client() as c:156- resp = c.get('/')157- assert flask.g.value == 42158- assert resp.data == 'Hello World!'159- assert resp.status_code == 200160-161- resp = c.get('/other')162- assert not hasattr(flask.g, 'value')163- assert 'Internal Server Error' in resp.data164- assert resp.status_code == 500165- flask.g.value = 23166-167- try:168- flask.g.value169- except (AttributeError, RuntimeError):170- pass171- else:172- raise AssertionError('some kind of exception expected')173-174-175-class BasicFunctionalityTestCase(unittest.TestCase):176-177- def test_options_work(self):178- app = flask.Flask(__name__)179- @app.route('/', methods=['GET', 'POST'])180- def index():181- return 'Hello World'182- rv = app.test_client().open('/', method='OPTIONS')183- assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']184- assert rv.data == ''185-186- def test_options_on_multiple_rules(self):187- app = flask.Flask(__name__)188- @app.route('/', methods=['GET', 'POST'])189- def index():190- return 'Hello World'191- @app.route('/', methods=['PUT'])192- def index_put():193- return 'Aha!'194- rv = app.test_client().open('/', method='OPTIONS')195- assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']196-197- def test_options_handling_disabled(self):198- app = flask.Flask(__name__)199- def index():200- return 'Hello World!'201- index.provide_automatic_options = False202- app.route('/')(index)203- rv = app.test_client().open('/', method='OPTIONS')204- assert rv.status_code == 405205-206- app = flask.Flask(__name__)207- def index2():208- return 'Hello World!'209- index2.provide_automatic_options = True210- app.route('/', methods=['OPTIONS'])(index2)211- rv = app.test_client().open('/', method='OPTIONS')212- assert sorted(rv.allow) == ['OPTIONS']213-214- def test_request_dispatching(self):215- app = flask.Flask(__name__)216- @app.route('/')217- def index():218- return flask.request.method219- @app.route('/more', methods=['GET', 'POST'])220- def more():221- return flask.request.method222-223- c = app.test_client()224- assert c.get('/').data == 'GET'225- rv = c.post('/')226- assert rv.status_code == 405227- assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']228- rv = c.head('/')229- assert rv.status_code == 200230- assert not rv.data # head truncates231- assert c.post('/more').data == 'POST'232- assert c.get('/more').data == 'GET'233- rv = c.delete('/more')234- assert rv.status_code == 405235- assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']236-237- def test_url_mapping(self):238- app = flask.Flask(__name__)239- def index():240- return flask.request.method241- def more():242- return flask.request.method243-244- app.add_url_rule('/', 'index', index)245- app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])246-247- c = app.test_client()248- assert c.get('/').data == 'GET'249- rv = c.post('/')250- assert rv.status_code == 405251- assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']252- rv = c.head('/')253- assert rv.status_code == 200254- assert not rv.data # head truncates255- assert c.post('/more').data == 'POST'256- assert c.get('/more').data == 'GET'257- rv = c.delete('/more')258- assert rv.status_code == 405259- assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']260-261- def test_werkzeug_routing(self):262- from werkzeug.routing import Submount, Rule263- app = flask.Flask(__name__)264- app.url_map.add(Submount('/foo', [265- Rule('/bar', endpoint='bar'),266- Rule('/', endpoint='index')267- ]))268- def bar():269- return 'bar'270- def index():271- return 'index'272- app.view_functions['bar'] = bar273- app.view_functions['index'] = index274-275- c = app.test_client()276- assert c.get('/foo/').data == 'index'277- assert c.get('/foo/bar').data == 'bar'278-279- def test_endpoint_decorator(self):280- from werkzeug.routing import Submount, Rule281- app = flask.Flask(__name__)282- app.url_map.add(Submount('/foo', [283- Rule('/bar', endpoint='bar'),284- Rule('/', endpoint='index')285- ]))286-287- @app.endpoint('bar')288- def bar():289- return 'bar'290-291- @app.endpoint('index')292- def index():293- return 'index'294-295- c = app.test_client()296- assert c.get('/foo/').data == 'index'297- assert c.get('/foo/bar').data == 'bar'298-299- def test_session(self):300- app = flask.Flask(__name__)301- app.secret_key = 'testkey'302- @app.route('/set', methods=['POST'])303- def set():304- flask.session['value'] = flask.request.form['value']305- return 'value set'306- @app.route('/get')307- def get():308- return flask.session['value']309-310- c = app.test_client()311- assert c.post('/set', data={'value': '42'}).data == 'value set'312- assert c.get('/get').data == '42'313-314- def test_session_using_server_name(self):315- app = flask.Flask(__name__)316- app.config.update(317- SECRET_KEY='foo',318- SERVER_NAME='example.com'319- )320- @app.route('/')321- def index():322- flask.session['testing'] = 42323- return 'Hello World'324- rv = app.test_client().get('/', 'http://example.com/')325- assert 'domain=.example.com' in rv.headers['set-cookie'].lower()326- assert 'httponly' in rv.headers['set-cookie'].lower()327-328- def test_session_using_server_name_and_port(self):329- app = flask.Flask(__name__)330- app.config.update(331- SECRET_KEY='foo',332- SERVER_NAME='example.com:8080'333- )334- @app.route('/')335- def index():336- flask.session['testing'] = 42337- return 'Hello World'338- rv = app.test_client().get('/', 'http://example.com:8080/')339- assert 'domain=.example.com' in rv.headers['set-cookie'].lower()340- assert 'httponly' in rv.headers['set-cookie'].lower()341-342- def test_missing_session(self):343- app = flask.Flask(__name__)344- def expect_exception(f, *args, **kwargs):345- try:346- f(*args, **kwargs)347- except RuntimeError, e:348- assert e.args and 'session is unavailable' in e.args[0]349- else:350- assert False, 'expected exception'351- with app.test_request_context():352- assert flask.session.get('missing_key') is None353- expect_exception(flask.session.__setitem__, 'foo', 42)354- expect_exception(flask.session.pop, 'foo')355-356- def test_session_expiration(self):357- permanent = True358- app = flask.Flask(__name__)359- app.secret_key = 'testkey'360- @app.route('/')361- def index():362- flask.session['test'] = 42363- flask.session.permanent = permanent364- return ''365-366- @app.route('/test')367- def test():368- return unicode(flask.session.permanent)369-370- client = app.test_client()371- rv = client.get('/')372- assert 'set-cookie' in rv.headers373- match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])374- expires = parse_date(match.group())375- expected = datetime.utcnow() + app.permanent_session_lifetime376- assert expires.year == expected.year377- assert expires.month == expected.month378- assert expires.day == expected.day379-380- rv = client.get('/test')381- assert rv.data == 'True'382-383- permanent = False384- rv = app.test_client().get('/')385- assert 'set-cookie' in rv.headers386- match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])387- assert match is None388-389- def test_flashes(self):390- app = flask.Flask(__name__)391- app.secret_key = 'testkey'392-393- with app.test_request_context():394- assert not flask.session.modified395- flask.flash('Zap')396- flask.session.modified = False397- flask.flash('Zip')398- assert flask.session.modified399- assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']400-401- def test_extended_flashing(self):402- app = flask.Flask(__name__)403- app.secret_key = 'testkey'404-405- @app.route('/')406- def index():407- flask.flash(u'Hello World')408- flask.flash(u'Hello World', 'error')409- flask.flash(flask.Markup(u'<em>Testing</em>'), 'warning')410- return ''411-412- @app.route('/test')413- def test():414- messages = flask.get_flashed_messages(with_categories=True)415- assert len(messages) == 3416- assert messages[0] == ('message', u'Hello World')417- assert messages[1] == ('error', u'Hello World')418- assert messages[2] == ('warning', flask.Markup(u'<em>Testing</em>'))419- return ''420- messages = flask.get_flashed_messages()421- assert len(messages) == 3422- assert messages[0] == u'Hello World'423- assert messages[1] == u'Hello World'424- assert messages[2] == flask.Markup(u'<em>Testing</em>')425-426- c = app.test_client()427- c.get('/')428- c.get('/test')429-430- def test_request_processing(self):431- app = flask.Flask(__name__)432- evts = []433- @app.before_request434- def before_request():435- evts.append('before')436- @app.after_request437- def after_request(response):438- response.data += '|after'439- evts.append('after')440- return response441- @app.route('/')442- def index():443- assert 'before' in evts444- assert 'after' not in evts445- return 'request'446- assert 'after' not in evts447- rv = app.test_client().get('/').data448- assert 'after' in evts449- assert rv == 'request|after'450-451- def test_teardown_request_handler(self):452- called = []453- app = flask.Flask(__name__)454- @app.teardown_request455- def teardown_request(exc):456- called.append(True)457- return "Ignored"458- @app.route('/')459- def root():460- return "Response"461- rv = app.test_client().get('/')462- assert rv.status_code == 200463- assert 'Response' in rv.data464- assert len(called) == 1465-466- def test_teardown_request_handler_debug_mode(self):467- called = []468- app = flask.Flask(__name__)469- app.testing = True470- @app.teardown_request471- def teardown_request(exc):472- called.append(True)473- return "Ignored"474- @app.route('/')475- def root():476- return "Response"477- rv = app.test_client().get('/')478- assert rv.status_code == 200479- assert 'Response' in rv.data480- assert len(called) == 1481-482- def test_teardown_request_handler_error(self):483- called = []484- app = flask.Flask(__name__)485- @app.teardown_request486- def teardown_request1(exc):487- assert type(exc) == ZeroDivisionError488- called.append(True)489- # This raises a new error and blows away sys.exc_info(), so we can490- # test that all teardown_requests get passed the same original491- # exception.492- try:493- raise TypeError494- except:495- pass496- @app.teardown_request497- def teardown_request2(exc):498- assert type(exc) == ZeroDivisionError499- called.append(True)500- # This raises a new error and blows away sys.exc_info(), so we can501- # test that all teardown_requests get passed the same original502- # exception.503- try:504- raise TypeError505- except:506- pass507- @app.route('/')508- def fails():509- 1/0510- rv = app.test_client().get('/')511- assert rv.status_code == 500512- assert 'Internal Server Error' in rv.data513- assert len(called) == 2514-515- def test_before_after_request_order(self):516- called = []517- app = flask.Flask(__name__)518- @app.before_request519- def before1():520- called.append(1)521- @app.before_request522- def before2():523- called.append(2)524- @app.after_request525- def after1(response):526- called.append(4)527- return response528- @app.after_request529- def after2(response):530- called.append(3)531- return response532- @app.teardown_request533- def finish1(exc):534- called.append(6)535- @app.teardown_request536- def finish2(exc):537- called.append(5)538- @app.route('/')539- def index():540- return '42'541- rv = app.test_client().get('/')542- assert rv.data == '42'543- assert called == [1, 2, 3, 4, 5, 6]544-545- def test_error_handling(self):546- app = flask.Flask(__name__)547- @app.errorhandler(404)548- def not_found(e):549- return 'not found', 404550- @app.errorhandler(500)551- def internal_server_error(e):552- return 'internal server error', 500553- @app.route('/')554- def index():555- flask.abort(404)556- @app.route('/error')557- def error():558- 1 // 0559- c = app.test_client()560- rv = c.get('/')561- assert rv.status_code == 404562- assert rv.data == 'not found'563- rv = c.get('/error')564- assert rv.status_code == 500565- assert 'internal server error' == rv.data566-567- def test_before_request_and_routing_errors(self):568- app = flask.Flask(__name__)569- @app.before_request570- def attach_something():571- flask.g.something = 'value'572- @app.errorhandler(404)573- def return_something(error):574- return flask.g.something, 404575- rv = app.test_client().get('/')576- assert rv.status_code == 404577- assert rv.data == 'value'578-579- def test_user_error_handling(self):580- class MyException(Exception):581- pass582-583- app = flask.Flask(__name__)584- @app.errorhandler(MyException)585- def handle_my_exception(e):586- assert isinstance(e, MyException)587- return '42'588- @app.route('/')589- def index():590- raise MyException()591-592- c = app.test_client()593- assert c.get('/').data == '42'594-595- def test_trapping_of_bad_request_key_errors(self):596- app = flask.Flask(__name__)597- app.testing = True598- @app.route('/fail')599- def fail():600- flask.request.form['missing_key']601- c = app.test_client()602- assert c.get('/fail').status_code == 400603-604- app.config['TRAP_BAD_REQUEST_ERRORS'] = True605- c = app.test_client()606- try:607- c.get('/fail')608- except KeyError, e:609- assert isinstance(e, BadRequest)610- else:611- self.fail('Expected exception')612-613- def test_trapping_of_all_http_exceptions(self):614- app = flask.Flask(__name__)615- app.testing = True616- app.config['TRAP_HTTP_EXCEPTIONS'] = True617- @app.route('/fail')618- def fail():619- flask.abort(404)620-621- c = app.test_client()622- try:623- c.get('/fail')624- except NotFound, e:625- pass626- else:627- self.fail('Expected exception')628-629- def test_enctype_debug_helper(self):630- from flask.debughelpers import DebugFilesKeyError631- app = flask.Flask(__name__)632- app.debug = True633- @app.route('/fail', methods=['POST'])634- def index():635- return flask.request.files['foo'].filename636-637- # with statement is important because we leave an exception on the638- # stack otherwise and we want to ensure that this is not the case639- # to not negatively affect other tests.640- with app.test_client() as c:641- try:642- c.post('/fail', data={'foo': 'index.txt'})643- except DebugFilesKeyError, e:644- assert 'no file contents were transmitted' in str(e)645- assert 'This was submitted: "index.txt"' in str(e)646- else:647- self.fail('Expected exception')648-649- def test_teardown_on_pop(self):650- buffer = []651- app = flask.Flask(__name__)652- @app.teardown_request653- def end_of_request(exception):654- buffer.append(exception)655-656- ctx = app.test_request_context()657- ctx.push()658- assert buffer == []659- ctx.pop()660- assert buffer == [None]661-662- def test_response_creation(self):663- app = flask.Flask(__name__)664- @app.route('/unicode')665- def from_unicode():666- return u'Hällo Wörld'667- @app.route('/string')668- def from_string():669- return u'Hällo Wörld'.encode('utf-8')670- @app.route('/args')671- def from_tuple():672- return 'Meh', 400, {'X-Foo': 'Testing'}, 'text/plain'673- c = app.test_client()674- assert c.get('/unicode').data == u'Hällo Wörld'.encode('utf-8')675- assert c.get('/string').data == u'Hällo Wörld'.encode('utf-8')676- rv = c.get('/args')677- assert rv.data == 'Meh'678- assert rv.headers['X-Foo'] == 'Testing'679- assert rv.status_code == 400680- assert rv.mimetype == 'text/plain'681-682- def test_make_response(self):683- app = flask.Flask(__name__)684- with app.test_request_context():685- rv = flask.make_response()686- assert rv.status_code == 200687- assert rv.data == ''688- assert rv.mimetype == 'text/html'689-690- rv = flask.make_response('Awesome')691- assert rv.status_code == 200692- assert rv.data == 'Awesome'693- assert rv.mimetype == 'text/html'694-695- rv = flask.make_response('W00t', 404)696- assert rv.status_code == 404697- assert rv.data == 'W00t'698- assert rv.mimetype == 'text/html'699-700- def test_url_generation(self):701- app = flask.Flask(__name__)702- @app.route('/hello/<name>', methods=['POST'])703- def hello():704- pass705- with app.test_request_context():706- assert flask.url_for('hello', name='test x') == '/hello/test%20x'707- assert flask.url_for('hello', name='test x', _external=True) \708- == 'http://localhost/hello/test%20x'709-710- def test_custom_converters(self):711- from werkzeug.routing import BaseConverter712- class ListConverter(BaseConverter):713- def to_python(self, value):714- return value.split(',')715- def to_url(self, value):716- base_to_url = super(ListConverter, self).to_url717- return ','.join(base_to_url(x) for x in value)718- app = flask.Flask(__name__)719- app.url_map.converters['list'] = ListConverter720- @app.route('/<list:args>')721- def index(args):722- return '|'.join(args)723- c = app.test_client()724- assert c.get('/1,2,3').data == '1|2|3'725-726- def test_static_files(self):727- app = flask.Flask(__name__)728- rv = app.test_client().get('/static/index.html')729- assert rv.status_code == 200730- assert rv.data.strip() == '<h1>Hello World!</h1>'731- with app.test_request_context():732- assert flask.url_for('static', filename='index.html') \733- == '/static/index.html'734-735- def test_none_response(self):736- app = flask.Flask(__name__)737- @app.route('/')738- def test():739- return None740- try:741- app.test_client().get('/')742- except ValueError, e:743- assert str(e) == 'View function did not return a response'744- pass745- else:746- assert "Expected ValueError"747-748- def test_request_locals(self):749- self.assertEqual(repr(flask.g), '<LocalProxy unbound>')750- self.assertFalse(flask.g)751-752- def test_proper_test_request_context(self):753- app = flask.Flask(__name__)754- app.config.update(755- SERVER_NAME='localhost.localdomain:5000'756- )757-758- @app.route('/')759- def index():760- return None761-762- @app.route('/', subdomain='foo')763- def sub():764- return None765-766- with app.test_request_context('/'):767- assert flask.url_for('index', _external=True) == 'http://localhost.localdomain:5000/'768-769- with app.test_request_context('/'):770- assert flask.url_for('sub', _external=True) == 'http://foo.localhost.localdomain:5000/'771-772- try:773- with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}):774- pass775- except Exception, e:776- assert isinstance(e, ValueError)777- assert str(e) == "the server name provided " + \778- "('localhost.localdomain:5000') does not match the " + \779- "server name from the WSGI environment ('localhost')", str(e)780-781- try:782- app.config.update(SERVER_NAME='localhost')783- with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}):784- pass785- except ValueError, e:786- raise ValueError(787- "No ValueError exception should have been raised \"%s\"" % e788- )789-790- try:791- app.config.update(SERVER_NAME='localhost:80')792- with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}):793- pass794- except ValueError, e:795- raise ValueError(796- "No ValueError exception should have been raised \"%s\"" % e797- )798-799- def test_test_app_proper_environ(self):800- app = flask.Flask(__name__)801- app.config.update(802- SERVER_NAME='localhost.localdomain:5000'803- )804- @app.route('/')805- def index():806- return 'Foo'807-808- @app.route('/', subdomain='foo')809- def subdomain():810- return 'Foo SubDomain'811-812- try:813- rv = app.test_client().get('/')814- assert rv.data == 'Foo'815- except ValueError, e:816- raise ValueError(817- "No ValueError exception should have been raised \"%s\"" % e818- )819-820- try:821- rv = app.test_client().get('/', 'http://localhost.localdomain:5000')822- assert rv.data == 'Foo'823- except ValueError, e:824- raise ValueError(825- "No ValueError exception should have been raised \"%s\"" % e826- )827-828- try:829- rv = app.test_client().get('/', 'https://localhost.localdomain:5000')830- assert rv.data == 'Foo'831- except ValueError, e:832- raise ValueError(833- "No ValueError exception should have been raised \"%s\"" % e834- )835-836- try:837- app.config.update(SERVER_NAME='localhost.localdomain')838- rv = app.test_client().get('/', 'https://localhost.localdomain')839- assert rv.data == 'Foo'840- except ValueError, e:841- raise ValueError(842- "No ValueError exception should have been raised \"%s\"" % e843- )844-845- try:846- app.config.update(SERVER_NAME='localhost.localdomain:443')847- rv = app.test_client().get('/', 'https://localhost.localdomain')848- assert rv.data == 'Foo'849- except ValueError, e:850- assert str(e) == "the server name provided " + \851- "('localhost.localdomain:443') does not match the " + \852- "server name from the WSGI environment ('localhost.localdomain')", str(e)853-854- try:855- app.config.update(SERVER_NAME='localhost.localdomain')856- app.test_client().get('/', 'http://foo.localhost')857- except ValueError, e:858- assert str(e) == "the server name provided " + \859- "('localhost.localdomain') does not match the " + \860- "server name from the WSGI environment ('foo.localhost')", str(e)861-862- try:863- rv = app.test_client().get('/', 'http://foo.localhost.localdomain')864- assert rv.data == 'Foo SubDomain'865- except ValueError, e:866- raise ValueError(867- "No ValueError exception should have been raised \"%s\"" % e868- )869-870- def test_exception_propagation(self):871- def apprunner(configkey):872- app = flask.Flask(__name__)873- @app.route('/')874- def index():875- 1/0876- c = app.test_client()877- if config_key is not None:878- app.config[config_key] = True879- try:880- resp = c.get('/')881- except Exception:882- pass883- else:884- self.fail('expected exception')885- else:886- assert c.get('/').status_code == 500887-888- # we have to run this test in an isolated thread because if the889- # debug flag is set to true and an exception happens the context is890- # not torn down. This causes other tests that run after this fail891- # when they expect no exception on the stack.892- for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None:893- t = Thread(target=apprunner, args=(config_key,))894- t.start()895- t.join()896-897- def test_max_content_length(self):898- app = flask.Flask(__name__)899- app.config['MAX_CONTENT_LENGTH'] = 64900- @app.before_request901- def always_first():902- flask.request.form['myfile']903- assert False904- @app.route('/accept', methods=['POST'])905- def accept_file():906- flask.request.form['myfile']907- assert False908- @app.errorhandler(413)909- def catcher(error):910- return '42'911-912- c = app.test_client()913- rv = c.post('/accept', data={'myfile': 'foo' * 100})914- assert rv.data == '42'915-916- def test_url_processors(self):917- app = flask.Flask(__name__)918-919- @app.url_defaults920- def add_language_code(endpoint, values):921- if flask.g.lang_code is not None and \922- app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):923- values.setdefault('lang_code', flask.g.lang_code)924-925- @app.url_value_preprocessor926- def pull_lang_code(endpoint, values):927- flask.g.lang_code = values.pop('lang_code', None)928-929- @app.route('/<lang_code>/')930- def index():931- return flask.url_for('about')932-933- @app.route('/<lang_code>/about')934- def about():935- return flask.url_for('something_else')936-937- @app.route('/foo')938- def something_else():939- return flask.url_for('about', lang_code='en')940-941- c = app.test_client()942-943- self.assertEqual(c.get('/de/').data, '/de/about')944- self.assertEqual(c.get('/de/about').data, '/foo')945- self.assertEqual(c.get('/foo').data, '/en/about')946-947- def test_debug_mode_complains_after_first_request(self):948- app = flask.Flask(__name__)949- app.debug = True950- @app.route('/')951- def index():952- return 'Awesome'953- self.assert_(not app.got_first_request)954- self.assertEqual(app.test_client().get('/').data, 'Awesome')955- try:956- @app.route('/foo')957- def broken():958- return 'Meh'959- except AssertionError, e:960- self.assert_('A setup function was called' in str(e))961- else:962- self.fail('Expected exception')963-964- app.debug = False965- @app.route('/foo')966- def working():967- return 'Meh'968- self.assertEqual(app.test_client().get('/foo').data, 'Meh')969- self.assert_(app.got_first_request)970-971- def test_before_first_request_functions(self):972- got = []973- app = flask.Flask(__name__)974- @app.before_first_request975- def foo():976- got.append(42)977- c = app.test_client()978- c.get('/')979- self.assertEqual(got, [42])980- c.get('/')981- self.assertEqual(got, [42])982- self.assert_(app.got_first_request)983-984- def test_routing_redirect_debugging(self):985- app = flask.Flask(__name__)986- app.debug = True987- @app.route('/foo/', methods=['GET', 'POST'])988- def foo():989- return 'success'990- with app.test_client() as c:991- try:992- c.post('/foo', data={})993- except AssertionError, e:994- self.assert_('http://localhost/foo/' in str(e))995- self.assert_('Make sure to directly send your POST-request '996- 'to this URL' in str(e))997- else:998- self.fail('Expected exception')999-1000- rv = c.get('/foo', data={}, follow_redirects=True)1001- self.assertEqual(rv.data, 'success')1002-1003- app.debug = False1004- with app.test_client() as c:1005- rv = c.post('/foo', data={}, follow_redirects=True)1006- self.assertEqual(rv.data, 'success')1007-1008- def test_route_decorator_custom_endpoint(self):1009- app = flask.Flask(__name__)1010- app.debug = True1011-1012- @app.route('/foo/')1013- def foo():1014- return flask.request.endpoint1015-1016- @app.route('/bar/', endpoint='bar')1017- def for_bar():1018- return flask.request.endpoint1019-1020- @app.route('/bar/123', endpoint='123')1021- def for_bar_foo():1022- return flask.request.endpoint1023-1024- with app.test_request_context():1025- assert flask.url_for('foo') == '/foo/'1026- assert flask.url_for('bar') == '/bar/'1027- assert flask.url_for('123') == '/bar/123'1028-1029- c = app.test_client()1030- self.assertEqual(c.get('/foo/').data, 'foo')1031- self.assertEqual(c.get('/bar/').data, 'bar')1032- self.assertEqual(c.get('/bar/123').data, '123')1033-1034-1035-class InstanceTestCase(unittest.TestCase):1036-1037- def test_explicit_instance_paths(self):1038- here = os.path.abspath(os.path.dirname(__file__))1039- try:1040- flask.Flask(__name__, instance_path='instance')1041- except ValueError, e:1042- self.assert_('must be absolute' in str(e))1043- else:1044- self.fail('Expected value error')1045-1046- app = flask.Flask(__name__, instance_path=here)1047- self.assertEqual(app.instance_path, here)1048-1049- def test_uninstalled_module_paths(self):1050- here = os.path.abspath(os.path.dirname(__file__))1051- app = flask.Flask(__name__)1052- self.assertEqual(app.instance_path, os.path.join(here, 'instance'))1053-1054- def test_uninstalled_package_paths(self):1055- from blueprintapp import app1056- here = os.path.abspath(os.path.dirname(__file__))1057- self.assertEqual(app.instance_path, os.path.join(here, 'instance'))1058-1059- def test_installed_module_paths(self):1060- import types1061- expected_prefix = os.path.abspath('foo')1062- mod = types.ModuleType('myapp')1063- mod.__file__ = os.path.join(expected_prefix, 'lib', 'python2.5',1064- 'site-packages', 'myapp.py')1065- sys.modules['myapp'] = mod1066- try:1067- mod.app = flask.Flask(mod.__name__)1068- self.assertEqual(mod.app.instance_path,1069- os.path.join(expected_prefix, 'var',1070- 'myapp-instance'))1071- finally:1072- sys.modules['myapp'] = None1073-1074- def test_installed_package_paths(self):1075- import types1076- expected_prefix = os.path.abspath('foo')1077- package_path = os.path.join(expected_prefix, 'lib', 'python2.5',1078- 'site-packages', 'myapp')1079- mod = types.ModuleType('myapp')1080- mod.__path__ = [package_path]1081- mod.__file__ = os.path.join(package_path, '__init__.py')1082- sys.modules['myapp'] = mod1083- try:1084- mod.app = flask.Flask(mod.__name__)1085- self.assertEqual(mod.app.instance_path,1086- os.path.join(expected_prefix, 'var',1087- 'myapp-instance'))1088- finally:1089- sys.modules['myapp'] = None1090-1091- def test_prefix_installed_paths(self):1092- import types1093- expected_prefix = os.path.abspath(sys.prefix)1094- package_path = os.path.join(expected_prefix, 'lib', 'python2.5',1095- 'site-packages', 'myapp')1096- mod = types.ModuleType('myapp')1097- mod.__path__ = [package_path]1098- mod.__file__ = os.path.join(package_path, '__init__.py')1099- sys.modules['myapp'] = mod1100- try:1101- mod.app = flask.Flask(mod.__name__)1102- self.assertEqual(mod.app.instance_path,1103- os.path.join(expected_prefix, 'var',1104- 'myapp-instance'))1105- finally:1106- sys.modules['myapp'] = None1107-1108- def test_egg_installed_paths(self):1109- import types1110- expected_prefix = os.path.abspath(sys.prefix)1111- package_path = os.path.join(expected_prefix, 'lib', 'python2.5',1112- 'site-packages', 'MyApp.egg', 'myapp')1113- mod = types.ModuleType('myapp')1114- mod.__path__ = [package_path]1115- mod.__file__ = os.path.join(package_path, '__init__.py')1116- sys.modules['myapp'] = mod1117- try:1118- mod.app = flask.Flask(mod.__name__)1119- self.assertEqual(mod.app.instance_path,1120- os.path.join(expected_prefix, 'var',1121- 'myapp-instance'))1122- finally:1123- sys.modules['myapp'] = None1124-1125-1126-class JSONTestCase(unittest.TestCase):1127-1128- def test_json_bad_requests(self):1129- app = flask.Flask(__name__)1130- @app.route('/json', methods=['POST'])1131- def return_json():1132- return unicode(flask.request.json)1133- c = app.test_client()1134- rv = c.post('/json', data='malformed', content_type='application/json')1135- self.assertEqual(rv.status_code, 400)1136-1137- def test_json_body_encoding(self):1138- app = flask.Flask(__name__)1139- app.testing = True1140- @app.route('/')1141- def index():1142- return flask.request.json1143-1144- c = app.test_client()1145- resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),1146- content_type='application/json; charset=iso-8859-15')1147- assert resp.data == u'Hällo Wörld'.encode('utf-8')1148-1149- def test_jsonify(self):1150- d = dict(a=23, b=42, c=[1, 2, 3])1151- app = flask.Flask(__name__)1152- @app.route('/kw')1153- def return_kwargs():1154- return flask.jsonify(**d)1155- @app.route('/dict')1156- def return_dict():1157- return flask.jsonify(d)1158- c = app.test_client()1159- for url in '/kw', '/dict':1160- rv = c.get(url)1161- assert rv.mimetype == 'application/json'1162- assert flask.json.loads(rv.data) == d1163-1164- def test_json_attr(self):1165- app = flask.Flask(__name__)1166- @app.route('/add', methods=['POST'])1167- def add():1168- return unicode(flask.request.json['a'] + flask.request.json['b'])1169- c = app.test_client()1170- rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),1171- content_type='application/json')1172- assert rv.data == '3'1173-1174- def test_template_escaping(self):1175- app = flask.Flask(__name__)1176- render = flask.render_template_string1177- with app.test_request_context():1178- rv = render('{{ "</script>"|tojson|safe }}')1179- assert rv == '"<\\/script>"'1180- rv = render('{{ "<\0/script>"|tojson|safe }}')1181- assert rv == '"<\\u0000\\/script>"'1182-1183- def test_modified_url_encoding(self):1184- class ModifiedRequest(flask.Request):1185- url_charset = 'euc-kr'1186- app = flask.Flask(__name__)1187- app.request_class = ModifiedRequest1188- app.url_map.charset = 'euc-kr'1189-1190- @app.route('/')1191- def index():1192- return flask.request.args['foo']1193-1194- rv = app.test_client().get(u'/?foo=정상처리'.encode('euc-kr'))1195- assert rv.status_code == 2001196- assert rv.data == u'정상처리'.encode('utf-8')1197-1198- if not has_encoding('euc-kr'):1199- test_modified_url_encoding = None1200-1201-1202-class TemplatingTestCase(unittest.TestCase):1203-1204- def test_context_processing(self):1205- app = flask.Flask(__name__)1206- @app.context_processor1207- def context_processor():1208- return {'injected_value': 42}1209- @app.route('/')1210- def index():1211- return flask.render_template('context_template.html', value=23)1212- rv = app.test_client().get('/')1213- assert rv.data == '<p>23|42'1214-1215- def test_original_win(self):1216- app = flask.Flask(__name__)1217- @app.route('/')1218- def index():1219- return flask.render_template_string('{{ config }}', config=42)1220- rv = app.test_client().get('/')1221- assert rv.data == '42'1222-1223- def test_standard_context(self):1224- app = flask.Flask(__name__)1225- app.secret_key = 'development key'1226- @app.route('/')1227- def index():1228- flask.g.foo = 231229- flask.session['test'] = 'aha'1230- return flask.render_template_string('''1231- {{ request.args.foo }}1232- {{ g.foo }}1233- {{ config.DEBUG }}1234- {{ session.test }}1235- ''')1236- rv = app.test_client().get('/?foo=42')1237- assert rv.data.split() == ['42', '23', 'False', 'aha']1238-1239- def test_escaping(self):1240- text = '<p>Hello World!'1241- app = flask.Flask(__name__)1242- @app.route('/')1243- def index():1244- return flask.render_template('escaping_template.html', text=text,1245- html=flask.Markup(text))1246- lines = app.test_client().get('/').data.splitlines()1247- assert lines == [1248- '<p>Hello World!',1249- '<p>Hello World!',1250- '<p>Hello World!',1251- '<p>Hello World!',1252- '<p>Hello World!',1253- '<p>Hello World!'1254- ]1255-1256- def test_no_escaping(self):1257- app = flask.Flask(__name__)1258- with app.test_request_context():1259- assert flask.render_template_string('{{ foo }}',1260- foo='<test>') == '<test>'1261- assert flask.render_template('mail.txt', foo='<test>') \1262- == '<test> Mail'1263-1264- def test_macros(self):1265- app = flask.Flask(__name__)1266- with app.test_request_context():1267- macro = flask.get_template_attribute('_macro.html', 'hello')1268- assert macro('World') == 'Hello World!'1269-1270- def test_template_filter(self):1271- app = flask.Flask(__name__)1272- @app.template_filter()1273- def my_reverse(s):1274- return s[::-1]1275- assert 'my_reverse' in app.jinja_env.filters.keys()1276- assert app.jinja_env.filters['my_reverse'] == my_reverse1277- assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'1278-1279- def test_template_filter_with_name(self):1280- app = flask.Flask(__name__)1281- @app.template_filter('strrev')1282- def my_reverse(s):1283- return s[::-1]1284- assert 'strrev' in app.jinja_env.filters.keys()1285- assert app.jinja_env.filters['strrev'] == my_reverse1286- assert app.jinja_env.filters['strrev']('abcd') == 'dcba'1287-1288- def test_template_filter_with_template(self):1289- app = flask.Flask(__name__)1290- @app.template_filter()1291- def super_reverse(s):1292- return s[::-1]1293- @app.route('/')1294- def index():1295- return flask.render_template('template_filter.html', value='abcd')1296- rv = app.test_client().get('/')1297- assert rv.data == 'dcba'1298-1299- def test_template_filter_with_name_and_template(self):1300- app = flask.Flask(__name__)1301- @app.template_filter('super_reverse')1302- def my_reverse(s):1303- return s[::-1]1304- @app.route('/')1305- def index():1306- return flask.render_template('template_filter.html', value='abcd')1307- rv = app.test_client().get('/')1308- assert rv.data == 'dcba'1309-1310- def test_custom_template_loader(self):1311- class MyFlask(flask.Flask):1312- def create_global_jinja_loader(self):1313- from jinja2 import DictLoader1314- return DictLoader({'index.html': 'Hello Custom World!'})1315- app = MyFlask(__name__)1316- @app.route('/')1317- def index():1318- return flask.render_template('index.html')1319- c = app.test_client()1320- rv = c.get('/')1321- assert rv.data == 'Hello Custom World!'1322-1323-1324-class ModuleTestCase(unittest.TestCase):1325-1326- @emits_module_deprecation_warning1327- def test_basic_module(self):1328- app = flask.Flask(__name__)1329- admin = flask.Module(__name__, 'admin', url_prefix='/admin')1330- @admin.route('/')1331- def admin_index():1332- return 'admin index'1333- @admin.route('/login')1334- def admin_login():1335- return 'admin login'1336- @admin.route('/logout')1337- def admin_logout():1338- return 'admin logout'1339- @app.route('/')1340- def index():1341- return 'the index'1342- app.register_module(admin)1343- c = app.test_client()1344- assert c.get('/').data == 'the index'1345- assert c.get('/admin/').data == 'admin index'1346- assert c.get('/admin/login').data == 'admin login'1347- assert c.get('/admin/logout').data == 'admin logout'1348-1349- @emits_module_deprecation_warning1350- def test_default_endpoint_name(self):1351- app = flask.Flask(__name__)1352- mod = flask.Module(__name__, 'frontend')1353- def index():1354- return 'Awesome'1355- mod.add_url_rule('/', view_func=index)1356- app.register_module(mod)1357- rv = app.test_client().get('/')1358- assert rv.data == 'Awesome'1359- with app.test_request_context():1360- assert flask.url_for('frontend.index') == '/'1361-1362- @emits_module_deprecation_warning1363- def test_request_processing(self):1364- catched = []1365- app = flask.Flask(__name__)1366- admin = flask.Module(__name__, 'admin', url_prefix='/admin')1367- @admin.before_request1368- def before_admin_request():1369- catched.append('before-admin')1370- @admin.after_request1371- def after_admin_request(response):1372- catched.append('after-admin')1373- return response1374- @admin.route('/')1375- def admin_index():1376- return 'the admin'1377- @app.before_request1378- def before_request():1379- catched.append('before-app')1380- @app.after_request1381- def after_request(response):1382- catched.append('after-app')1383- return response1384- @app.route('/')1385- def index():1386- return 'the index'1387- app.register_module(admin)1388- c = app.test_client()1389-1390- assert c.get('/').data == 'the index'1391- assert catched == ['before-app', 'after-app']1392- del catched[:]1393-1394- assert c.get('/admin/').data == 'the admin'1395- assert catched == ['before-app', 'before-admin',1396- 'after-admin', 'after-app']1397-1398- @emits_module_deprecation_warning1399- def test_context_processors(self):1400- app = flask.Flask(__name__)1401- admin = flask.Module(__name__, 'admin', url_prefix='/admin')1402- @app.context_processor1403- def inject_all_regualr():1404- return {'a': 1}1405- @admin.context_processor1406- def inject_admin():1407- return {'b': 2}1408- @admin.app_context_processor1409- def inject_all_module():1410- return {'c': 3}1411- @app.route('/')1412- def index():1413- return flask.render_template_string('{{ a }}{{ b }}{{ c }}')1414- @admin.route('/')1415- def admin_index():1416- return flask.render_template_string('{{ a }}{{ b }}{{ c }}')1417- app.register_module(admin)1418- c = app.test_client()1419- assert c.get('/').data == '13'1420- assert c.get('/admin/').data == '123'1421-1422- @emits_module_deprecation_warning1423- def test_late_binding(self):1424- app = flask.Flask(__name__)1425- admin = flask.Module(__name__, 'admin')1426- @admin.route('/')1427- def index():1428- return '42'1429- app.register_module(admin, url_prefix='/admin')1430- assert app.test_client().get('/admin/').data == '42'1431-1432- @emits_module_deprecation_warning1433- def test_error_handling(self):1434- app = flask.Flask(__name__)1435- admin = flask.Module(__name__, 'admin')1436- @admin.app_errorhandler(404)1437- def not_found(e):1438- return 'not found', 4041439- @admin.app_errorhandler(500)1440- def internal_server_error(e):1441- return 'internal server error', 5001442- @admin.route('/')1443- def index():1444- flask.abort(404)1445- @admin.route('/error')1446- def error():1447- 1 // 01448- app.register_module(admin)1449- c = app.test_client()1450- rv = c.get('/')1451- assert rv.status_code == 4041452- assert rv.data == 'not found'1453- rv = c.get('/error')1454- assert rv.status_code == 5001455- assert 'internal server error' == rv.data1456-1457- def test_templates_and_static(self):1458- app = moduleapp1459- app.testing = True1460- c = app.test_client()1461-1462- rv = c.get('/')1463- assert rv.data == 'Hello from the Frontend'1464- rv = c.get('/admin/')1465- assert rv.data == 'Hello from the Admin'1466- rv = c.get('/admin/index2')1467- assert rv.data == 'Hello from the Admin'1468- rv = c.get('/admin/static/test.txt')1469- assert rv.data.strip() == 'Admin File'1470- rv = c.get('/admin/static/css/test.css')1471- assert rv.data.strip() == '/* nested file */'1472-1473- with app.test_request_context():1474- assert flask.url_for('admin.static', filename='test.txt') \1475- == '/admin/static/test.txt'1476-1477- with app.test_request_context():1478- try:1479- flask.render_template('missing.html')1480- except TemplateNotFound, e:1481- assert e.name == 'missing.html'1482- else:1483- assert 0, 'expected exception'1484-1485- with flask.Flask(__name__).test_request_context():1486- assert flask.render_template('nested/nested.txt') == 'I\'m nested'1487-1488- def test_safe_access(self):1489- app = moduleapp1490-1491- with app.test_request_context():1492- f = app.view_functions['admin.static']1493-1494- try:1495- f('/etc/passwd')1496- except NotFound:1497- pass1498- else:1499- assert 0, 'expected exception'1500- try:1501- f('../__init__.py')1502- except NotFound:1503- pass1504- else:1505- assert 0, 'expected exception'1506-1507- # testcase for a security issue that may exist on windows systems1508- import os1509- import ntpath1510- old_path = os.path1511- os.path = ntpath1512- try:1513- try:1514- f('..\\__init__.py')1515- except NotFound:1516- pass1517- else:1518- assert 0, 'expected exception'1519- finally:1520- os.path = old_path1521-1522- @emits_module_deprecation_warning1523- def test_endpoint_decorator(self):1524- from werkzeug.routing import Submount, Rule1525- from flask import Module1526-1527- app = flask.Flask(__name__)1528- app.testing = True1529- app.url_map.add(Submount('/foo', [1530- Rule('/bar', endpoint='bar'),1531- Rule('/', endpoint='index')1532- ]))1533- module = Module(__name__, __name__)1534-1535- @module.endpoint('bar')1536- def bar():1537- return 'bar'1538-1539- @module.endpoint('index')1540- def index():1541- return 'index'1542-1543- app.register_module(module)1544-1545- c = app.test_client()1546- assert c.get('/foo/').data == 'index'1547- assert c.get('/foo/bar').data == 'bar'1548-1549-1550-class BlueprintTestCase(unittest.TestCase):1551-1552- def test_blueprint_specific_error_handling(self):1553- frontend = flask.Blueprint('frontend', __name__)1554- backend = flask.Blueprint('backend', __name__)1555- sideend = flask.Blueprint('sideend', __name__)1556-1557- @frontend.errorhandler(403)1558- def frontend_forbidden(e):1559- return 'frontend says no', 4031560-1561- @frontend.route('/frontend-no')1562- def frontend_no():1563- flask.abort(403)1564-1565- @backend.errorhandler(403)1566- def backend_forbidden(e):1567- return 'backend says no', 4031568-1569- @backend.route('/backend-no')1570- def backend_no():1571- flask.abort(403)1572-1573- @sideend.route('/what-is-a-sideend')1574- def sideend_no():1575- flask.abort(403)1576-1577- app = flask.Flask(__name__)1578- app.register_blueprint(frontend)1579- app.register_blueprint(backend)1580- app.register_blueprint(sideend)1581-1582- @app.errorhandler(403)1583- def app_forbidden(e):1584- return 'application itself says no', 4031585-1586- c = app.test_client()1587-1588- assert c.get('/frontend-no').data == 'frontend says no'1589- assert c.get('/backend-no').data == 'backend says no'1590- assert c.get('/what-is-a-sideend').data == 'application itself says no'1591-1592- def test_blueprint_url_definitions(self):1593- bp = flask.Blueprint('test', __name__)1594-1595- @bp.route('/foo', defaults={'baz': 42})1596- def foo(bar, baz):1597- return '%s/%d' % (bar, baz)1598-1599- @bp.route('/bar')1600- def bar(bar):1601- return unicode(bar)1602-1603- app = flask.Flask(__name__)1604- app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23})1605- app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19})1606-1607- c = app.test_client()1608- self.assertEqual(c.get('/1/foo').data, u'23/42')1609- self.assertEqual(c.get('/2/foo').data, u'19/42')1610- self.assertEqual(c.get('/1/bar').data, u'23')1611- self.assertEqual(c.get('/2/bar').data, u'19')1612-1613- def test_blueprint_url_processors(self):1614- bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')1615-1616- @bp.url_defaults1617- def add_language_code(endpoint, values):1618- values.setdefault('lang_code', flask.g.lang_code)1619-1620- @bp.url_value_preprocessor1621- def pull_lang_code(endpoint, values):1622- flask.g.lang_code = values.pop('lang_code')1623-1624- @bp.route('/')1625- def index():1626- return flask.url_for('.about')1627-1628- @bp.route('/about')1629- def about():1630- return flask.url_for('.index')1631-1632- app = flask.Flask(__name__)1633- app.register_blueprint(bp)1634-1635- c = app.test_client()1636-1637- self.assertEqual(c.get('/de/').data, '/de/about')1638- self.assertEqual(c.get('/de/about').data, '/de/')1639-1640- def test_templates_and_static(self):1641- from blueprintapp import app1642- c = app.test_client()1643-1644- rv = c.get('/')1645- assert rv.data == 'Hello from the Frontend'1646- rv = c.get('/admin/')1647- assert rv.data == 'Hello from the Admin'1648- rv = c.get('/admin/index2')1649- assert rv.data == 'Hello from the Admin'1650- rv = c.get('/admin/static/test.txt')1651- assert rv.data.strip() == 'Admin File'1652- rv = c.get('/admin/static/css/test.css')1653- assert rv.data.strip() == '/* nested file */'1654-1655- with app.test_request_context():1656- assert flask.url_for('admin.static', filename='test.txt') \1657- == '/admin/static/test.txt'1658-1659- with app.test_request_context():1660- try:1661- flask.render_template('missing.html')1662- except TemplateNotFound, e:1663- assert e.name == 'missing.html'1664- else:1665- assert 0, 'expected exception'1666-1667- with flask.Flask(__name__).test_request_context():1668- assert flask.render_template('nested/nested.txt') == 'I\'m nested'1669-1670- def test_templates_list(self):1671- from blueprintapp import app1672- templates = sorted(app.jinja_env.list_templates())1673- self.assertEqual(templates, ['admin/index.html',1674- 'frontend/index.html'])1675-1676- def test_dotted_names(self):1677- frontend = flask.Blueprint('myapp.frontend', __name__)1678- backend = flask.Blueprint('myapp.backend', __name__)1679-1680- @frontend.route('/fe')1681- def frontend_index():1682- return flask.url_for('myapp.backend.backend_index')1683-1684- @frontend.route('/fe2')1685- def frontend_page2():1686- return flask.url_for('.frontend_index')1687-1688- @backend.route('/be')1689- def backend_index():1690- return flask.url_for('myapp.frontend.frontend_index')1691-1692- app = flask.Flask(__name__)1693- app.register_blueprint(frontend)1694- app.register_blueprint(backend)1695-1696- c = app.test_client()1697- self.assertEqual(c.get('/fe').data.strip(), '/be')1698- self.assertEqual(c.get('/fe2').data.strip(), '/fe')1699- self.assertEqual(c.get('/be').data.strip(), '/fe')1700-1701- def test_empty_url_defaults(self):1702- bp = flask.Blueprint('bp', __name__)1703-1704- @bp.route('/', defaults={'page': 1})1705- @bp.route('/page/<int:page>')1706- def something(page):1707- return str(page)1708-1709- app = flask.Flask(__name__)1710- app.register_blueprint(bp)1711-1712- c = app.test_client()1713- self.assertEqual(c.get('/').data, '1')1714- self.assertEqual(c.get('/page/2').data, '2')1715-1716- def test_route_decorator_custom_endpoint(self):1717-1718- bp = flask.Blueprint('bp', __name__)1719-1720- @bp.route('/foo')1721- def foo():1722- return flask.request.endpoint1723-1724- @bp.route('/bar', endpoint='bar')1725- def foo_bar():1726- return flask.request.endpoint1727-1728- @bp.route('/bar/123', endpoint='123')1729- def foo_bar_foo():1730- return flask.request.endpoint1731-1732- @bp.route('/bar/foo')1733- def bar_foo():1734- return flask.request.endpoint1735-1736- app = flask.Flask(__name__)1737- app.register_blueprint(bp, url_prefix='/py')1738-1739- @app.route('/')1740- def index():1741- return flask.request.endpoint1742-1743- c = app.test_client()1744- self.assertEqual(c.get('/').data, 'index')1745- self.assertEqual(c.get('/py/foo').data, 'bp.foo')1746- self.assertEqual(c.get('/py/bar').data, 'bp.bar')1747- self.assertEqual(c.get('/py/bar/123').data, 'bp.123')1748- self.assertEqual(c.get('/py/bar/foo').data, 'bp.bar_foo')1749-1750- def test_route_decorator_custom_endpoint_with_dots(self):1751- bp = flask.Blueprint('bp', __name__)1752-1753- @bp.route('/foo')1754- def foo():1755- return flask.request.endpoint1756-1757- try:1758- @bp.route('/bar', endpoint='bar.bar')1759- def foo_bar():1760- return flask.request.endpoint1761- except AssertionError:1762- pass1763- else:1764- raise AssertionError('expected AssertionError not raised')1765-1766- try:1767- @bp.route('/bar/123', endpoint='bar.123')1768- def foo_bar_foo():1769- return flask.request.endpoint1770- except AssertionError:1771- pass1772- else:1773- raise AssertionError('expected AssertionError not raised')1774-1775- def foo_foo_foo():1776- pass1777-1778- self.assertRaises(1779- AssertionError,1780- lambda: bp.add_url_rule(1781- '/bar/123', endpoint='bar.123', view_func=foo_foo_foo1782- )1783- )1784-1785- self.assertRaises(1786- AssertionError,1787- bp.route('/bar/123', endpoint='bar.123'),1788- lambda: None1789- )1790-1791- app = flask.Flask(__name__)1792- app.register_blueprint(bp, url_prefix='/py')1793-1794- c = app.test_client()1795- self.assertEqual(c.get('/py/foo').data, 'bp.foo')1796- # The rule's din't actually made it through1797- rv = c.get('/py/bar')1798- assert rv.status_code == 4041799- rv = c.get('/py/bar/123')1800- assert rv.status_code == 4041801-1802-class SendfileTestCase(unittest.TestCase):1803-1804- def test_send_file_regular(self):1805- app = flask.Flask(__name__)1806- with app.test_request_context():1807- rv = flask.send_file('static/index.html')1808- assert rv.direct_passthrough1809- assert rv.mimetype == 'text/html'1810- with app.open_resource('static/index.html') as f:1811- assert rv.data == f.read()1812-1813- def test_send_file_xsendfile(self):1814- app = flask.Flask(__name__)1815- app.use_x_sendfile = True1816- with app.test_request_context():1817- rv = flask.send_file('static/index.html')1818- assert rv.direct_passthrough1819- assert 'x-sendfile' in rv.headers1820- assert rv.headers['x-sendfile'] == \1821- os.path.join(app.root_path, 'static/index.html')1822- assert rv.mimetype == 'text/html'1823-1824- def test_send_file_object(self):1825- app = flask.Flask(__name__)1826- with catch_warnings() as captured:1827- with app.test_request_context():1828- f = open(os.path.join(app.root_path, 'static/index.html'))1829- rv = flask.send_file(f)1830- with app.open_resource('static/index.html') as f:1831- assert rv.data == f.read()1832- assert rv.mimetype == 'text/html'1833- # mimetypes + etag1834- assert len(captured) == 21835-1836- app.use_x_sendfile = True1837- with catch_warnings() as captured:1838- with app.test_request_context():1839- f = open(os.path.join(app.root_path, 'static/index.html'))1840- rv = flask.send_file(f)1841- assert rv.mimetype == 'text/html'1842- assert 'x-sendfile' in rv.headers1843- assert rv.headers['x-sendfile'] == \1844- os.path.join(app.root_path, 'static/index.html')1845- # mimetypes + etag1846- assert len(captured) == 21847-1848- app.use_x_sendfile = False1849- with app.test_request_context():1850- with catch_warnings() as captured:1851- f = StringIO('Test')1852- rv = flask.send_file(f)1853- assert rv.data == 'Test'1854- assert rv.mimetype == 'application/octet-stream'1855- # etags1856- assert len(captured) == 11857- with catch_warnings() as captured:1858- f = StringIO('Test')1859- rv = flask.send_file(f, mimetype='text/plain')1860- assert rv.data == 'Test'1861- assert rv.mimetype == 'text/plain'1862- # etags1863- assert len(captured) == 11864-1865- app.use_x_sendfile = True1866- with catch_warnings() as captured:1867- with app.test_request_context():1868- f = StringIO('Test')1869- rv = flask.send_file(f)1870- assert 'x-sendfile' not in rv.headers1871- # etags1872- assert len(captured) == 11873-1874- def test_attachment(self):1875- app = flask.Flask(__name__)1876- with catch_warnings() as captured:1877- with app.test_request_context():1878- f = open(os.path.join(app.root_path, 'static/index.html'))1879- rv = flask.send_file(f, as_attachment=True)1880- value, options = parse_options_header(rv.headers['Content-Disposition'])1881- assert value == 'attachment'1882- # mimetypes + etag1883- assert len(captured) == 21884-1885- with app.test_request_context():1886- assert options['filename'] == 'index.html'1887- rv = flask.send_file('static/index.html', as_attachment=True)1888- value, options = parse_options_header(rv.headers['Content-Disposition'])1889- assert value == 'attachment'1890- assert options['filename'] == 'index.html'1891-1892- with app.test_request_context():1893- rv = flask.send_file(StringIO('Test'), as_attachment=True,1894- attachment_filename='index.txt',1895- add_etags=False)1896- assert rv.mimetype == 'text/plain'1897- value, options = parse_options_header(rv.headers['Content-Disposition'])1898- assert value == 'attachment'1899- assert options['filename'] == 'index.txt'1900-1901-1902-class LoggingTestCase(unittest.TestCase):1903-1904- def test_logger_cache(self):1905- app = flask.Flask(__name__)1906- logger1 = app.logger1907- assert app.logger is logger11908- assert logger1.name == __name__1909- app.logger_name = __name__ + '/test_logger_cache'1910- assert app.logger is not logger11911-1912- def test_debug_log(self):1913- app = flask.Flask(__name__)1914- app.debug = True1915-1916- @app.route('/')1917- def index():1918- app.logger.warning('the standard library is dead')1919- app.logger.debug('this is a debug statement')1920- return ''1921-1922- @app.route('/exc')1923- def exc():1924- 1/01925- c = app.test_client()1926-1927- with catch_stderr() as err:1928- c.get('/')1929- out = err.getvalue()1930- assert 'WARNING in flask_tests [' in out1931- assert 'flask_tests.py' in out1932- assert 'the standard library is dead' in out1933- assert 'this is a debug statement' in out1934-1935- with catch_stderr() as err:1936- try:1937- c.get('/exc')1938- except ZeroDivisionError:1939- pass1940- else:1941- assert False, 'debug log ate the exception'1942-1943- def test_exception_logging(self):1944- out = StringIO()1945- app = flask.Flask(__name__)1946- app.logger_name = 'flask_tests/test_exception_logging'1947- app.logger.addHandler(StreamHandler(out))1948-1949- @app.route('/')1950- def index():1951- 1/01952-1953- rv = app.test_client().get('/')1954- assert rv.status_code == 5001955- assert 'Internal Server Error' in rv.data1956-1957- err = out.getvalue()1958- assert 'Exception on / [GET]' in err1959- assert 'Traceback (most recent call last):' in err1960- assert '1/0' in err1961- assert 'ZeroDivisionError:' in err1962-1963- def test_processor_exceptions(self):1964- app = flask.Flask(__name__)1965- @app.before_request1966- def before_request():1967- if trigger == 'before':1968- 1/01969- @app.after_request1970- def after_request(response):1971- if trigger == 'after':1972- 1/01973- return response1974- @app.route('/')1975- def index():1976- return 'Foo'1977- @app.errorhandler(500)1978- def internal_server_error(e):1979- return 'Hello Server Error', 5001980- for trigger in 'before', 'after':1981- rv = app.test_client().get('/')1982- assert rv.status_code == 5001983- assert rv.data == 'Hello Server Error'1984-1985-1986-class ConfigTestCase(unittest.TestCase):1987-1988- def common_object_test(self, app):1989- assert app.secret_key == 'devkey'1990- assert app.config['TEST_KEY'] == 'foo'1991- assert 'ConfigTestCase' not in app.config1992-1993- def test_config_from_file(self):1994- app = flask.Flask(__name__)1995- app.config.from_pyfile('flask_tests.py')1996- self.common_object_test(app)1997-1998- def test_config_from_object(self):1999- app = flask.Flask(__name__)2000- app.config.from_object(__name__)2001- self.common_object_test(app)2002-2003- def test_config_from_class(self):2004- class Base(object):2005- TEST_KEY = 'foo'2006- class Test(Base):2007- SECRET_KEY = 'devkey'2008- app = flask.Flask(__name__)2009- app.config.from_object(Test)2010- self.common_object_test(app)2011-2012- def test_config_from_envvar(self):2013- import os2014- env = os.environ2015- try:2016- os.environ = {}2017- app = flask.Flask(__name__)2018- try:2019- app.config.from_envvar('FOO_SETTINGS')2020- except RuntimeError, e:2021- assert "'FOO_SETTINGS' is not set" in str(e)2022- else:2023- assert 0, 'expected exception'2024- assert not app.config.from_envvar('FOO_SETTINGS', silent=True)2025-2026- os.environ = {'FOO_SETTINGS': 'flask_tests.py'}2027- assert app.config.from_envvar('FOO_SETTINGS')2028- self.common_object_test(app)2029- finally:2030- os.environ = env2031-2032- def test_config_missing(self):2033- app = flask.Flask(__name__)2034- try:2035- app.config.from_pyfile('missing.cfg')2036- except IOError, e:2037- msg = str(e)2038- assert msg.startswith('[Errno 2] Unable to load configuration '2039- 'file (No such file or directory):')2040- assert msg.endswith("missing.cfg'")2041- else:2042- assert 0, 'expected config'2043- assert not app.config.from_pyfile('missing.cfg', silent=True)2044-2045-2046-class SubdomainTestCase(unittest.TestCase):2047-2048- def test_basic_support(self):2049- app = flask.Flask(__name__)2050- app.config['SERVER_NAME'] = 'localhost'2051- @app.route('/')2052- def normal_index():2053- return 'normal index'2054- @app.route('/', subdomain='test')2055- def test_index():2056- return 'test index'2057-2058- c = app.test_client()2059- rv = c.get('/', 'http://localhost/')2060- assert rv.data == 'normal index'2061-2062- rv = c.get('/', 'http://test.localhost/')2063- assert rv.data == 'test index'2064-2065- @emits_module_deprecation_warning2066- def test_module_static_path_subdomain(self):2067- app = flask.Flask(__name__)2068- app.config['SERVER_NAME'] = 'example.com'2069- from subdomaintestmodule import mod2070- app.register_module(mod)2071- c = app.test_client()2072- rv = c.get('/static/hello.txt', 'http://foo.example.com/')2073- assert rv.data.strip() == 'Hello Subdomain'2074-2075- def test_subdomain_matching(self):2076- app = flask.Flask(__name__)2077- app.config['SERVER_NAME'] = 'localhost'2078- @app.route('/', subdomain='<user>')2079- def index(user):2080- return 'index for %s' % user2081-2082- c = app.test_client()2083- rv = c.get('/', 'http://mitsuhiko.localhost/')2084- assert rv.data == 'index for mitsuhiko'2085-2086- @emits_module_deprecation_warning2087- def test_module_subdomain_support(self):2088- app = flask.Flask(__name__)2089- mod = flask.Module(__name__, 'test', subdomain='testing')2090- app.config['SERVER_NAME'] = 'localhost'2091-2092- @mod.route('/test')2093- def test():2094- return 'Test'2095-2096- @mod.route('/outside', subdomain='xtesting')2097- def bar():2098- return 'Outside'2099-2100- app.register_module(mod)2101-2102- c = app.test_client()2103- rv = c.get('/test', 'http://testing.localhost/')2104- assert rv.data == 'Test'2105- rv = c.get('/outside', 'http://xtesting.localhost/')2106- assert rv.data == 'Outside'2107-2108-2109-class TestSignals(unittest.TestCase):2110-2111- def test_template_rendered(self):2112- app = flask.Flask(__name__)2113-2114- @app.route('/')2115- def index():2116- return flask.render_template('simple_template.html', whiskey=42)2117-2118- recorded = []2119- def record(sender, template, context):2120- recorded.append((template, context))2121-2122- flask.template_rendered.connect(record, app)2123- try:2124- app.test_client().get('/')2125- assert len(recorded) == 12126- template, context = recorded[0]2127- assert template.name == 'simple_template.html'2128- assert context['whiskey'] == 422129- finally:2130- flask.template_rendered.disconnect(record, app)2131-2132- def test_request_signals(self):2133- app = flask.Flask(__name__)2134- calls = []2135-2136- def before_request_signal(sender):2137- calls.append('before-signal')2138-2139- def after_request_signal(sender, response):2140- assert response.data == 'stuff'2141- calls.append('after-signal')2142-2143- @app.before_request2144- def before_request_handler():2145- calls.append('before-handler')2146-2147- @app.after_request2148- def after_request_handler(response):2149- calls.append('after-handler')2150- response.data = 'stuff'2151- return response2152-2153- @app.route('/')2154- def index():2155- calls.append('handler')2156- return 'ignored anyway'2157-2158- flask.request_started.connect(before_request_signal, app)2159- flask.request_finished.connect(after_request_signal, app)2160-2161- try:2162- rv = app.test_client().get('/')2163- assert rv.data == 'stuff'2164-2165- assert calls == ['before-signal', 'before-handler',2166- 'handler', 'after-handler',2167- 'after-signal']2168- finally:2169- flask.request_started.disconnect(before_request_signal, app)2170- flask.request_finished.disconnect(after_request_signal, app)2171-2172- def test_request_exception_signal(self):2173- app = flask.Flask(__name__)2174- recorded = []2175-2176- @app.route('/')2177- def index():2178- 1/02179-2180- def record(sender, exception):2181- recorded.append(exception)2182-2183- flask.got_request_exception.connect(record, app)2184- try:2185- assert app.test_client().get('/').status_code == 5002186- assert len(recorded) == 12187- assert isinstance(recorded[0], ZeroDivisionError)2188- finally:2189- flask.got_request_exception.disconnect(record, app)2190-2191-2192-class ViewTestCase(unittest.TestCase):2193-2194- def common_test(self, app):2195- c = app.test_client()2196-2197- self.assertEqual(c.get('/').data, 'GET')2198- self.assertEqual(c.post('/').data, 'POST')2199- self.assertEqual(c.put('/').status_code, 405)2200- meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])2201- self.assertEqual(sorted(meths), ['GET', 'HEAD', 'OPTIONS', 'POST'])2202-2203- def test_basic_view(self):2204- app = flask.Flask(__name__)2205-2206- class Index(flask.views.View):2207- methods = ['GET', 'POST']2208- def dispatch_request(self):2209- return flask.request.method2210-2211- app.add_url_rule('/', view_func=Index.as_view('index'))2212- self.common_test(app)2213-2214- def test_method_based_view(self):2215- app = flask.Flask(__name__)2216-2217- class Index(flask.views.MethodView):2218- def get(self):2219- return 'GET'2220- def post(self):2221- return 'POST'2222-2223- app.add_url_rule('/', view_func=Index.as_view('index'))2224-2225- self.common_test(app)2226-2227- def test_view_patching(self):2228- app = flask.Flask(__name__)2229-2230- class Index(flask.views.MethodView):2231- def get(self):2232- 1/02233- def post(self):2234- 1/02235-2236- class Other(Index):2237- def get(self):2238- return 'GET'2239- def post(self):2240- return 'POST'2241-2242- view = Index.as_view('index')2243- view.view_class = Other2244- app.add_url_rule('/', view_func=view)2245- self.common_test(app)2246-2247- def test_view_inheritance(self):2248- app = flask.Flask(__name__)2249-2250- class Index(flask.views.MethodView):2251- def get(self):2252- return 'GET'2253- def post(self):2254- return 'POST'2255-2256- class BetterIndex(Index):2257- def delete(self):2258- return 'DELETE'2259-2260- app.add_url_rule('/', view_func=BetterIndex.as_view('index'))2261- c = app.test_client()2262-2263- meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])2264- self.assertEqual(sorted(meths), ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST'])2265-2266-2267-class DeprecationsTestCase(unittest.TestCase):2268-2269- def test_init_jinja_globals(self):2270- class MyFlask(flask.Flask):2271- def init_jinja_globals(self):2272- self.jinja_env.globals['foo'] = '42'2273-2274- with catch_warnings() as log:2275- app = MyFlask(__name__)2276- @app.route('/')2277- def foo():2278- return app.jinja_env.globals['foo']2279-2280- c = app.test_client()2281- assert c.get('/').data == '42'2282- assert len(log) == 12283- assert 'init_jinja_globals' in str(log[0]['message'])2284-2285-2286-def suite():2287- from minitwit_tests import MiniTwitTestCase2288- from flaskr_tests import FlaskrTestCase2289- suite = unittest.TestSuite()2290- suite.addTest(unittest.makeSuite(ContextTestCase))2291- suite.addTest(unittest.makeSuite(BasicFunctionalityTestCase))2292- suite.addTest(unittest.makeSuite(TemplatingTestCase))2293- suite.addTest(unittest.makeSuite(ModuleTestCase))2294- suite.addTest(unittest.makeSuite(BlueprintTestCase))2295- suite.addTest(unittest.makeSuite(SendfileTestCase))2296- suite.addTest(unittest.makeSuite(LoggingTestCase))2297- suite.addTest(unittest.makeSuite(ConfigTestCase))2298- suite.addTest(unittest.makeSuite(SubdomainTestCase))2299- suite.addTest(unittest.makeSuite(ViewTestCase))2300- suite.addTest(unittest.makeSuite(DeprecationsTestCase))2301- suite.addTest(unittest.makeSuite(InstanceTestCase))2302- if flask.json_available:2303- suite.addTest(unittest.makeSuite(JSONTestCase))2304- if flask.signals_available:2305- suite.addTest(unittest.makeSuite(TestSignals))2306- suite.addTest(unittest.makeSuite(MiniTwitTestCase))2307- suite.addTest(unittest.makeSuite(FlaskrTestCase))2308- return suite2309-2310-2311-if __name__ == '__main__':2312- unittest.main(defaultTest='suite')deleted:tests/flaskext_test.py-311 removed
1-# -*- coding: utf-8 -*-2-"""3- Flask Extension Tests4- ~~~~~~~~~~~~~~~~~~~~~5-6- Tests the Flask extensions.7-8- :copyright: (c) 2010 by Ali Afshar.9- :license: BSD, see LICENSE for more details.10-"""11-12-from __future__ import with_statement13-14-import os15-import sys16-import shutil17-import urllib218-import tempfile19-import subprocess20-import argparse21-22-from flask import json23-24-from setuptools.package_index import PackageIndex25-from setuptools.archive_util import unpack_archive26-27-flask_svc_url = 'http://flask.pocoo.org/extensions/'28-29-30-# OS X has awful paths when using mkstemp or gettempdir(). I don't31-# care about security or clashes here, so pick something that is32-# actually rememberable.33-if sys.platform == 'darwin':34- _tempdir = '/private/tmp'35-else:36- _tempdir = tempfile.gettempdir()37-tdir = _tempdir + '/flaskext-test'38-flaskdir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))39-40-41-# virtualenv hack *cough*42-os.environ['PYTHONDONTWRITEBYTECODE'] = ''43-44-45-RESULT_TEMPATE = u'''\46-<!doctype html>47-<title>Flask-Extension Test Results</title>48-<style type=text/css>49- body { font-family: 'Georgia', serif; font-size: 17px; color: #000; }50- a { color: #004B6B; }51- a:hover { color: #6D4100; }52- h1, h2, h3 { font-family: 'Garamond', 'Georgia', serif; font-weight: normal; }53- h1 { font-size: 30px; margin: 15px 0 5px 0; }54- h2 { font-size: 24px; margin: 15px 0 5px 0; }55- h3 { font-size: 19px; margin: 15px 0 5px 0; }56- textarea, code,57- pre { font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono',58- 'Bitstream Vera Sans Mono', monospace!important; font-size: 15px;59- background: #eee; }60- pre { padding: 7px 15px; line-height: 1.3; }61- p { line-height: 1.4; }62- table { border: 1px solid black; border-collapse: collapse;63- margin: 15px 0; }64- td, th { border: 1px solid black; padding: 4px 10px;65- text-align: left; }66- th { background: #eee; font-weight: normal; }67- tr.success { background: #D3F5CC; }68- tr.failed { background: #F5D2CB; }69-</style>70-<h1>Flask-Extension Test Results</h1>71-<p>72- This page contains the detailed test results for the test run of73- all {{ 'approved' if approved }} Flask extensions.74-<h2>Summary</h2>75-<table class=results>76- <thead>77- <tr>78- <th>Extension79- <th>Version80- <th>Author81- <th>License82- <th>Outcome83- {%- for iptr, _ in results[0].logs|dictsort %}84- <th>{{ iptr }}85- {%- endfor %}86- </tr>87- </thead>88- <tbody>89- {%- for result in results %}90- {% set outcome = 'success' if result.success else 'failed' %}91- <tr class={{ outcome }}>92- <th>{{ result.name }}93- <td>{{ result.version }}94- <td>{{ result.author }}95- <td>{{ result.license }}96- <td>{{ outcome }}97- {%- for iptr, _ in result.logs|dictsort %}98- <td><a href="#{{ result.name }}-{{ iptr }}">see log</a>99- {%- endfor %}100- </tr>101- {%- endfor %}102- </tbody>103-</table>104-<h2>Test Logs</h2>105-<p>Detailed test logs for all tests on all platforms:106-{%- for result in results %}107- {%- for iptr, log in result.logs|dictsort %}108- <h3 id="{{ result.name }}-{{ iptr }}">109- {{ result.name }} - {{ result.version }} [{{ iptr }}]</h3>110- <pre>{{ log }}</pre>111- {%- endfor %}112-{%- endfor %}113-'''114-115-116-def log(msg, *args):117- print '[EXTTEST]', msg % args118-119-120-class TestResult(object):121-122- def __init__(self, name, folder, statuscode, interpreters):123- intrptr = os.path.join(folder, '.tox/%s/bin/python'124- % interpreters[0])125- self.statuscode = statuscode126- self.folder = folder127- self.success = statuscode == 0128-129- def fetch(field):130- try:131- c = subprocess.Popen([intrptr, 'setup.py',132- '--' + field], cwd=folder,133- stdout=subprocess.PIPE)134- return c.communicate()[0].strip()135- except OSError:136- return '?'137- self.name = name138- self.license = fetch('license')139- self.author = fetch('author')140- self.version = fetch('version')141-142- self.logs = {}143- for interpreter in interpreters:144- logfile = os.path.join(folder, '.tox/%s/log/test.log'145- % interpreter)146- if os.path.isfile(logfile):147- self.logs[interpreter] = open(logfile).read()148- else:149- self.logs[interpreter] = ''150-151-152-def create_tdir():153- try:154- shutil.rmtree(tdir)155- except Exception:156- pass157- os.mkdir(tdir)158-159-160-def package_flask():161- distfolder = tdir + '/.flask-dist'162- c = subprocess.Popen(['python', 'setup.py', 'sdist', '--formats=gztar',163- '--dist', distfolder], cwd=flaskdir)164- c.wait()165- return os.path.join(distfolder, os.listdir(distfolder)[0])166-167-168-def get_test_command(checkout_dir):169- if os.path.isfile(checkout_dir + '/Makefile'):170- return 'make test'171- return 'python setup.py test'172-173-174-def fetch_extensions_list():175- req = urllib2.Request(flask_svc_url, headers={'accept':'application/json'})176- d = urllib2.urlopen(req).read()177- data = json.loads(d)178- for ext in data['extensions']:179- yield ext180-181-182-def checkout_extension(name):183- log('Downloading extension %s to temporary folder', name)184- root = os.path.join(tdir, name)185- os.mkdir(root)186- checkout_path = PackageIndex().download(name, root)187-188- unpack_archive(checkout_path, root)189- path = None190- for fn in os.listdir(root):191- path = os.path.join(root, fn)192- if os.path.isdir(path):193- break194- log('Downloaded to %s', path)195- return path196-197-198-tox_template = """[tox]199-envlist=%(env)s200-201-[testenv]202-deps=203- %(deps)s204- distribute205- py206-commands=bash flaskext-runtest.sh {envlogdir}/test.log207-downloadcache=%(cache)s208-"""209-210-211-def create_tox_ini(checkout_path, interpreters, flask_dep):212- tox_path = os.path.join(checkout_path, 'tox-flask-test.ini')213- if not os.path.exists(tox_path):214- with open(tox_path, 'w') as f:215- f.write(tox_template % {216- 'env': ','.join(interpreters),217- 'cache': tdir,218- 'deps': flask_dep219- })220- return tox_path221-222-223-def iter_extensions(only_approved=True):224- for ext in fetch_extensions_list():225- if ext['approved'] or not only_approved:226- yield ext['name']227-228-229-def test_extension(name, interpreters, flask_dep):230- checkout_path = checkout_extension(name)231- log('Running tests with tox in %s', checkout_path)232-233- # figure out the test command and write a wrapper script. We234- # can't write that directly into the tox ini because tox does235- # not invoke the command from the shell so we have no chance236- # to pipe the output into a logfile. The /dev/null hack is237- # to trick py.test (if used) into not guessing widths from the238- # invoking terminal.239- test_command = get_test_command(checkout_path)240- log('Test command: %s', test_command)241- f = open(checkout_path + '/flaskext-runtest.sh', 'w')242- f.write(test_command + ' &> "$1" < /dev/null\n')243- f.close()244-245- # if there is a tox.ini, remove it, it will cause troubles246- # for us. Remove it if present, we are running tox ourselves247- # afterall.248-249- create_tox_ini(checkout_path, interpreters, flask_dep)250- rv = subprocess.call(['tox', '-c', 'tox-flask-test.ini'], cwd=checkout_path)251- return TestResult(name, checkout_path, rv, interpreters)252-253-254-def run_tests(extensions, interpreters):255- results = {}256- create_tdir()257- log('Packaging Flask')258- flask_dep = package_flask()259- log('Running extension tests')260- log('Temporary Environment: %s', tdir)261- for name in extensions:262- log('Testing %s', name)263- result = test_extension(name, interpreters, flask_dep)264- if result.success:265- log('Extension test succeeded')266- else:267- log('Extension test failed')268- results[name] = result269- return results270-271-272-def render_results(results, approved):273- from jinja2 import Template274- items = results.values()275- items.sort(key=lambda x: x.name.lower())276- rv = Template(RESULT_TEMPATE, autoescape=True).render(results=items,277- approved=approved)278- fd, filename = tempfile.mkstemp(suffix='.html')279- os.fdopen(fd, 'w').write(rv.encode('utf-8') + '\n')280- return filename281-282-283-def main():284- parser = argparse.ArgumentParser(description='Runs Flask extension tests')285- parser.add_argument('--all', dest='all', action='store_true',286- help='run against all extensions, not just approved')287- parser.add_argument('--browse', dest='browse', action='store_true',288- help='show browser with the result summary')289- parser.add_argument('--env', dest='env', default='py25,py26,py27',290- help='the tox environments to run against')291- parser.add_argument('--extension=', dest='extension', default=None,292- help='tests a single extension')293- args = parser.parse_args()294-295- if args.extension is not None:296- only_approved = False297- extensions = [args.extension]298- else:299- only_approved = not args.all300- extensions = iter_extensions(only_approved)301-302- results = run_tests(extensions, [x.strip() for x in args.env.split(',')])303- filename = render_results(results, only_approved)304- if args.browse:305- import webbrowser306- webbrowser.open('file:///' + filename.lstrip('/'))307- print 'Results written to', filename308-309-310-if __name__ == '__main__':311- main()modified:CHANGES+11 added
30 unmodified lines31 drop files that are modified at runtime (uploads etc.). Also this is32 conceptionally only instance depending and outside version control so it's33 the perfect place to put configuration files etc. For more information34 see :ref:`instance-folders`.35+- Added the ``APPLICATION_ROOT`` configuration variable.36+- Implemented :meth:`~flask.testing.TestClient.session_transaction` to37+ easily modify sessions from the test environment.38+- Refactored test client internally. The ``APPLICATION_ROOT`` configuration39+ variable as well as ``SERVER_NAME`` are now properly used by the test client40+ as defaults.41+- Added :attr:`flask.views.View.decorators` to support simpler decorating of42+ pluggable (class based) views.43+- Fixed an issue where the test client if used with the with statement did not44+ trigger the execution of the teardown handlers.45+- Added finer control over the session cookie parameters.46 47 Version 0.7.348 -------------49 238 unmodified linesmodified:Makefile+1 added-1 removed
1 unmodified line2 3 all: clean-pyc test4 5 test:6- python setup.py test6+ python run-tests.py7 8 audit:9 python setup.py audit10 24 unmodified linesmodified:MANIFEST.in+4 added-1 removed
1-include Makefile CHANGES LICENSE AUTHORS1+include Makefile CHANGES LICENSE AUTHORS run-tests.py2 recursive-include artwork *3 recursive-include tests *4 recursive-include examples *5 recursive-include docs *2 unmodified lines8 recursive-exclude tests *.pyc9 recursive-exclude tests *.pyo10 recursive-exclude examples *.pyc11 recursive-exclude examples *.pyo12+recursive-include flask/testsuite/static *13+recursive-include flask/testsuite/templates *14+recursive-include flask/testsuite/test_apps *15 prune docs/_build16 prune docs/_themes/.gitmodified:README+25 added-8 removed
9 unmodified lines10 and was developed with best intentions in mind.11 12 ~ Is it ready?13 14- A preview release is out now, and I'm hoping for some15- input about what you want from a microframework and16- how it should look like. Consider the API to slightly17- improve over time.14+ It's still not 1.0 but it's shaping up nicely and is15+ already widely used. Consider the API to slightly16+ improve over time but we don't plan on breaking it.17 18 ~ What do I need?19 21- Jinja 2.4 and Werkzeug 0.6.1. `easy_install` will22- install them for you if you do `easy_install Flask==dev`.20+ Jinja 2.4 and Werkzeug 0.6.1. `pip` or `easy_install` will21+ install them for you if you do `easy_install Flask`.22 I encourage you to use a virtualenv. Check the docs for23 complete installation and usage instructions.24 25 ~ Where are the docs?26 28- Go to http://flask.pocoo.org/ for a prebuilt version of29- the current documentation. Otherwise build them yourself27+ Go to http://flask.pocoo.org/docs/ for a prebuilt version28+ of the current documentation. Otherwise build them yourself29 from the sphinx sources in the docs folder.30 31+ ~ Where are the tests?32+33+ Good that you're asking. The tests are in the34+ flask/testsuite package. To run the tests use the35+ `run-tests.py` file:36+37+ $ python run-tests.py38+39+ If it's not enough output for you, you can use the40+ `--verbose` flag:41+42+ $ python run-tests.py --verbose43+44+ If you just want one particular testcase to run you can45+ provide it on the command line:46+47+ $ python run-tests.py test_to_run48+49 ~ Where can I get help?50 51 Either use the #pocoo IRC channel on irc.freenode.net or52 ask on the mailinglist: http://flask.pocoo.org/mailinglist/added:run-tests.py+3 added
1+#!/usr/bin/env python2+from flask.testsuite import main3+main()modified:setup.py+5 added-8 removed
75 unmodified lines76 print ("Audit finished with total %d warnings." % warns)77 else:78 print ("No problems found in sourcecode.")79 80-def run_tests():81- import os, sys82- sys.path.append(os.path.join(os.path.dirname(__file__), 'tests'))83- from flask_tests import suite84- return suite()80 86-81 setup(82 name='Flask',83 version='0.8-dev',84 url='http://github.com/mitsuhiko/flask/',2 unmodified lines87 author_email='armin.ronacher@active-4.com',88 description='A microframework based on Werkzeug, Jinja2 '89 'and good intentions',90 long_description=__doc__,97- packages=['flask'],91+ packages=['flask', 'flask.testsuite'],92+ package_data={93+ 'flask.testsuite': ['test_apps/*', 'static/*', 'templates/*']94+ },95 zip_safe=False,96 platforms='any',97 install_requires=[98 'Werkzeug>=0.6.1',9 unmodified lines108 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',109 'Topic :: Software Development :: Libraries :: Python Modules'110 ],111 cmdclass={'audit': run_audit},115- test_suite='__main__.run_tests'112+ test_suite='flask.testsuite.suite'113 )