Skip to content
Myr

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

93 files+3657 added−2827 removed

modified:docs/patterns/sqlite3.rst+9 added-1 removed
22 unmodified lines
23 g.db = connect_db()2425 @app.teardown_request26 def teardown_request(exception):27 if hasattr(g, 'db'):27 g.db.close()28 g.db.close()2930.. note::3132 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.3637Connect on Demand38-----------------3940The downside of this approach is that this will only work if Flask
79 unmodified lines
modified:docs/api.rst+9 added
216 unmodified lines
217.. autoclass:: SessionMixin218 :members:219220221Test Client222-----------223224.. currentmodule:: flask.testing225226.. autoclass:: FlaskClient227 :members:228229230Application Globals231-------------------232233.. currentmodule:: flask
270 unmodified lines
modified:docs/config.rst+45 added-9 removed
68 unmodified lines
69 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 lines
154.. versionadded:: 0.7155 ``PROPAGATE_EXCEPTIONS``, ``PRESERVE_CONTEXT_ON_EXCEPTION``156157.. 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``162163Configuring from Files164----------------------165
148 unmodified lines
314“instance folder”. The instance folder is designed to not be under315version control and be deployment specific. It's the perfect place to316drop things that either change at runtime or configuration files.317294To make it easier to put this folder into an ignore list for your version295control system it's called ``instance`` and placed directly next to your296package or module by default. This path can be overridden by specifying297the `instance_path` parameter to your application::318You can either explicitly provide the path of the instance folder when319creating the Flask application or you can let Flask autodetect the320instance folder. For explicit configuration use the `instance_path`321parameter::322323 app = Flask(__name__, instance_path='/path/to/instance/folder')324301Default locations::325Please keep in mind that this path *must* be absolute when provided.326303 Module situation:327If the `instance_path` parameter is not provided the following default328locations are used:329330- Uninstalled module::331332 /myapp.py333 /instance334307 Package situation:335- Uninstalled package::336337 /myapp338 /__init__.py339 /instance340312Please keep in mind that this path *must* be absolute when provided.341- Installed module or package::342343 $PREFIX/lib/python2.X/site-packages/myapp344 $PREFIX/var/myapp-instance345346 ``$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.349350Since the config object provided loading of configuration files from351relative filenames we made it possible to change the loading via filenames352to be relative to the instance path if wanted. The behavior of relative353paths in config files can be flipped between “relative to the application
26 unmodified lines
modified:docs/design.rst+16 added
77 unmodified lines
78Furthermore this design makes it possible to use a factory function to79create the application which is very helpful for unittesting and similar80things (:ref:`app-factories`).8182The Routing System83------------------8485Flask uses the Werkzeug routing system which has was designed to86automatically order routes by complexity. This means that you can declare87routes in arbitrary order and they will still work as expected. This is a88requirement if you want to properly implement decorator based routing89since decorators could be fired in undefined order when the application is90split into multiple modules.9192Another design decision with the Werkzeug routing system is that routes93in Werkzeug try to ensure that there is that URLs are unique. Werkzeug94will go quite far with that in that it will automatically redirect to a95canonical URL if a route is ambiguous.969798One Template Engine99-------------------100101Flask decides on one template engine: Jinja2. Why doesn't Flask have a
90 unmodified lines
modified:docs/foreword.rst+23 added-27 removed
7 unmodified lines
8What does "micro" mean?9-----------------------1011To me, the "micro" in microframework refers not only to the simplicity and12small size of the framework, but also to the typically limited complexity13and size of applications that are written with the framework. Also the14fact that you can have an entire application in a single Python file. To15be approachable and concise, a microframework sacrifices a few features16that may be necessary in larger or more complex applications.12small size of the framework, but also the fact that it does not make much13decisions for you. While Flask does pick a templating engine for you, we14won't make such decisions for your datastore or other parts.1518For example, Flask uses thread-local objects internally so that you don't19have to pass objects around from function to function within a request in20order to stay threadsafe. While this is a really easy approach and saves21you a lot of time, it might also cause some troubles for very large22applications because changes on these thread-local objects can happen23anywhere in the same thread.16For us however the term “micro” does not mean that the whole implementation17has to fit into a single Python file.1825Flask provides some tools to deal with the downsides of this approach but26it might be an issue for larger applications because in theory27modifications on these objects might happen anywhere in the same thread.19One of the design decisions with Flask was that simple tasks should be20simple and not take up a lot of code and yet not limit yourself. Because21of that we took a few design choices that some people might find22surprising or unorthodox. For example, Flask uses thread-local objects23internally so that you don't have to pass objects around from function to24function within a request in order to stay threadsafe. While this is a25really easy approach and saves you a lot of time, it might also cause some26troubles for very large applications because changes on these thread-local27objects can happen anywhere in the same thread. In order to solve these28problems we don't hide the thread locals for you but instead embrace them29and provide you with a lot of tools to make it as pleasant as possible to30work with them.3132Flask is also based on convention over configuration, which means that33many things are preconfigured. For example, by convention, templates and34static files are in subdirectories within the Python source tree of the32application.35application. While this can be changed you usually don't have to.3637The main reason however why Flask is called a "microframework" is the idea38to keep the core simple but extensible. There is no database abstraction39layer, no form validation or anything else where different libraries
2 unmodified lines
42was implemented in Flask itself. There are currently extensions for43object relational mappers, form validation, upload handling, various open44authentication technologies and more.4543However Flask is not much code and it is built on a very solid foundation44and with that it is very easy to adapt for large applications. If you are45interested in that, check out the :ref:`becomingbig` chapter.46Since Flask is based on a very solid foundation there is not a lot of code47in Flask itself. As such it's easy to adapt even for lage applications48and we are making sure that you can either configure it as much as49possible by subclassing things or by forking the entire codebase. If you50are interested in that, check out the :ref:`becomingbig` chapter.5152If you are curious about the Flask design principles, head over to the53section about :ref:`design`.5450A Framework and an Example51--------------------------5253Flask is not only a microframework; it is also an example. Based on54Flask, there will be a series of blog posts that explain how to create a55framework. Flask itself is just one way to implement a framework on top56of existing libraries. Unlike many other microframeworks, Flask does not57try to implement everything on its own; it reuses existing code.5855Web Development is Dangerous56----------------------------5758I'm not joking. Well, maybe a little. If you write a web
42 unmodified lines
modified:docs/reqcontext.rst+9 added-1 removed
129 unmodified lines
130 functions which have the chance to replace it or modify it in place.1311324. 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).137138Now what happens on errors? In production mode if an exception is not139caught, the 500 internal server handler is called. In development mode140however the exception is not further processed and bubbles up to the WSGI
43 unmodified lines
184>>> ctx.pop()185this runs after request186>>>187188Keep in mind that teardown callbacks are always executed, even if189before-request callbacks were not executed yet but an exception happened.190Certain parts of the test system might also temporarily create a request191context without calling the before-request handlers. Make sure to write192your teardown-request handlers in a way that they will never fail.193194.. _notes-on-proxies:195196Notes On Proxies197----------------
42 unmodified lines
modified:docs/testing.rst+32 added
271 unmodified lines
272is no longer available (because you are trying to use it outside of the actual request).273However, keep in mind that any :meth:`~flask.Flask.after_request` functions274are already called at this point so your database connection and275everything involved is probably already closed down.276277278Accessing and Modifying Sessions279--------------------------------280281.. versionadded:: 0.8282283Sometimes it can be very helpful to access or modify the sessions from the284test client. Generally there are two ways for this. If you just want to285ensure that a session has certain keys set to certain values you can just286keep the context around and access :data:`flask.session`::287288 with app.test_client() as c:289 rv = c.get('/')290 assert flask.session['foo'] == 42291292This however does not make it possible to also modify the session or to293access the session before a request was fired. Starting with Flask 0.8 we294provide a so called “session transaction” which simulates the appropriate295calls to open a session in the context of the test client and to modify296it. At the end of the transaction the session is stored. This works297independently of the session backend used::298299 with app.test_client() as c:300 with c.session_transaction() as sess:301 sess['a_key'] = 'a value'302303 # once this is reached the session was stored304305Note that in this case you have to use the ``sess`` object instead of the306:data:`flask.session` proxy. The object however itself will provide the307same interface.
modified:docs/upgrading.rst+7 added-1 removed
34 unmodified lines
35longer have to handle that error to avoid an internal server error showing36up for the user. If you were catching this down explicitly in the past37as `ValueError` you will need to change this.3839Due to a bug in the test client Flask 0.7 did not trigger teardown40handlers when the test client was used in a with statement. This was41since fixed but might require some changes in your testsuites if you42relied on this behavior.4344Version 0.745-----------4647In Flask 0.7 we cleaned up the code base internally a lot and did some
98 unmodified lines
146You are now encouraged to use this instead::147148 @app.teardown_request149 def after_request(exception):150 if hasattr(g, 'db'):145 g.db.close()151 g.db.close()152153On the upside this change greatly improves the internal code flow and154makes it easier to customize the dispatching and error handling. This155makes it now a lot easier to write unit tests as you can prevent closing
169 unmodified lines
modified:docs/views.rst+21 added
133 unmodified lines
134135That way you also don't have to provide the136:attr:`~flask.views.View.methods` attribute. It's automatically set based137on the methods defined in the class.138139Decorating Views140----------------141142Since the view class itself is not the view function that is added to the143routing system it does not make much sense to decorate the class itself.144Instead you either have to decorate the return value of145:meth:`~flask.views.View.as_view` by hand::146147 view = rate_limited(UserAPI.as_view('users'))148 app.add_url_rule('/users/', view_func=view)149150Starting with Flask 0.8 there is also an alternative way where you can151specify a list of decorators to apply in the class declaration::152153 class UserAPI(MethodView):154 decorators = [rate_limited]155156Due to the implicit self from the caller's perspective you cannot use157regular view decorators on the individual methods of the view however,158keep this in mind.
modified:examples/flaskr/flaskr.py+2 added-1 removed
48 unmodified lines
4950@app.teardown_request51def 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()555657@app.route('/')58def show_entries():
40 unmodified lines
modified:examples/minitwit/minitwit.py+2 added-1 removed
83 unmodified lines
8485@app.teardown_request86def 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()909192@app.route('/')93def timeline():
155 unmodified lines
added:flask/testsuite/static/index.html+1 added
1<h1>Hello World!</h1>
added:flask/testsuite/templates/nested/nested.txt+1 added
1I'm nested
added: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}} Mail
added: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
1Admin File
added:flask/testsuite/test_apps/blueprintapp/apps/admin/templates/admin/index.html+1 added
1Hello from the Admin
added:flask/testsuite/test_apps/blueprintapp/apps/admin/__init__.py+15 added
1from flask import Blueprint, render_template23admin = Blueprint('admin', __name__, url_prefix='/admin',4 template_folder='templates',5 static_folder='static')678@admin.route('/')9def index():10 return render_template('admin/index.html')111213@admin.route('/index2')14def index2():15 return render_template('./admin/index.html')
added:flask/testsuite/test_apps/blueprintapp/apps/frontend/templates/frontend/index.html+1 added
1Hello from the Frontend
added:flask/testsuite/test_apps/blueprintapp/apps/frontend/__init__.py+8 added
1from flask import Blueprint, render_template23frontend = Blueprint('frontend', __name__, template_folder='templates')456@frontend.route('/')7def 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
1from flask import Flask23app = Flask(__name__)4from blueprintapp.apps.admin import admin5from blueprintapp.apps.frontend import frontend6app.register_blueprint(admin)7app.register_blueprint(frontend)
added:flask/testsuite/test_apps/config_package_app/__init__.py+4 added
1import os2import flask3here = os.path.abspath(os.path.dirname(__file__))4app = 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
1Admin File
added:flask/testsuite/test_apps/moduleapp/apps/admin/templates/index.html+1 added
1Hello from the Admin
added:flask/testsuite/test_apps/moduleapp/apps/admin/__init__.py+14 added
1from flask import Module, render_template234admin = Module(__name__, url_prefix='/admin')567@admin.route('/')8def index():9 return render_template('admin/index.html')101112@admin.route('/index2')13def index2():14 return render_template('./admin/index.html')
added:flask/testsuite/test_apps/moduleapp/apps/frontend/templates/index.html+1 added
1Hello from the Frontend
added:flask/testsuite/test_apps/moduleapp/apps/frontend/__init__.py+9 added
1from flask import Module, render_template234frontend = Module(__name__)567@frontend.route('/')8def 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
1from flask import Flask23app = Flask(__name__)4from moduleapp.apps.admin import admin5from moduleapp.apps.frontend import frontend6app.register_module(admin)7app.register_module(frontend)
added:flask/testsuite/test_apps/subdomaintestmodule/static/hello.txt+1 added
1Hello Subdomain
added:flask/testsuite/test_apps/subdomaintestmodule/__init__.py+4 added
1from flask import Module234mod = Module(__name__, 'foo', subdomain='foo')
added:flask/testsuite/test_apps/config_module_app.py+4 added
1import os2import flask3here = os.path.abspath(os.path.dirname(__file__))4app = flask.Flask(__name__)
added:flask/testsuite/__init__.py+194 added
1# -*- coding: utf-8 -*-2"""3 flask.testsuite4 ~~~~~~~~~~~~~~~56 Tests Flask itself. The majority of Flask is already tested7 as part of Werkzeug.89 :copyright: (c) 2011 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""12import os13import sys14import flask15import warnings16import unittest17from StringIO import StringIO18from functools import update_wrapper19from contextlib import contextmanager20from werkzeug.utils import import_string, find_modules212223def 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')2728 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)404142def 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()484950def 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 )636465@contextmanager66def 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)7071 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_showwarning838485@contextmanager86def 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_stderr949596def 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)104105106class 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 """111112 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)116117 def setup(self):118 pass119120 def teardown(self):121 pass122123 def setUp(self):124 self.setup()125126 def tearDown(self):127 unittest.TestCase.tearDown(self)128 self.ensure_clean_request_context()129 self.teardown()130131 def assert_equal(self, x, y):132 return self.assertEqual(x, y)133134135class 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 """143144 def getRootSuite(self):145 return suite()146147 def loadTestsFromName(self, name, module=None):148 root = self.getRootSuite()149 if name == 'suite':150 return root151152 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)159160 if not all_tests:161 raise LookupError('could not find test case for "%s"' % name)162163 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 rv169170171def setup_path():172 add_to_path(os.path.abspath(os.path.join(173 os.path.dirname(__file__), 'test_apps')))174175176def 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 suite187188189def 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' % e
added:flask/testsuite/basic.py+1051 added
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.basic4 ~~~~~~~~~~~~~~~~~~~~~56 The basic functionality.78 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import re12import flask13import unittest14from datetime import datetime15from threading import Thread16from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning17from werkzeug.exceptions import BadRequest, NotFound18from werkzeug.http import parse_date192021class BasicFunctionalityTestCase(FlaskTestCase):2223 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, '')3132 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'])4243 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)5152 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'])5960 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.method6869 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'])8283 def test_url_mapping(self):84 app = flask.Flask(__name__)85 def index():86 return flask.request.method87 def more():88 return flask.request.method8990 app.add_url_rule('/', 'index', index)91 app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])9293 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'])106107 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'] = index120121 c = app.test_client()122 self.assert_equal(c.get('/foo/').data, 'index')123 self.assert_equal(c.get('/foo/bar').data, 'bar')124125 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 ]))132133 @app.endpoint('bar')134 def bar():135 return 'bar'136137 @app.endpoint('index')138 def index():139 return 'index'140141 c = app.test_client()142 self.assert_equal(c.get('/foo/').data, 'index')143 self.assert_equal(c.get('/foo/bar').data, 'bar')144145 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']155156 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')159160 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())173174 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())187188 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)196197 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())209210 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)231232 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')245246 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 ''255256 @app.route('/test')257 def test():258 return unicode(flask.session.permanent)259260 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)269270 rv = client.get('/test')271 self.assert_equal(rv.data, 'True')272273 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)278279 def test_flashes(self):280 app = flask.Flask(__name__)281 app.secret_key = 'testkey'282283 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'])290291 def test_extended_flashing(self):292 app = flask.Flask(__name__)293 app.secret_key = 'testkey'294295 @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 ''301302 @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>'))315316 c = app.test_client()317 c.get('/')318 c.get('/test')319320 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')340341 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)355356 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)371372 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)404405 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])434435 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)456457 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')468469 def test_user_error_handling(self):470 class MyException(Exception):471 pass472473 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()481482 c = app.test_client()483 self.assert_equal(c.get('/').data, '42')484485 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)493494 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')502503 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)510511 c = app.test_client()512 try:513 c.get('/fail')514 except NotFound, e:515 pass516 else:517 self.fail('Expected exception')518519 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'].filename526527 # 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')538539 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)545546 ctx = app.test_request_context()547 ctx.push()548 self.assert_equal(buffer, [])549 ctx.pop()550 self.assert_equal(buffer, [None])551552 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')571572 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')579580 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')584585 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')589590 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')599600 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')615616 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')624625 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")637638 def test_request_locals(self):639 self.assert_equal(repr(flask.g), '<LocalProxy unbound>')640 self.assertFalse(flask.g)641642 def test_proper_test_request_context(self):643 app = flask.Flask(__name__)644 app.config.update(645 SERVER_NAME='localhost.localdomain:5000'646 )647648 @app.route('/')649 def index():650 return None651652 @app.route('/', subdomain='foo')653 def sub():654 return None655656 with app.test_request_context('/'):657 self.assert_equal(flask.url_for('index', _external=True), 'http://localhost.localdomain:5000/')658659 with app.test_request_context('/'):660 self.assert_equal(flask.url_for('sub', _external=True), 'http://foo.localhost.localdomain:5000/')661662 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')")670671 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 )679680 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 )688689 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'697698 @app.route('/', subdomain='foo')699 def subdomain():700 return 'Foo SubDomain'701702 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 )709710 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 )717718 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 )725726 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 )734735 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')")743744 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')")751752 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 )759760 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)777778 # 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()786787 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'801802 c = app.test_client()803 rv = c.post('/accept', data={'myfile': 'foo' * 100})804 self.assert_equal(rv.data, '42')805806 def test_url_processors(self):807 app = flask.Flask(__name__)808809 @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)814815 @app.url_value_preprocessor816 def pull_lang_code(endpoint, values):817 flask.g.lang_code = values.pop('lang_code', None)818819 @app.route('/<lang_code>/')820 def index():821 return flask.url_for('about')822823 @app.route('/<lang_code>/about')824 def about():825 return flask.url_for('something_else')826827 @app.route('/foo')828 def something_else():829 return flask.url_for('about', lang_code='en')830831 c = app.test_client()832833 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')836837 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')853854 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)860861 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)873874 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')889890 rv = c.get('/foo', data={}, follow_redirects=True)891 self.assert_equal(rv.data, 'success')892893 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')897898 def test_route_decorator_custom_endpoint(self):899 app = flask.Flask(__name__)900 app.debug = True901902 @app.route('/foo/')903 def foo():904 return flask.request.endpoint905906 @app.route('/bar/', endpoint='bar')907 def for_bar():908 return flask.request.endpoint909910 @app.route('/bar/123', endpoint='123')911 def for_bar_foo():912 return flask.request.endpoint913914 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'918919 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')923924925class ContextTestCase(FlaskTestCase):926927 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.url935936 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)941942 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()953954 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']959960 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')970971972class SubdomainTestCase(FlaskTestCase):973974 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'983984 c = app.test_client()985 rv = c.get('/', 'http://localhost/')986 self.assert_equal(rv.data, 'normal index')987988 rv = c.get('/', 'http://test.localhost/')989 self.assert_equal(rv.data, 'test index')990991 @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')10001001 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' % user10071008 c = app.test_client()1009 rv = c.get('/', 'http://mitsuhiko.localhost/')1010 self.assert_equal(rv.data, 'index for mitsuhiko')10111012 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' % user10181019 c = app.test_client()1020 rv = c.get('/', 'http://mitsuhiko.localhost:3000/')1021 self.assert_equal(rv.data, 'index for mitsuhiko')10221023 @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'10281029 @mod.route('/test')1030 def test():1031 return 'Test'10321033 @mod.route('/outside', subdomain='xtesting')1034 def bar():1035 return 'Outside'10361037 app.register_module(mod)10381039 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')104410451046def 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 suite
added:flask/testsuite/blueprints.py+509 added
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.blueprints4 ~~~~~~~~~~~~~~~~~~~~~~~~~~56 Blueprints (and currently modules)78 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import flask12import unittest13import warnings14from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning15from werkzeug.exceptions import NotFound16from jinja2 import TemplateNotFound171819# import moduleapp here because it uses deprecated features and we don't20# want to see the warnings21warnings.simplefilter('ignore', DeprecationWarning)22from moduleapp import app as moduleapp23warnings.simplefilter('default', DeprecationWarning)242526class ModuleTestCase(FlaskTestCase):2728 @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')5051 @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'), '/')6364 @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()9192 self.assert_equal(c.get('/').data, 'the index')93 self.assert_equal(catched, ['before-app', 'after-app'])94 del catched[:]9596 self.assert_equal(c.get('/admin/').data, 'the admin')97 self.assert_equal(catched, ['before-app', 'before-admin',98 'after-admin', 'after-app'])99100 @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')123124 @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')133134 @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)158159 def test_templates_and_static(self):160 app = moduleapp161 app.testing = True162 c = app.test_client()163164 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 */')174175 with app.test_request_context():176 self.assert_equal(flask.url_for('admin.static', filename='test.txt'),177 '/admin/static/test.txt')178179 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')186187 with flask.Flask(__name__).test_request_context():188 self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested')189190 def test_safe_access(self):191 app = moduleapp192193 with app.test_request_context():194 f = app.view_functions['admin.static']195196 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')208209 # 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_path223224 @emits_module_deprecation_warning225 def test_endpoint_decorator(self):226 from werkzeug.routing import Submount, Rule227 from flask import Module228229 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__)236237 @module.endpoint('bar')238 def bar():239 return 'bar'240241 @module.endpoint('index')242 def index():243 return 'index'244245 app.register_module(module)246247 c = app.test_client()248 self.assert_equal(c.get('/foo/').data, 'index')249 self.assert_equal(c.get('/foo/bar').data, 'bar')250251252class BlueprintTestCase(FlaskTestCase):253254 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__)258259 @frontend.errorhandler(403)260 def frontend_forbidden(e):261 return 'frontend says no', 403262263 @frontend.route('/frontend-no')264 def frontend_no():265 flask.abort(403)266267 @backend.errorhandler(403)268 def backend_forbidden(e):269 return 'backend says no', 403270271 @backend.route('/backend-no')272 def backend_no():273 flask.abort(403)274275 @sideend.route('/what-is-a-sideend')276 def sideend_no():277 flask.abort(403)278279 app = flask.Flask(__name__)280 app.register_blueprint(frontend)281 app.register_blueprint(backend)282 app.register_blueprint(sideend)283284 @app.errorhandler(403)285 def app_forbidden(e):286 return 'application itself says no', 403287288 c = app.test_client()289290 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')293294 def test_blueprint_url_definitions(self):295 bp = flask.Blueprint('test', __name__)296297 @bp.route('/foo', defaults={'baz': 42})298 def foo(bar, baz):299 return '%s/%d' % (bar, baz)300301 @bp.route('/bar')302 def bar(bar):303 return unicode(bar)304305 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})308309 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')314315 def test_blueprint_url_processors(self):316 bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')317318 @bp.url_defaults319 def add_language_code(endpoint, values):320 values.setdefault('lang_code', flask.g.lang_code)321322 @bp.url_value_preprocessor323 def pull_lang_code(endpoint, values):324 flask.g.lang_code = values.pop('lang_code')325326 @bp.route('/')327 def index():328 return flask.url_for('.about')329330 @bp.route('/about')331 def about():332 return flask.url_for('.index')333334 app = flask.Flask(__name__)335 app.register_blueprint(bp)336337 c = app.test_client()338339 self.assert_equal(c.get('/de/').data, '/de/about')340 self.assert_equal(c.get('/de/about').data, '/de/')341342 def test_templates_and_static(self):343 from blueprintapp import app344 c = app.test_client()345346 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 */')356357 with app.test_request_context():358 self.assert_equal(flask.url_for('admin.static', filename='test.txt'),359 '/admin/static/test.txt')360361 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')368369 with flask.Flask(__name__).test_request_context():370 self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested')371372 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'])377378 def test_dotted_names(self):379 frontend = flask.Blueprint('myapp.frontend', __name__)380 backend = flask.Blueprint('myapp.backend', __name__)381382 @frontend.route('/fe')383 def frontend_index():384 return flask.url_for('myapp.backend.backend_index')385386 @frontend.route('/fe2')387 def frontend_page2():388 return flask.url_for('.frontend_index')389390 @backend.route('/be')391 def backend_index():392 return flask.url_for('myapp.frontend.frontend_index')393394 app = flask.Flask(__name__)395 app.register_blueprint(frontend)396 app.register_blueprint(backend)397398 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')402403 def test_empty_url_defaults(self):404 bp = flask.Blueprint('bp', __name__)405406 @bp.route('/', defaults={'page': 1})407 @bp.route('/page/<int:page>')408 def something(page):409 return str(page)410411 app = flask.Flask(__name__)412 app.register_blueprint(bp)413414 c = app.test_client()415 self.assert_equal(c.get('/').data, '1')416 self.assert_equal(c.get('/page/2').data, '2')417418 def test_route_decorator_custom_endpoint(self):419420 bp = flask.Blueprint('bp', __name__)421422 @bp.route('/foo')423 def foo():424 return flask.request.endpoint425426 @bp.route('/bar', endpoint='bar')427 def foo_bar():428 return flask.request.endpoint429430 @bp.route('/bar/123', endpoint='123')431 def foo_bar_foo():432 return flask.request.endpoint433434 @bp.route('/bar/foo')435 def bar_foo():436 return flask.request.endpoint437438 app = flask.Flask(__name__)439 app.register_blueprint(bp, url_prefix='/py')440441 @app.route('/')442 def index():443 return flask.request.endpoint444445 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')451452 def test_route_decorator_custom_endpoint_with_dots(self):453 bp = flask.Blueprint('bp', __name__)454455 @bp.route('/foo')456 def foo():457 return flask.request.endpoint458459 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')467468 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')476477 def foo_foo_foo():478 pass479480 self.assertRaises(481 AssertionError,482 lambda: bp.add_url_rule(483 '/bar/123', endpoint='bar.123', view_func=foo_foo_foo484 )485 )486487 self.assertRaises(488 AssertionError,489 bp.route('/bar/123', endpoint='bar.123'),490 lambda: None491 )492493 app = flask.Flask(__name__)494 app.register_blueprint(bp, url_prefix='/py')495496 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 == 404503504505def suite():506 suite = unittest.TestSuite()507 suite.addTest(unittest.makeSuite(BlueprintTestCase))508 suite.addTest(unittest.makeSuite(ModuleTestCase))509 return suite
added:flask/testsuite/config.py+177 added
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.config4 ~~~~~~~~~~~~~~~~~~~~~~56 Configuration and instances.78 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import os12import sys13import flask14import unittest15from flask.testsuite import FlaskTestCase161718# config keys used for the ConfigTestCase19TEST_KEY = 'foo'20SECRET_KEY = 'devkey'212223class ConfigTestCase(FlaskTestCase):2425 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)2930 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)3435 def test_config_from_object(self):36 app = flask.Flask(__name__)37 app.config.from_object(__name__)38 self.common_object_test(app)3940 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)4849 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))6162 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 = env6768 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))808182class InstanceTestCase(FlaskTestCase):8384 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')9293 app = flask.Flask(__name__, instance_path=here)94 self.assert_equal(app.instance_path, here)9596 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'))100101 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'))105106 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'] = None120121 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'] = None137138 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'] = None154155 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'] = None171172173def suite():174 suite = unittest.TestSuite()175 suite.addTest(unittest.makeSuite(ConfigTestCase))176 suite.addTest(unittest.makeSuite(InstanceTestCase))177 return suite
added:flask/testsuite/deprecations.py+38 added
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.deprecations4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~56 Tests deprecation support.78 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import flask12import unittest13from flask.testsuite import FlaskTestCase, catch_warnings141516class DeprecationsTestCase(FlaskTestCase):1718 def test_init_jinja_globals(self):19 class MyFlask(flask.Flask):20 def init_jinja_globals(self):21 self.jinja_env.globals['foo'] = '42'2223 with catch_warnings() as log:24 app = MyFlask(__name__)25 @app.route('/')26 def foo():27 return app.jinja_env.globals['foo']2829 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']))333435def suite():36 suite = unittest.TestSuite()37 suite.addTest(unittest.makeSuite(DeprecationsTestCase))38 return suite
added:flask/testsuite/examples.py+38 added
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.examples4 ~~~~~~~~~~~~~~~~~~~~~~~~56 Tests the examples.78 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import os12import unittest13from flask.testsuite import add_to_path141516def 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'))212223def 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 suite
added:flask/testsuite/helpers.py+295 added
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.helpers4 ~~~~~~~~~~~~~~~~~~~~~~~56 Various helpers.78 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import os12import flask13import unittest14from logging import StreamHandler15from StringIO import StringIO16from flask.testsuite import FlaskTestCase, catch_warnings, catch_stderr17from werkzeug.http import parse_options_header181920def has_encoding(name):21 try:22 import codecs23 codecs.lookup(name)24 return True25 except LookupError:26 return False272829class JSONTestCase(FlaskTestCase):3031 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)3940 def test_json_body_encoding(self):41 app = flask.Flask(__name__)42 app.testing = True43 @app.route('/')44 def index():45 return flask.request.json4647 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'))5152 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)6667 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')7677 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>"')8586 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'9293 @app.route('/')94 def index():95 return flask.request.args['foo']9697 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'))100101 if not has_encoding('euc-kr'):102 test_modified_url_encoding = None103104105class SendfileTestCase(FlaskTestCase):106107 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())115116 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')126127 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)138139 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)150151 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)167168 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)176177 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)187188 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')194195 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')203204205class LoggingTestCase(FlaskTestCase):206207 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)214215 def test_debug_log(self):216 app = flask.Flask(__name__)217 app.debug = True218219 @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 ''224225 @app.route('/exc')226 def exc():227 1/0228229 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)237238 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')245246 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))251252 @app.route('/')253 def index():254 1/0255256 rv = app.test_client().get('/')257 self.assert_equal(rv.status_code, 500)258 self.assert_('Internal Server Error' in rv.data)259260 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)265266 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')287288289def 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 suite
added:flask/testsuite/signals.py+103 added
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.signals4 ~~~~~~~~~~~~~~~~~~~~~~~56 Signalling.78 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import flask12import unittest13from flask.testsuite import FlaskTestCase141516class SignalsTestCase(FlaskTestCase):1718 def test_template_rendered(self):19 app = flask.Flask(__name__)2021 @app.route('/')22 def index():23 return flask.render_template('simple_template.html', whiskey=42)2425 recorded = []26 def record(sender, template, context):27 recorded.append((template, context))2829 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)3839 def test_request_signals(self):40 app = flask.Flask(__name__)41 calls = []4243 def before_request_signal(sender):44 calls.append('before-signal')4546 def after_request_signal(sender, response):47 self.assert_equal(response.data, 'stuff')48 calls.append('after-signal')4950 @app.before_request51 def before_request_handler():52 calls.append('before-handler')5354 @app.after_request55 def after_request_handler(response):56 calls.append('after-handler')57 response.data = 'stuff'58 return response5960 @app.route('/')61 def index():62 calls.append('handler')63 return 'ignored anyway'6465 flask.request_started.connect(before_request_signal, app)66 flask.request_finished.connect(after_request_signal, app)6768 try:69 rv = app.test_client().get('/')70 self.assert_equal(rv.data, 'stuff')7172 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)7879 def test_request_exception_signal(self):80 app = flask.Flask(__name__)81 recorded = []8283 @app.route('/')84 def index():85 1/08687 def record(sender, exception):88 recorded.append(exception)8990 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)979899def suite():100 suite = unittest.TestSuite()101 if flask.signals_available:102 suite.addTest(unittest.makeSuite(SignalsTestCase))103 return suite
added:flask/testsuite/templating.py+141 added
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.templating4 ~~~~~~~~~~~~~~~~~~~~~~~~~~56 Template functionality78 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import flask12import unittest13from flask.testsuite import FlaskTestCase141516class TemplatingTestCase(FlaskTestCase):1718 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')2829 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')3637 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'])5253 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 '&lt;p&gt;Hello World!',63 '<p>Hello World!',64 '<p>Hello World!',65 '<p>Hello World!',66 '&lt;p&gt;Hello World!',67 '<p>Hello World!'68 ])6970 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')7778 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!')8384 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')9293 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')101102 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')112113 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')123124 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!')136137138def suite():139 suite = unittest.TestSuite()140 suite.addTest(unittest.makeSuite(TemplatingTestCase))141 return suite
added:flask/testsuite/testing.py+165 added
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.testing4 ~~~~~~~~~~~~~~~~~~~~~~~56 Test client and more.78 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import flask12import unittest13from flask.testsuite import FlaskTestCase141516class TestToolsTestCase(FlaskTestCase):1718 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.url2627 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/')3233 def test_environ_defaults(self):34 app = flask.Flask(__name__)35 app.testing = True36 @app.route('/')37 def index():38 return flask.request.url3940 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/')4546 def test_session_transactions(self):47 app = flask.Flask(__name__)48 app.testing = True49 app.secret_key = 'testing'5051 @app.route('/')52 def index():53 return unicode(flask.session['foo'])5455 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]')6263 def test_session_transactions_no_null_sessions(self):64 app = flask.Flask(__name__)65 app.testing = True6667 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')7576 def test_session_transactions_keep_context(self):77 app = flask.Flask(__name__)78 app.testing = True79 app.secret_key = 'testing'8081 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())8687 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')9899 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!'105106 @app.route('/other')107 def other():108 1/0109110 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)115116 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 = 23121122 try:123 flask.g.value124 except (AttributeError, RuntimeError):125 pass126 else:127 raise AssertionError('some kind of exception expected')128129 def test_reuse_client(self):130 app = flask.Flask(__name__)131 c = app.test_client()132133 with c:134 self.assert_equal(c.get('/').status_code, 404)135136 with c:137 self.assert_equal(c.get('/').status_code, 404)138139 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)145146 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])151152 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])160161162def suite():163 suite = unittest.TestSuite()164 suite.addTest(unittest.makeSuite(TestToolsTestCase))165 return suite
added:flask/testsuite/views.py+117 added
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.views4 ~~~~~~~~~~~~~~~~~~~~~56 Pluggable views.78 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import flask12import flask.views13import unittest14from flask.testsuite import FlaskTestCase15from werkzeug.http import parse_set_header161718class ViewTestCase(FlaskTestCase):1920 def common_test(self, app):21 c = app.test_client()2223 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'])2829 def test_basic_view(self):30 app = flask.Flask(__name__)3132 class Index(flask.views.View):33 methods = ['GET', 'POST']34 def dispatch_request(self):35 return flask.request.method3637 app.add_url_rule('/', view_func=Index.as_view('index'))38 self.common_test(app)3940 def test_method_based_view(self):41 app = flask.Flask(__name__)4243 class Index(flask.views.MethodView):44 def get(self):45 return 'GET'46 def post(self):47 return 'POST'4849 app.add_url_rule('/', view_func=Index.as_view('index'))5051 self.common_test(app)5253 def test_view_patching(self):54 app = flask.Flask(__name__)5556 class Index(flask.views.MethodView):57 def get(self):58 1/059 def post(self):60 1/06162 class Other(Index):63 def get(self):64 return 'GET'65 def post(self):66 return 'POST'6768 view = Index.as_view('index')69 view.view_class = Other70 app.add_url_rule('/', view_func=view)71 self.common_test(app)7273 def test_view_inheritance(self):74 app = flask.Flask(__name__)7576 class Index(flask.views.MethodView):77 def get(self):78 return 'GET'79 def post(self):80 return 'POST'8182 class BetterIndex(Index):83 def delete(self):84 return 'DELETE'8586 app.add_url_rule('/', view_func=BetterIndex.as_view('index'))87 c = app.test_client()8889 meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])90 self.assert_equal(sorted(meths), ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST'])9192 def test_view_decorators(self):93 app = flask.Flask(__name__)9495 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_function101102 class Index(flask.views.View):103 decorators = [add_x_parachute]104 def dispatch_request(self):105 return 'Awesome'106107 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')112113114def suite():115 suite = unittest.TestSuite()116 suite.addTest(unittest.makeSuite(ViewTestCase))117 return suite
modified:flask/app.py+42 added-31 removed
229 unmodified lines
230 '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 lines
709 with app.test_client() as c:710 rv = c.get('/?vodka=42')711 assert request.args['vodka'] == '42'712713 See :class:`~flask.testing.FlaskClient` for more information.714715 .. versionchanged:: 0.4716 added support for `with` block usage for the client.717718 .. versionadded:: 0.7
504 unmodified lines
1223 raise exc_type, exc_value, tb1224 else:1225 raise e12261220 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)12311232 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`.12371238 .. versionadded:: 0.81239 """1240 self.logger.error('Exception on %s [%s]' % (1241 request.path,1242 request.method1243 ), exc_info=exc_info)12441245 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 raising
73 unmodified lines
1322 behaviour of `OPTIONS` responses.13231324 .. 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 lines
14041405 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.blueprint14091410 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 lines
1454 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 lines
1499 """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()15091494 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))14981510 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 lines
modified:flask/ctx.py+1 added-1 removed
89 unmodified lines
90 self.session = None9192 self.match_request()9394 # 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 that
48 unmodified lines
modified:flask/debughelpers.py+2 added-1 removed
52 unmodified lines
53 'without one.')5455 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'))6162
17 unmodified lines
modified:flask/helpers.py+10 added
143 unmodified lines
144 code::145146 response = make_response(render_template('not_found.html'), 404)147148 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::151152 response = make_response(view_function())153 response.headers['X-Parachutes'] = 'parachutes are cool'154155 Internally this function does the following things:156157 - if no arguments are passed, it creates a new response argument158 - if one argument is passed, :meth:`flask.Flask.make_response`
324 unmodified lines
483 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()490491492def find_package(import_name):
7 unmodified lines
500 __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 lines
modified:flask/sessions.py+31 added-3 removed
121 unmodified lines
122 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]131132 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 '/'140141 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']147148 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']153154 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 session
34 unmodified lines
192193 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 lines
33 '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 _fail3940# the namespace for code signals. If you are not flask code, do41# not put signals in here. Create your own namespace instead.
10 unmodified lines
modified:flask/testing.py+78 added-22 removed
8 unmodified lines
9 :copyright: (c) 2010 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213from contextlib import contextmanager14from werkzeug.test import Client, EnvironBuilder15from flask import _request_ctx_stack161718def 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)272829class 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`.3435 Basic usage is outlined in the :ref:`testing` chapter.36 """3738 preserve_context = context_preserved = False3940 @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.4647 with client.session_transaction() as session:48 session['value'] = 424950 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')6869 # 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()8182 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)8788 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_context9293 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)9737 builder = EnvironBuilder(*args, **kwargs)3839 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 lines
104 finally:105 self.context_preserved = _request_ctx_stack.top is not old106107 def __enter__(self):108 if self.preserve_context:109 raise RuntimeError('Cannot nest client invocations')110 self.preserve_context = True111 return self112113 def __exit__(self, exc_type, exc_value, tb):114 self.preserve_context = False115 self._pop_reqctx_if_necessary()116117 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 = False
modified:flask/views.py+35 added
28 unmodified lines
29 def dispatch_request(self, name):30 return 'Hello %s!' % name3132 app.add_url_rule('/hello/<name>', view_func=MyView.as_view('myview'))3334 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::3738 class SecretView(View):39 methods = ['GET']40 decorators = [superuser_required]4142 def dispatch_request(self):43 ...4445 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 """5051 #: A for which methods this pluggable view can handle.52 methods = None5354 #: 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 = []6465 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 lines
81 """82 def view(*args, **kwargs):83 self = view.view_class(*class_args, **class_kwargs)84 return self.dispatch_request(*args, **kwargs)8586 if cls.decorators:87 view.__name__ = name88 view.__module__ = cls.__module__89 for decorator in cls.decorators:90 view = decorator(view)9192 # 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 else
52 unmodified lines
added:scripts/flaskext_test.py+311 added
1# -*- coding: utf-8 -*-2"""3 Flask Extension Tests4 ~~~~~~~~~~~~~~~~~~~~~56 Tests the Flask extensions.78 :copyright: (c) 2010 by Ali Afshar.9 :license: BSD, see LICENSE for more details.10"""1112from __future__ import with_statement1314import os15import sys16import shutil17import urllib218import tempfile19import subprocess20import argparse2122from flask import json2324from setuptools.package_index import PackageIndex25from setuptools.archive_util import unpack_archive2627flask_svc_url = 'http://flask.pocoo.org/extensions/'282930# 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.33if sys.platform == 'darwin':34 _tempdir = '/private/tmp'35else:36 _tempdir = tempfile.gettempdir()37tdir = _tempdir + '/flaskext-test'38flaskdir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))394041# virtualenv hack *cough*42os.environ['PYTHONDONTWRITEBYTECODE'] = ''434445RESULT_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'''114115116def log(msg, *args):117 print '[EXTTEST]', msg % args118119120class TestResult(object):121122 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 == 0128129 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')141142 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] = ''150151152def create_tdir():153 try:154 shutil.rmtree(tdir)155 except Exception:156 pass157 os.mkdir(tdir)158159160def 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])166167168def get_test_command(checkout_dir):169 if os.path.isfile(checkout_dir + '/Makefile'):170 return 'make test'171 return 'python setup.py test'172173174def 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 ext180181182def 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)187188 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 path196197198tox_template = """[tox]199envlist=%(env)s200201[testenv]202deps=203 %(deps)s204 distribute205 py206commands=bash flaskext-runtest.sh {envlogdir}/test.log207downloadcache=%(cache)s208"""209210211def 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_path221222223def iter_extensions(only_approved=True):224 for ext in fetch_extensions_list():225 if ext['approved'] or not only_approved:226 yield ext['name']227228229def test_extension(name, interpreters, flask_dep):230 checkout_path = checkout_extension(name)231 log('Running tests with tox in %s', checkout_path)232233 # 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()244245 # if there is a tox.ini, remove it, it will cause troubles246 # for us. Remove it if present, we are running tox ourselves247 # afterall.248249 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)252253254def 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 results270271272def 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 filename281282283def 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()294295 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)301302 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', filename308309310if __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
1Admin File
deleted:tests/blueprintapp/apps/admin/templates/admin/index.html-1 removed
1Hello from the Admin
deleted:tests/blueprintapp/apps/admin/__init__.py-15 removed
1from flask import Blueprint, render_template23admin = Blueprint('admin', __name__, url_prefix='/admin',4 template_folder='templates',5 static_folder='static')678@admin.route('/')9def index():10 return render_template('admin/index.html')111213@admin.route('/index2')14def index2():15 return render_template('./admin/index.html')
deleted:tests/blueprintapp/apps/frontend/templates/frontend/index.html-1 removed
1Hello from the Frontend
deleted:tests/blueprintapp/apps/frontend/__init__.py-8 removed
1from flask import Blueprint, render_template23frontend = Blueprint('frontend', __name__, template_folder='templates')456@frontend.route('/')7def index():8 return render_template('frontend/index.html')
deleted:tests/blueprintapp/apps/__init__.py
deleted:tests/blueprintapp/__init__.py-7 removed
1from flask import Flask23app = Flask(__name__)4from blueprintapp.apps.admin import admin5from blueprintapp.apps.frontend import frontend6app.register_blueprint(admin)7app.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
1Admin File
deleted:tests/moduleapp/apps/admin/templates/index.html-1 removed
1Hello from the Admin
deleted:tests/moduleapp/apps/admin/__init__.py-14 removed
1from flask import Module, render_template234admin = Module(__name__, url_prefix='/admin')567@admin.route('/')8def index():9 return render_template('admin/index.html')101112@admin.route('/index2')13def index2():14 return render_template('./admin/index.html')
deleted:tests/moduleapp/apps/frontend/templates/index.html-1 removed
1Hello from the Frontend
deleted:tests/moduleapp/apps/frontend/__init__.py-9 removed
1from flask import Module, render_template234frontend = Module(__name__)567@frontend.route('/')8def index():9 return render_template('frontend/index.html')
deleted:tests/moduleapp/apps/__init__.py
deleted:tests/moduleapp/__init__.py-7 removed
1from flask import Flask23app = Flask(__name__)4from moduleapp.apps.admin import admin5from moduleapp.apps.frontend import frontend6app.register_module(admin)7app.register_module(frontend)
deleted:tests/static/index.html-1 removed
1<h1>Hello World!</h1>
deleted:tests/subdomaintestmodule/static/hello.txt-1 removed
1Hello Subdomain
deleted:tests/subdomaintestmodule/__init__.py-4 removed
1from flask import Module234mod = Module(__name__, 'foo', subdomain='foo')
deleted:tests/templates/nested/nested.txt-1 removed
1I'm nested
deleted: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}} Mail
deleted: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 ~~~~~~~~~~~56 Tests Flask itself. The majority of Flask is already tested7 as part of Werkzeug.89 :copyright: (c) 2010 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""12from __future__ import with_statement13import os14import re15import sys16import flask17import flask.views18import unittest19import warnings20from threading import Thread21from logging import StreamHandler22from contextlib import contextmanager23from functools import update_wrapper24from datetime import datetime25from werkzeug import parse_date, parse_options_header26from werkzeug.exceptions import NotFound, BadRequest27from werkzeug.http import parse_set_header28from jinja2 import TemplateNotFound29from cStringIO import StringIO3031example_path = os.path.join(os.path.dirname(__file__), '..', 'examples')32sys.path.append(os.path.join(example_path, 'flaskr'))33sys.path.append(os.path.join(example_path, 'minitwit'))343536def has_encoding(name):37 try:38 import codecs39 codecs.lookup(name)40 return True41 except LookupError:42 return False434445# config keys used for the ConfigTestCase46TEST_KEY = 'foo'47SECRET_KEY = 'devkey'484950# import moduleapp here because it uses deprecated features and we don't51# want to see the warnings52warnings.simplefilter('ignore', DeprecationWarning)53from moduleapp import app as moduleapp54warnings.simplefilter('default', DeprecationWarning)555657@contextmanager58def 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)6263 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_showwarning757677@contextmanager78def 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_stderr868788def 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)969798class ContextTestCase(unittest.TestCase):99100 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.url108109 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 None114115 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()126127 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']132133 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'143144 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!'150151 @app.route('/other')152 def other():153 1/0154155 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 == 200160161 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 = 23166167 try:168 flask.g.value169 except (AttributeError, RuntimeError):170 pass171 else:172 raise AssertionError('some kind of exception expected')173174175class BasicFunctionalityTestCase(unittest.TestCase):176177 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 == ''185186 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']196197 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 == 405205206 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']213214 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.method222223 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']236237 def test_url_mapping(self):238 app = flask.Flask(__name__)239 def index():240 return flask.request.method241 def more():242 return flask.request.method243244 app.add_url_rule('/', 'index', index)245 app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])246247 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']260261 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'] = index274275 c = app.test_client()276 assert c.get('/foo/').data == 'index'277 assert c.get('/foo/bar').data == 'bar'278279 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 ]))286287 @app.endpoint('bar')288 def bar():289 return 'bar'290291 @app.endpoint('index')292 def index():293 return 'index'294295 c = app.test_client()296 assert c.get('/foo/').data == 'index'297 assert c.get('/foo/bar').data == 'bar'298299 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']309310 c = app.test_client()311 assert c.post('/set', data={'value': '42'}).data == 'value set'312 assert c.get('/get').data == '42'313314 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()327328 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()341342 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')355356 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 ''365366 @app.route('/test')367 def test():368 return unicode(flask.session.permanent)369370 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.day379380 rv = client.get('/test')381 assert rv.data == 'True'382383 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 None388389 def test_flashes(self):390 app = flask.Flask(__name__)391 app.secret_key = 'testkey'392393 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']400401 def test_extended_flashing(self):402 app = flask.Flask(__name__)403 app.secret_key = 'testkey'404405 @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 ''411412 @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>')425426 c = app.test_client()427 c.get('/')428 c.get('/test')429430 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'450451 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) == 1465466 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) == 1481482 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) == 2514515 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]544545 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.data566567 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'578579 def test_user_error_handling(self):580 class MyException(Exception):581 pass582583 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()591592 c = app.test_client()593 assert c.get('/').data == '42'594595 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 == 400603604 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')612613 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)620621 c = app.test_client()622 try:623 c.get('/fail')624 except NotFound, e:625 pass626 else:627 self.fail('Expected exception')628629 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'].filename636637 # 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')648649 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)655656 ctx = app.test_request_context()657 ctx.push()658 assert buffer == []659 ctx.pop()660 assert buffer == [None]661662 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'681682 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'689690 rv = flask.make_response('Awesome')691 assert rv.status_code == 200692 assert rv.data == 'Awesome'693 assert rv.mimetype == 'text/html'694695 rv = flask.make_response('W00t', 404)696 assert rv.status_code == 404697 assert rv.data == 'W00t'698 assert rv.mimetype == 'text/html'699700 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'709710 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'725726 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'734735 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"747748 def test_request_locals(self):749 self.assertEqual(repr(flask.g), '<LocalProxy unbound>')750 self.assertFalse(flask.g)751752 def test_proper_test_request_context(self):753 app = flask.Flask(__name__)754 app.config.update(755 SERVER_NAME='localhost.localdomain:5000'756 )757758 @app.route('/')759 def index():760 return None761762 @app.route('/', subdomain='foo')763 def sub():764 return None765766 with app.test_request_context('/'):767 assert flask.url_for('index', _external=True) == 'http://localhost.localdomain:5000/'768769 with app.test_request_context('/'):770 assert flask.url_for('sub', _external=True) == 'http://foo.localhost.localdomain:5000/'771772 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)780781 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 )789790 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 )798799 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'807808 @app.route('/', subdomain='foo')809 def subdomain():810 return 'Foo SubDomain'811812 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 )819820 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 )827828 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 )835836 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 )844845 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)853854 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)861862 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 )869870 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 == 500887888 # 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()896897 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'911912 c = app.test_client()913 rv = c.post('/accept', data={'myfile': 'foo' * 100})914 assert rv.data == '42'915916 def test_url_processors(self):917 app = flask.Flask(__name__)918919 @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)924925 @app.url_value_preprocessor926 def pull_lang_code(endpoint, values):927 flask.g.lang_code = values.pop('lang_code', None)928929 @app.route('/<lang_code>/')930 def index():931 return flask.url_for('about')932933 @app.route('/<lang_code>/about')934 def about():935 return flask.url_for('something_else')936937 @app.route('/foo')938 def something_else():939 return flask.url_for('about', lang_code='en')940941 c = app.test_client()942943 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')946947 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')963964 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)970971 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)983984 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')9991000 rv = c.get('/foo', data={}, follow_redirects=True)1001 self.assertEqual(rv.data, 'success')10021003 app.debug = False1004 with app.test_client() as c:1005 rv = c.post('/foo', data={}, follow_redirects=True)1006 self.assertEqual(rv.data, 'success')10071008 def test_route_decorator_custom_endpoint(self):1009 app = flask.Flask(__name__)1010 app.debug = True10111012 @app.route('/foo/')1013 def foo():1014 return flask.request.endpoint10151016 @app.route('/bar/', endpoint='bar')1017 def for_bar():1018 return flask.request.endpoint10191020 @app.route('/bar/123', endpoint='123')1021 def for_bar_foo():1022 return flask.request.endpoint10231024 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'10281029 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')103310341035class InstanceTestCase(unittest.TestCase):10361037 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')10451046 app = flask.Flask(__name__, instance_path=here)1047 self.assertEqual(app.instance_path, here)10481049 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'))10531054 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'))10581059 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'] = None10731074 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'] = None10901091 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'] = None11071108 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'] = None112411251126class JSONTestCase(unittest.TestCase):11271128 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)11361137 def test_json_body_encoding(self):1138 app = flask.Flask(__name__)1139 app.testing = True1140 @app.route('/')1141 def index():1142 return flask.request.json11431144 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')11481149 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) == d11631164 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'11731174 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>"'11821183 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'11891190 @app.route('/')1191 def index():1192 return flask.request.args['foo']11931194 rv = app.test_client().get(u'/?foo=정상처리'.encode('euc-kr'))1195 assert rv.status_code == 2001196 assert rv.data == u'정상처리'.encode('utf-8')11971198 if not has_encoding('euc-kr'):1199 test_modified_url_encoding = None120012011202class TemplatingTestCase(unittest.TestCase):12031204 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'12141215 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'12221223 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']12381239 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 '&lt;p&gt;Hello World!',1249 '<p>Hello World!',1250 '<p>Hello World!',1251 '<p>Hello World!',1252 '&lt;p&gt;Hello World!',1253 '<p>Hello World!'1254 ]12551256 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'12631264 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!'12691270 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'12781279 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'12871288 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'12981299 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'13091310 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!'132213231324class ModuleTestCase(unittest.TestCase):13251326 @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'13481349 @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') == '/'13611362 @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()13891390 assert c.get('/').data == 'the index'1391 assert catched == ['before-app', 'after-app']1392 del catched[:]13931394 assert c.get('/admin/').data == 'the admin'1395 assert catched == ['before-app', 'before-admin',1396 'after-admin', 'after-app']13971398 @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'14211422 @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'14311432 @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.data14561457 def test_templates_and_static(self):1458 app = moduleapp1459 app.testing = True1460 c = app.test_client()14611462 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 */'14721473 with app.test_request_context():1474 assert flask.url_for('admin.static', filename='test.txt') \1475 == '/admin/static/test.txt'14761477 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'14841485 with flask.Flask(__name__).test_request_context():1486 assert flask.render_template('nested/nested.txt') == 'I\'m nested'14871488 def test_safe_access(self):1489 app = moduleapp14901491 with app.test_request_context():1492 f = app.view_functions['admin.static']14931494 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'15061507 # 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_path15211522 @emits_module_deprecation_warning1523 def test_endpoint_decorator(self):1524 from werkzeug.routing import Submount, Rule1525 from flask import Module15261527 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__)15341535 @module.endpoint('bar')1536 def bar():1537 return 'bar'15381539 @module.endpoint('index')1540 def index():1541 return 'index'15421543 app.register_module(module)15441545 c = app.test_client()1546 assert c.get('/foo/').data == 'index'1547 assert c.get('/foo/bar').data == 'bar'154815491550class BlueprintTestCase(unittest.TestCase):15511552 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__)15561557 @frontend.errorhandler(403)1558 def frontend_forbidden(e):1559 return 'frontend says no', 40315601561 @frontend.route('/frontend-no')1562 def frontend_no():1563 flask.abort(403)15641565 @backend.errorhandler(403)1566 def backend_forbidden(e):1567 return 'backend says no', 40315681569 @backend.route('/backend-no')1570 def backend_no():1571 flask.abort(403)15721573 @sideend.route('/what-is-a-sideend')1574 def sideend_no():1575 flask.abort(403)15761577 app = flask.Flask(__name__)1578 app.register_blueprint(frontend)1579 app.register_blueprint(backend)1580 app.register_blueprint(sideend)15811582 @app.errorhandler(403)1583 def app_forbidden(e):1584 return 'application itself says no', 40315851586 c = app.test_client()15871588 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'15911592 def test_blueprint_url_definitions(self):1593 bp = flask.Blueprint('test', __name__)15941595 @bp.route('/foo', defaults={'baz': 42})1596 def foo(bar, baz):1597 return '%s/%d' % (bar, baz)15981599 @bp.route('/bar')1600 def bar(bar):1601 return unicode(bar)16021603 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})16061607 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')16121613 def test_blueprint_url_processors(self):1614 bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')16151616 @bp.url_defaults1617 def add_language_code(endpoint, values):1618 values.setdefault('lang_code', flask.g.lang_code)16191620 @bp.url_value_preprocessor1621 def pull_lang_code(endpoint, values):1622 flask.g.lang_code = values.pop('lang_code')16231624 @bp.route('/')1625 def index():1626 return flask.url_for('.about')16271628 @bp.route('/about')1629 def about():1630 return flask.url_for('.index')16311632 app = flask.Flask(__name__)1633 app.register_blueprint(bp)16341635 c = app.test_client()16361637 self.assertEqual(c.get('/de/').data, '/de/about')1638 self.assertEqual(c.get('/de/about').data, '/de/')16391640 def test_templates_and_static(self):1641 from blueprintapp import app1642 c = app.test_client()16431644 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 */'16541655 with app.test_request_context():1656 assert flask.url_for('admin.static', filename='test.txt') \1657 == '/admin/static/test.txt'16581659 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'16661667 with flask.Flask(__name__).test_request_context():1668 assert flask.render_template('nested/nested.txt') == 'I\'m nested'16691670 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'])16751676 def test_dotted_names(self):1677 frontend = flask.Blueprint('myapp.frontend', __name__)1678 backend = flask.Blueprint('myapp.backend', __name__)16791680 @frontend.route('/fe')1681 def frontend_index():1682 return flask.url_for('myapp.backend.backend_index')16831684 @frontend.route('/fe2')1685 def frontend_page2():1686 return flask.url_for('.frontend_index')16871688 @backend.route('/be')1689 def backend_index():1690 return flask.url_for('myapp.frontend.frontend_index')16911692 app = flask.Flask(__name__)1693 app.register_blueprint(frontend)1694 app.register_blueprint(backend)16951696 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')17001701 def test_empty_url_defaults(self):1702 bp = flask.Blueprint('bp', __name__)17031704 @bp.route('/', defaults={'page': 1})1705 @bp.route('/page/<int:page>')1706 def something(page):1707 return str(page)17081709 app = flask.Flask(__name__)1710 app.register_blueprint(bp)17111712 c = app.test_client()1713 self.assertEqual(c.get('/').data, '1')1714 self.assertEqual(c.get('/page/2').data, '2')17151716 def test_route_decorator_custom_endpoint(self):17171718 bp = flask.Blueprint('bp', __name__)17191720 @bp.route('/foo')1721 def foo():1722 return flask.request.endpoint17231724 @bp.route('/bar', endpoint='bar')1725 def foo_bar():1726 return flask.request.endpoint17271728 @bp.route('/bar/123', endpoint='123')1729 def foo_bar_foo():1730 return flask.request.endpoint17311732 @bp.route('/bar/foo')1733 def bar_foo():1734 return flask.request.endpoint17351736 app = flask.Flask(__name__)1737 app.register_blueprint(bp, url_prefix='/py')17381739 @app.route('/')1740 def index():1741 return flask.request.endpoint17421743 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')17491750 def test_route_decorator_custom_endpoint_with_dots(self):1751 bp = flask.Blueprint('bp', __name__)17521753 @bp.route('/foo')1754 def foo():1755 return flask.request.endpoint17561757 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')17651766 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')17741775 def foo_foo_foo():1776 pass17771778 self.assertRaises(1779 AssertionError,1780 lambda: bp.add_url_rule(1781 '/bar/123', endpoint='bar.123', view_func=foo_foo_foo1782 )1783 )17841785 self.assertRaises(1786 AssertionError,1787 bp.route('/bar/123', endpoint='bar.123'),1788 lambda: None1789 )17901791 app = flask.Flask(__name__)1792 app.register_blueprint(bp, url_prefix='/py')17931794 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 == 40418011802class SendfileTestCase(unittest.TestCase):18031804 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()18121813 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'18231824 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) == 218351836 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) == 218471848 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) == 118641865 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) == 118731874 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) == 218841885 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'18911892 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'190019011902class LoggingTestCase(unittest.TestCase):19031904 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 logger119111912 def test_debug_log(self):1913 app = flask.Flask(__name__)1914 app.debug = True19151916 @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 ''19211922 @app.route('/exc')1923 def exc():1924 1/01925 c = app.test_client()19261927 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 out19341935 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'19421943 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))19481949 @app.route('/')1950 def index():1951 1/019521953 rv = app.test_client().get('/')1954 assert rv.status_code == 5001955 assert 'Internal Server Error' in rv.data19561957 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 err19621963 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'198419851986class ConfigTestCase(unittest.TestCase):19871988 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.config19921993 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)19971998 def test_config_from_object(self):1999 app = flask.Flask(__name__)2000 app.config.from_object(__name__)2001 self.common_object_test(app)20022003 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)20112012 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)20252026 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 = env20312032 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)204420452046class SubdomainTestCase(unittest.TestCase):20472048 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'20572058 c = app.test_client()2059 rv = c.get('/', 'http://localhost/')2060 assert rv.data == 'normal index'20612062 rv = c.get('/', 'http://test.localhost/')2063 assert rv.data == 'test index'20642065 @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'20742075 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' % user20812082 c = app.test_client()2083 rv = c.get('/', 'http://mitsuhiko.localhost/')2084 assert rv.data == 'index for mitsuhiko'20852086 @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'20912092 @mod.route('/test')2093 def test():2094 return 'Test'20952096 @mod.route('/outside', subdomain='xtesting')2097 def bar():2098 return 'Outside'20992100 app.register_module(mod)21012102 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'210721082109class TestSignals(unittest.TestCase):21102111 def test_template_rendered(self):2112 app = flask.Flask(__name__)21132114 @app.route('/')2115 def index():2116 return flask.render_template('simple_template.html', whiskey=42)21172118 recorded = []2119 def record(sender, template, context):2120 recorded.append((template, context))21212122 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)21312132 def test_request_signals(self):2133 app = flask.Flask(__name__)2134 calls = []21352136 def before_request_signal(sender):2137 calls.append('before-signal')21382139 def after_request_signal(sender, response):2140 assert response.data == 'stuff'2141 calls.append('after-signal')21422143 @app.before_request2144 def before_request_handler():2145 calls.append('before-handler')21462147 @app.after_request2148 def after_request_handler(response):2149 calls.append('after-handler')2150 response.data = 'stuff'2151 return response21522153 @app.route('/')2154 def index():2155 calls.append('handler')2156 return 'ignored anyway'21572158 flask.request_started.connect(before_request_signal, app)2159 flask.request_finished.connect(after_request_signal, app)21602161 try:2162 rv = app.test_client().get('/')2163 assert rv.data == 'stuff'21642165 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)21712172 def test_request_exception_signal(self):2173 app = flask.Flask(__name__)2174 recorded = []21752176 @app.route('/')2177 def index():2178 1/021792180 def record(sender, exception):2181 recorded.append(exception)21822183 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)219021912192class ViewTestCase(unittest.TestCase):21932194 def common_test(self, app):2195 c = app.test_client()21962197 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'])22022203 def test_basic_view(self):2204 app = flask.Flask(__name__)22052206 class Index(flask.views.View):2207 methods = ['GET', 'POST']2208 def dispatch_request(self):2209 return flask.request.method22102211 app.add_url_rule('/', view_func=Index.as_view('index'))2212 self.common_test(app)22132214 def test_method_based_view(self):2215 app = flask.Flask(__name__)22162217 class Index(flask.views.MethodView):2218 def get(self):2219 return 'GET'2220 def post(self):2221 return 'POST'22222223 app.add_url_rule('/', view_func=Index.as_view('index'))22242225 self.common_test(app)22262227 def test_view_patching(self):2228 app = flask.Flask(__name__)22292230 class Index(flask.views.MethodView):2231 def get(self):2232 1/02233 def post(self):2234 1/022352236 class Other(Index):2237 def get(self):2238 return 'GET'2239 def post(self):2240 return 'POST'22412242 view = Index.as_view('index')2243 view.view_class = Other2244 app.add_url_rule('/', view_func=view)2245 self.common_test(app)22462247 def test_view_inheritance(self):2248 app = flask.Flask(__name__)22492250 class Index(flask.views.MethodView):2251 def get(self):2252 return 'GET'2253 def post(self):2254 return 'POST'22552256 class BetterIndex(Index):2257 def delete(self):2258 return 'DELETE'22592260 app.add_url_rule('/', view_func=BetterIndex.as_view('index'))2261 c = app.test_client()22622263 meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])2264 self.assertEqual(sorted(meths), ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST'])226522662267class DeprecationsTestCase(unittest.TestCase):22682269 def test_init_jinja_globals(self):2270 class MyFlask(flask.Flask):2271 def init_jinja_globals(self):2272 self.jinja_env.globals['foo'] = '42'22732274 with catch_warnings() as log:2275 app = MyFlask(__name__)2276 @app.route('/')2277 def foo():2278 return app.jinja_env.globals['foo']22792280 c = app.test_client()2281 assert c.get('/').data == '42'2282 assert len(log) == 12283 assert 'init_jinja_globals' in str(log[0]['message'])228422852286def 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 suite230923102311if __name__ == '__main__':2312 unittest.main(defaultTest='suite')
deleted:tests/flaskext_test.py-311 removed
1# -*- coding: utf-8 -*-2"""3 Flask Extension Tests4 ~~~~~~~~~~~~~~~~~~~~~56 Tests the Flask extensions.78 :copyright: (c) 2010 by Ali Afshar.9 :license: BSD, see LICENSE for more details.10"""1112from __future__ import with_statement1314import os15import sys16import shutil17import urllib218import tempfile19import subprocess20import argparse2122from flask import json2324from setuptools.package_index import PackageIndex25from setuptools.archive_util import unpack_archive2627flask_svc_url = 'http://flask.pocoo.org/extensions/'282930# 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.33if sys.platform == 'darwin':34 _tempdir = '/private/tmp'35else:36 _tempdir = tempfile.gettempdir()37tdir = _tempdir + '/flaskext-test'38flaskdir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))394041# virtualenv hack *cough*42os.environ['PYTHONDONTWRITEBYTECODE'] = ''434445RESULT_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'''114115116def log(msg, *args):117 print '[EXTTEST]', msg % args118119120class TestResult(object):121122 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 == 0128129 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')141142 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] = ''150151152def create_tdir():153 try:154 shutil.rmtree(tdir)155 except Exception:156 pass157 os.mkdir(tdir)158159160def 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])166167168def get_test_command(checkout_dir):169 if os.path.isfile(checkout_dir + '/Makefile'):170 return 'make test'171 return 'python setup.py test'172173174def 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 ext180181182def 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)187188 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 path196197198tox_template = """[tox]199envlist=%(env)s200201[testenv]202deps=203 %(deps)s204 distribute205 py206commands=bash flaskext-runtest.sh {envlogdir}/test.log207downloadcache=%(cache)s208"""209210211def 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_path221222223def iter_extensions(only_approved=True):224 for ext in fetch_extensions_list():225 if ext['approved'] or not only_approved:226 yield ext['name']227228229def test_extension(name, interpreters, flask_dep):230 checkout_path = checkout_extension(name)231 log('Running tests with tox in %s', checkout_path)232233 # 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()244245 # if there is a tox.ini, remove it, it will cause troubles246 # for us. Remove it if present, we are running tox ourselves247 # afterall.248249 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)252253254def 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 results270271272def 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 filename281282283def 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()294295 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)301302 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', filename308309310if __name__ == '__main__':311 main()
modified:CHANGES+11 added
30 unmodified lines
31 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.4647Version 0.7.348-------------49
238 unmodified lines
modified:Makefile+1 added-1 removed
1 unmodified line
23all: clean-pyc test45test:6 python setup.py test6 python run-tests.py78audit:9 python setup.py audit10
24 unmodified lines
modified:MANIFEST.in+4 added-1 removed
1include Makefile CHANGES LICENSE AUTHORS1include Makefile CHANGES LICENSE AUTHORS run-tests.py2recursive-include artwork *3recursive-include tests *4recursive-include examples *5recursive-include docs *
2 unmodified lines
8recursive-exclude tests *.pyc9recursive-exclude tests *.pyo10recursive-exclude examples *.pyc11recursive-exclude examples *.pyo12recursive-include flask/testsuite/static *13recursive-include flask/testsuite/templates *14recursive-include flask/testsuite/test_apps *15prune docs/_build16prune docs/_themes/.git
modified:README+25 added-8 removed
9 unmodified lines
10 and was developed with best intentions in mind.1112 ~ Is it ready?1314 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.1718 ~ What do I need?1921 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.2425 ~ Where are the docs?2628 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.3031 ~ Where are the tests?3233 Good that you're asking. The tests are in the34 flask/testsuite package. To run the tests use the35 `run-tests.py` file:3637 $ python run-tests.py3839 If it's not enough output for you, you can use the40 `--verbose` flag:4142 $ python run-tests.py --verbose4344 If you just want one particular testcase to run you can45 provide it on the command line:4647 $ python run-tests.py test_to_run4849 ~ Where can I get help?5051 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 python2from flask.testsuite import main3main()
modified:setup.py+5 added-8 removed
75 unmodified lines
76 print ("Audit finished with total %d warnings." % warns)77 else:78 print ("No problems found in sourcecode.")7980def 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()808681setup(82 name='Flask',83 version='0.8-dev',84 url='http://github.com/mitsuhiko/flask/',
2 unmodified lines
87 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 lines
108 '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)