Skip to content
Myr

Merge branch 'sprint-branch'

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parents 250247d, b8aa9fe · Browse files · 44 files+732 added−549 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

44 files+732 added−549 removed

  • other:+732 added−549 removed

44 files+732 added−549 removed

modified:docs/patterns/jquery.rst-4 removed
9 unmodified lines
10Python primitives (numbers, strings, dicts and lists) look like which is11widely supported and very easy to parse. It became popular a few years12ago and quickly replaced XML as transport format in web applications.1314If you have Python 2.6 JSON will work out of the box, in Python 2.5 you15will have to install the `simplejson`_ library from PyPI.1614.. _jQuery: http://jquery.com/18.. _simplejson: http://pypi.python.org/pypi/simplejson1516Loading jQuery17--------------18
145 unmodified lines
modified:docs/patterns/sqlite3.rst+1 added-1 removed
122 unmodified lines
123124 def init_db():125 with app.app_context():126 db = get_db()127 with app.open_resource('schema.sql') as f:127 with app.open_resource('schema.sql', mode='r') as f:128 db.cursor().executescript(f.read())129 db.commit()130131You can then create such a database from the python shell:
3 unmodified lines
modified:docs/tutorial/dbinit.rst+3 added-6 removed
19 unmodified lines
20errors. It's a good idea to add a function that initializes the database21for you to the application.2223If you want to do that, you first have to import the24:func:`contextlib.closing` function from the contextlib package. If you25want to use Python 2.5 it's also necessary to enable the `with` statement26first (`__future__` imports must be the very first import). Accordingly,27add the following lines to your existing imports in `flaskr.py`::24:func:`contextlib.closing` function from the contextlib package.25Accordingly, add the following lines to your existing imports in `flaskr.py`::2629 from __future__ import with_statement27 from contextlib import closing2829Next we can create a function called `init_db` that initializes the30database. For this we can use the `connect_db` function we defined
1 unmodified line
32`flaskr.py`::3334 def init_db():35 with closing(connect_db()) as db:39 with app.open_resource('schema.sql') as f:36 with app.open_resource('schema.sql', mode='r') as f:37 db.cursor().executescript(f.read())38 db.commit()3940The :func:`~contextlib.closing` helper function allows us to keep a
26 unmodified lines
modified:docs/extensiondev.rst+1 added-1 removed
388 unmodified lines
389 must be a link to automatically install the development version390 (``PackageName==dev``).3919. The ``zip_safe`` flag in the setup script must be set to ``False``,392 even if the extension would be safe for zipping.39310. An extension currently has to support Python 2.5, 2.6 as well as39310. An extension currently has to support Python 2.6 as well as394 Python 2.7395396397.. _ext-import-transition:
23 unmodified lines
modified:docs/installation.rst+1 added-1 removed
11 unmodified lines
12So how do you get all that on your computer quickly? There are many ways you13could do that, but the most kick-ass method is virtualenv, so let's have a look14at that first.1516You will need Python 2.5 or higher to get started, so be sure to have an16You will need Python 2.6 or higher to get started, so be sure to have an17up-to-date Python 2.x installation. Python 3.x is not supported.1819.. _virtualenv:20
152 unmodified lines
modified:examples/flaskr/flaskr_tests.py+8 added-8 removed
40 unmodified lines
4142 def test_empty_db(self):43 """Start with a blank database."""44 rv = self.app.get('/')45 assert 'No entries here so far' in rv.data45 assert b'No entries here so far' in rv.data4647 def test_login_logout(self):48 """Make sure login and logout works"""49 rv = self.login(flaskr.app.config['USERNAME'],50 flaskr.app.config['PASSWORD'])51 assert 'You were logged in' in rv.data51 assert b'You were logged in' in rv.data52 rv = self.logout()53 assert 'You were logged out' in rv.data53 assert b'You were logged out' in rv.data54 rv = self.login(flaskr.app.config['USERNAME'] + 'x',55 flaskr.app.config['PASSWORD'])56 assert 'Invalid username' in rv.data56 assert b'Invalid username' in rv.data57 rv = self.login(flaskr.app.config['USERNAME'],58 flaskr.app.config['PASSWORD'] + 'x')59 assert 'Invalid password' in rv.data59 assert b'Invalid password' in rv.data6061 def test_messages(self):62 """Test that messages work"""63 self.login(flaskr.app.config['USERNAME'],
1 unmodified line
65 rv = self.app.post('/add', data=dict(66 title='<Hello>',67 text='<strong>HTML</strong> allowed here'68 ), follow_redirects=True)69 assert 'No entries here so far' not in rv.data70 assert '&lt;Hello&gt;' in rv.data71 assert '<strong>HTML</strong> allowed here' in rv.data69 assert b'No entries here so far' not in rv.data70 assert b'&lt;Hello&gt;' in rv.data71 assert b'<strong>HTML</strong> allowed here' in rv.data727374if __name__ == '__main__':75 unittest.main()
modified:examples/flaskr/flaskr.py+2 added-2 removed
7 unmodified lines
89 :copyright: (c) 2010 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""12from __future__ import with_statement1213from sqlite3 import dbapi2 as sqlite314from flask import Flask, request, session, g, redirect, url_for, abort, \15 render_template, flash, _app_ctx_stack16
13 unmodified lines
30def init_db():31 """Creates the database tables."""32 with app.app_context():33 db = get_db()34 with app.open_resource('schema.sql') as f:34 with app.open_resource('schema.sql', mode='r') as f:35 db.cursor().executescript(f.read())36 db.commit()3738
66 unmodified lines
modified:examples/minitwit/minitwit_tests.py+28 added-28 removed
61 unmodified lines
62 """Records a message"""63 rv = self.app.post('/add_message', data={'text': text},64 follow_redirects=True)65 if text:66 assert 'Your message was recorded' in rv.data66 assert b'Your message was recorded' in rv.data67 return rv6869 # testing functions7071 def test_register(self):72 """Make sure registering works"""73 rv = self.register('user1', 'default')74 assert 'You were successfully registered ' \75 'and can login now' in rv.data74 assert b'You were successfully registered ' \75 b'and can login now' in rv.data76 rv = self.register('user1', 'default')77 assert 'The username is already taken' in rv.data77 assert b'The username is already taken' in rv.data78 rv = self.register('', 'default')79 assert 'You have to enter a username' in rv.data79 assert b'You have to enter a username' in rv.data80 rv = self.register('meh', '')81 assert 'You have to enter a password' in rv.data81 assert b'You have to enter a password' in rv.data82 rv = self.register('meh', 'x', 'y')83 assert 'The two passwords do not match' in rv.data83 assert b'The two passwords do not match' in rv.data84 rv = self.register('meh', 'foo', email='broken')85 assert 'You have to enter a valid email address' in rv.data85 assert b'You have to enter a valid email address' in rv.data8687 def test_login_logout(self):88 """Make sure logging in and logging out works"""89 rv = self.register_and_login('user1', 'default')90 assert 'You were logged in' in rv.data90 assert b'You were logged in' in rv.data91 rv = self.logout()92 assert 'You were logged out' in rv.data92 assert b'You were logged out' in rv.data93 rv = self.login('user1', 'wrongpassword')94 assert 'Invalid password' in rv.data94 assert b'Invalid password' in rv.data95 rv = self.login('user2', 'wrongpassword')96 assert 'Invalid username' in rv.data96 assert b'Invalid username' in rv.data9798 def test_message_recording(self):99 """Check if adding messages works"""100 self.register_and_login('foo', 'default')101 self.add_message('test message 1')102 self.add_message('<test message 2>')103 rv = self.app.get('/')104 assert 'test message 1' in rv.data105 assert '&lt;test message 2&gt;' in rv.data104 assert b'test message 1' in rv.data105 assert b'&lt;test message 2&gt;' in rv.data106107 def test_timelines(self):108 """Make sure that timelines work"""109 self.register_and_login('foo', 'default')
1 unmodified line
111 self.logout()112 self.register_and_login('bar', 'default')113 self.add_message('the message by bar')114 rv = self.app.get('/public')115 assert 'the message by foo' in rv.data116 assert 'the message by bar' in rv.data115 assert b'the message by foo' in rv.data116 assert b'the message by bar' in rv.data117118 # bar's timeline should just show bar's message119 rv = self.app.get('/')120 assert 'the message by foo' not in rv.data121 assert 'the message by bar' in rv.data120 assert b'the message by foo' not in rv.data121 assert b'the message by bar' in rv.data122123 # now let's follow foo124 rv = self.app.get('/foo/follow', follow_redirects=True)125 assert 'You are now following &#34;foo&#34;' in rv.data125 assert b'You are now following &#34;foo&#34;' in rv.data126127 # we should now see foo's message128 rv = self.app.get('/')129 assert 'the message by foo' in rv.data130 assert 'the message by bar' in rv.data129 assert b'the message by foo' in rv.data130 assert b'the message by bar' in rv.data131132 # but on the user's page we only want the user's message133 rv = self.app.get('/bar')134 assert 'the message by foo' not in rv.data135 assert 'the message by bar' in rv.data134 assert b'the message by foo' not in rv.data135 assert b'the message by bar' in rv.data136 rv = self.app.get('/foo')137 assert 'the message by foo' in rv.data138 assert 'the message by bar' not in rv.data137 assert b'the message by foo' in rv.data138 assert b'the message by bar' not in rv.data139140 # now unfollow and check if that worked141 rv = self.app.get('/foo/unfollow', follow_redirects=True)142 assert 'You are no longer following &#34;foo&#34;' in rv.data142 assert b'You are no longer following &#34;foo&#34;' in rv.data143 rv = self.app.get('/')144 assert 'the message by foo' not in rv.data145 assert 'the message by bar' in rv.data144 assert b'the message by foo' not in rv.data145 assert b'the message by bar' in rv.data146147148if __name__ == '__main__':149 unittest.main()
modified:examples/minitwit/minitwit.py+2 added-2 removed
6 unmodified lines
78 :copyright: (c) 2010 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from __future__ import with_statement1112import time13from sqlite3 import dbapi2 as sqlite314from hashlib import md515from datetime import datetime
36 unmodified lines
52def init_db():53 """Creates the database tables."""54 with app.app_context():55 db = get_db()56 with app.open_resource('schema.sql') as f:56 with app.open_resource('schema.sql', mode='r') as f:57 db.cursor().executescript(f.read())58 db.commit()5960
195 unmodified lines
modified:flask/testsuite/__init__.py+30 added-8 removed
8 unmodified lines
9 :copyright: (c) 2011 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213from __future__ import with_statement13from __future__ import print_function1415import os16import sys17import flask18import warnings19import unittest20from StringIO import StringIO20from functools import update_wrapper21from contextlib import contextmanager22from werkzeug.utils import import_string, find_modules23from flask._compat import reraise, StringIO242526def add_to_path(path):27 """Adds an entry to sys.path if it's not already there. This does
72 unmodified lines
100def emits_module_deprecation_warning(f):101 def new_f(self, *args, **kwargs):102 with catch_warnings() as log:103 f(self, *args, **kwargs)104 self.assert_(log, 'expected deprecation warning')104 self.assert_true(log, 'expected deprecation warning')105 for entry in log:106 self.assert_('Modules are deprecated' in str(entry['message']))106 self.assert_in('Modules are deprecated', str(entry['message']))107 return update_wrapper(new_f, f)108109110class FlaskTestCase(unittest.TestCase):
4 unmodified lines
115116 def ensure_clean_request_context(self):117 # make sure we're not leaking a request context since we are118 # testing flask internally in debug mode in a few cases119 self.assert_equal(flask._request_ctx_stack.top, None)119 leaks = []120 while flask._request_ctx_stack.top is not None:121 leaks.append(flask._request_ctx_stack.pop())122 self.assert_equal(leaks, [])123124 def setup(self):125 pass126
17 unmodified lines
144 return catcher145 with catcher:146 callable(*args, **kwargs)147148 def assert_true(self, x, msg=None):149 self.assertTrue(x, msg)150151 def assert_false(self, x, msg=None):152 self.assertFalse(x, msg)153154 def assert_in(self, x, y):155 self.assertIn(x, y)156157 def assert_not_in(self, x, y):158 self.assertNotIn(x, y)159160 if sys.version_info[:2] == (2, 6):161 def assertIn(self, x, y):162 assert x in y, "%r unexpectedly not in %r" % (x, y)163164 def assertNotIn(self, x, y):165 assert x not in y, "%r unexpectedly in %r" % (x, y)166167168class _ExceptionCatcher(object):169170 def __init__(self, test_case, exc_type):171 self.test_case = test_case
7 unmodified lines
179 if exc_type is None:180 self.test_case.fail('Expected exception of type %r' %181 exception_name)182 elif not issubclass(exc_type, self.exc_type):161 raise exc_type, exc_value, tb183 reraise(exc_type, exc_value, tb)184 return True185186187class BetterLoader(unittest.TestLoader):
53 unmodified lines
241def main():242 """Runs the testsuite as command line application."""243 try:244 unittest.main(testLoader=BetterLoader(), defaultTest='suite')223 except Exception, e:224 print 'Error: %s' % e245 except Exception as e:246 print('Error: %s' % e)
modified:flask/testsuite/appctx.py+2 added-3 removed
7 unmodified lines
8 :copyright: (c) 2012 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112from __future__ import with_statement1312import flask13import unittest14from flask.testsuite import FlaskTestCase15
70 unmodified lines
86 def index():87 with flask._app_ctx_stack.top:88 with flask._request_ctx_stack.top:89 pass92 self.assert_(flask._request_ctx_stack.request.environ90 self.assert_true(flask._request_ctx_stack.top.request.environ91 ['werkzeug.request'] is not None)92 return u''93 c = app.test_client()94 c.get('/')95 self.assertEqual(called, ['request', 'app'])96
5 unmodified lines
modified:flask/testsuite/basic.py+126 added-124 removed
7 unmodified lines
8 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112from __future__ import with_statement1312import re13import uuid14import flask15import pickle16import unittest17from datetime import datetime18from threading import Thread19from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning20from flask._compat import text_type21from werkzeug.exceptions import BadRequest, NotFound22from werkzeug.http import parse_date23from werkzeug.routing import BuildError24
6 unmodified lines
31 def index():32 return 'Hello World'33 rv = app.test_client().open('/', method='OPTIONS')34 self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST'])36 self.assert_equal(rv.data, '')35 self.assert_equal(rv.data, b'')3637 def test_options_on_multiple_rules(self):38 app = flask.Flask(__name__)39 @app.route('/', methods=['GET', 'POST'])
31 unmodified lines
71 def more():72 return flask.request.method7374 c = app.test_client()76 self.assert_equal(c.get('/').data, 'GET')75 self.assert_equal(c.get('/').data, b'GET')76 rv = c.post('/')77 self.assert_equal(rv.status_code, 405)78 self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS'])79 rv = c.head('/')80 self.assert_equal(rv.status_code, 200)82 self.assert_(not rv.data) # head truncates83 self.assert_equal(c.post('/more').data, 'POST')84 self.assert_equal(c.get('/more').data, 'GET')81 self.assert_false(rv.data) # head truncates82 self.assert_equal(c.post('/more').data, b'POST')83 self.assert_equal(c.get('/more').data, b'GET')84 rv = c.delete('/more')85 self.assert_equal(rv.status_code, 405)86 self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST'])87
7 unmodified lines
95 app.add_url_rule('/', 'index', index)96 app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])9798 c = app.test_client()100 self.assert_equal(c.get('/').data, 'GET')99 self.assert_equal(c.get('/').data, b'GET')100 rv = c.post('/')101 self.assert_equal(rv.status_code, 405)102 self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS'])103 rv = c.head('/')104 self.assert_equal(rv.status_code, 200)106 self.assert_(not rv.data) # head truncates107 self.assert_equal(c.post('/more').data, 'POST')108 self.assert_equal(c.get('/more').data, 'GET')105 self.assert_false(rv.data) # head truncates106 self.assert_equal(c.post('/more').data, b'POST')107 self.assert_equal(c.get('/more').data, b'GET')108 rv = c.delete('/more')109 self.assert_equal(rv.status_code, 405)110 self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST'])111
11 unmodified lines
123 app.view_functions['bar'] = bar124 app.view_functions['index'] = index125126 c = app.test_client()128 self.assert_equal(c.get('/foo/').data, 'index')129 self.assert_equal(c.get('/foo/bar').data, 'bar')127 self.assert_equal(c.get('/foo/').data, b'index')128 self.assert_equal(c.get('/foo/bar').data, b'bar')129130 def test_endpoint_decorator(self):131 from werkzeug.routing import Submount, Rule132 app = flask.Flask(__name__)
10 unmodified lines
143 def index():144 return 'index'145146 c = app.test_client()148 self.assert_equal(c.get('/foo/').data, 'index')149 self.assert_equal(c.get('/foo/bar').data, 'bar')147 self.assert_equal(c.get('/foo/').data, b'index')148 self.assert_equal(c.get('/foo/bar').data, b'bar')149150 def test_session(self):151 app = flask.Flask(__name__)152 app.secret_key = 'testkey'
5 unmodified lines
158 def get():159 return flask.session['value']160161 c = app.test_client()163 self.assert_equal(c.post('/set', data={'value': '42'}).data, 'value set')164 self.assert_equal(c.get('/get').data, '42')162 self.assert_equal(c.post('/set', data={'value': '42'}).data, b'value set')163 self.assert_equal(c.get('/get').data, b'42')164165 def test_session_using_server_name(self):166 app = flask.Flask(__name__)167 app.config.update(
4 unmodified lines
172 def index():173 flask.session['testing'] = 42174 return 'Hello World'175 rv = app.test_client().get('/', 'http://example.com/')177 self.assert_('domain=.example.com' in rv.headers['set-cookie'].lower())178 self.assert_('httponly' in rv.headers['set-cookie'].lower())176 self.assert_in('domain=.example.com', rv.headers['set-cookie'].lower())177 self.assert_in('httponly', rv.headers['set-cookie'].lower())178179 def test_session_using_server_name_and_port(self):180 app = flask.Flask(__name__)181 app.config.update(
4 unmodified lines
186 def index():187 flask.session['testing'] = 42188 return 'Hello World'189 rv = app.test_client().get('/', 'http://example.com:8080/')191 self.assert_('domain=.example.com' in rv.headers['set-cookie'].lower())192 self.assert_('httponly' in rv.headers['set-cookie'].lower())190 self.assert_in('domain=.example.com', rv.headers['set-cookie'].lower())191 self.assert_in('httponly', rv.headers['set-cookie'].lower())192193 def test_session_using_server_name_port_and_path(self):194 app = flask.Flask(__name__)195 app.config.update(
5 unmodified lines
201 def index():202 flask.session['testing'] = 42203 return 'Hello World'204 rv = app.test_client().get('/', 'http://example.com:8080/foo')206 self.assert_('domain=example.com' in rv.headers['set-cookie'].lower())207 self.assert_('path=/foo' in rv.headers['set-cookie'].lower())208 self.assert_('httponly' in rv.headers['set-cookie'].lower())205 self.assert_in('domain=example.com', rv.headers['set-cookie'].lower())206 self.assert_in('path=/foo', rv.headers['set-cookie'].lower())207 self.assert_in('httponly', rv.headers['set-cookie'].lower())208209 def test_session_using_application_root(self):210 class PrefixPathMiddleware(object):211 def __init__(self, app, prefix):
13 unmodified lines
225 def index():226 flask.session['testing'] = 42227 return 'Hello World'228 rv = app.test_client().get('/', 'http://example.com:8080/')230 self.assert_('path=/bar' in rv.headers['set-cookie'].lower())229 self.assert_in('path=/bar', rv.headers['set-cookie'].lower())230231 def test_session_using_session_settings(self):232 app = flask.Flask(__name__)233 app.config.update(
10 unmodified lines
244 flask.session['testing'] = 42245 return 'Hello World'246 rv = app.test_client().get('/', 'http://www.example.com:8080/test/')247 cookie = rv.headers['set-cookie'].lower()249 self.assert_('domain=.example.com' in cookie)250 self.assert_('path=/;' in cookie)251 self.assert_('secure' in cookie)252 self.assert_('httponly' not in cookie)248 self.assert_in('domain=.example.com', cookie)249 self.assert_in('path=/;', cookie)250 self.assert_in('secure', cookie)251 self.assert_not_in('httponly', cookie)252253 def test_missing_session(self):254 app = flask.Flask(__name__)255 def expect_exception(f, *args, **kwargs):256 try:257 f(*args, **kwargs)259 except RuntimeError, e:260 self.assert_(e.args and 'session is unavailable' in e.args[0])258 except RuntimeError as e:259 self.assert_true(e.args and 'session is unavailable' in e.args[0])260 else:262 self.assert_(False, 'expected exception')261 self.assert_true(False, 'expected exception')262 with app.test_request_context():264 self.assert_(flask.session.get('missing_key') is None)263 self.assert_true(flask.session.get('missing_key') is None)264 expect_exception(flask.session.__setitem__, 'foo', 42)265 expect_exception(flask.session.pop, 'foo')266267 def test_session_expiration(self):
7 unmodified lines
275 return ''276277 @app.route('/test')278 def test():280 return unicode(flask.session.permanent)279 return text_type(flask.session.permanent)280281 client = app.test_client()282 rv = client.get('/')284 self.assert_('set-cookie' in rv.headers)283 self.assert_in('set-cookie', rv.headers)284 match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])285 expires = parse_date(match.group())286 expected = datetime.utcnow() + app.permanent_session_lifetime287 self.assert_equal(expires.year, expected.year)288 self.assert_equal(expires.month, expected.month)289 self.assert_equal(expires.day, expected.day)290291 rv = client.get('/test')293 self.assert_equal(rv.data, 'True')292 self.assert_equal(rv.data, b'True')293294 permanent = False295 rv = app.test_client().get('/')297 self.assert_('set-cookie' in rv.headers)296 self.assert_in('set-cookie', rv.headers)297 match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])299 self.assert_(match is None)298 self.assert_true(match is None)299300 def test_session_stored_last(self):301 app = flask.Flask(__name__)302 app.secret_key = 'development-key'
7 unmodified lines
310 def dump_session_contents():311 return repr(flask.session.get('foo'))312313 c = app.test_client()315 self.assert_equal(c.get('/').data, 'None')316 self.assert_equal(c.get('/').data, '42')314 self.assert_equal(c.get('/').data, b'None')315 self.assert_equal(c.get('/').data, b'42')316317 def test_session_special_types(self):318 app = flask.Flask(__name__)319 app.secret_key = 'development-key'
26 unmodified lines
346 app = flask.Flask(__name__)347 app.secret_key = 'testkey'348349 with app.test_request_context():351 self.assert_(not flask.session.modified)350 self.assert_false(flask.session.modified)351 flask.flash('Zap')352 flask.session.modified = False353 flask.flash('Zip')355 self.assert_(flask.session.modified)354 self.assert_true(flask.session.modified)355 self.assert_equal(list(flask.get_flashed_messages()), ['Zap', 'Zip'])356357 def test_extended_flashing(self):358 # Be sure app.testing=True below, else tests can fail silently.
83 unmodified lines
442 def before_request():443 evts.append('before')444 @app.after_request445 def after_request(response):447 response.data += '|after'446 response.data += b'|after'447 evts.append('after')448 return response449 @app.route('/')450 def index():452 self.assert_('before' in evts)453 self.assert_('after' not in evts)451 self.assert_in('before', evts)452 self.assert_not_in('after', evts)453 return 'request'455 self.assert_('after' not in evts)454 self.assert_not_in('after', evts)455 rv = app.test_client().get('/').data457 self.assert_('after' in evts)458 self.assert_equal(rv, 'request|after')456 self.assert_in('after', evts)457 self.assert_equal(rv, b'request|after')458459 def test_after_request_processing(self):460 app = flask.Flask(__name__)461 app.testing = True
20 unmodified lines
482 def root():483 return "Response"484 rv = app.test_client().get('/')485 self.assert_equal(rv.status_code, 200)487 self.assert_('Response' in rv.data)486 self.assert_in(b'Response', rv.data)487 self.assert_equal(len(called), 1)488489 def test_teardown_request_handler_debug_mode(self):490 called = []
7 unmodified lines
498 def root():499 return "Response"500 rv = app.test_client().get('/')501 self.assert_equal(rv.status_code, 200)503 self.assert_('Response' in rv.data)502 self.assert_in(b'Response', rv.data)503 self.assert_equal(len(called), 1)504505 def test_teardown_request_handler_error(self):506 called = []
5 unmodified lines
512 # This raises a new error and blows away sys.exc_info(), so we can513 # test that all teardown_requests get passed the same original514 # exception.515 try:517 raise TypeError516 raise TypeError()517 except:518 pass519 @app.teardown_request520 def teardown_request2(exc):
2 unmodified lines
523 # This raises a new error and blows away sys.exc_info(), so we can524 # test that all teardown_requests get passed the same original525 # exception.526 try:528 raise TypeError527 raise TypeError()528 except:529 pass530 @app.route('/')531 def fails():533 1/0532 1 // 0533 rv = app.test_client().get('/')534 self.assert_equal(rv.status_code, 500)536 self.assert_('Internal Server Error' in rv.data)535 self.assert_in(b'Internal Server Error', rv.data)536 self.assert_equal(len(called), 2)537538 def test_before_after_request_order(self):539 called = []
21 unmodified lines
561 @app.route('/')562 def index():563 return '42'564 rv = app.test_client().get('/')566 self.assert_equal(rv.data, '42')565 self.assert_equal(rv.data, b'42')566 self.assert_equal(called, [1, 2, 3, 4, 5, 6])567568 def test_error_handling(self):569 app = flask.Flask(__name__)
11 unmodified lines
581 1 // 0582 c = app.test_client()583 rv = c.get('/')584 self.assert_equal(rv.status_code, 404)586 self.assert_equal(rv.data, 'not found')585 self.assert_equal(rv.data, b'not found')586 rv = c.get('/error')587 self.assert_equal(rv.status_code, 500)589 self.assert_equal('internal server error', rv.data)588 self.assert_equal(b'internal server error', rv.data)589590 def test_before_request_and_routing_errors(self):591 app = flask.Flask(__name__)592 @app.before_request
3 unmodified lines
596 def return_something(error):597 return flask.g.something, 404598 rv = app.test_client().get('/')599 self.assert_equal(rv.status_code, 404)601 self.assert_equal(rv.data, 'value')600 self.assert_equal(rv.data, b'value')601602 def test_user_error_handling(self):603 class MyException(Exception):604 pass605606 app = flask.Flask(__name__)607 @app.errorhandler(MyException)608 def handle_my_exception(e):610 self.assert_(isinstance(e, MyException))609 self.assert_true(isinstance(e, MyException))610 return '42'611 @app.route('/')612 def index():613 raise MyException()614615 c = app.test_client()617 self.assert_equal(c.get('/').data, '42')616 self.assert_equal(c.get('/').data, b'42')617618 def test_trapping_of_bad_request_key_errors(self):619 app = flask.Flask(__name__)620 app.testing = True
6 unmodified lines
627 app.config['TRAP_BAD_REQUEST_ERRORS'] = True628 c = app.test_client()629 try:630 c.get('/fail')632 except KeyError, e:633 self.assert_(isinstance(e, BadRequest))631 except KeyError as e:632 self.assert_true(isinstance(e, BadRequest))633 else:634 self.fail('Expected exception')635636 def test_trapping_of_all_http_exceptions(self):
6 unmodified lines
643644 c = app.test_client()645 try:646 c.get('/fail')648 except NotFound, e:647 except NotFound as e:648 pass649 else:650 self.fail('Expected exception')651
10 unmodified lines
662 # to not negatively affect other tests.663 with app.test_client() as c:664 try:665 c.post('/fail', data={'foo': 'index.txt'})667 except DebugFilesKeyError, e:668 self.assert_('no file contents were transmitted' in str(e))669 self.assert_('This was submitted: "index.txt"' in str(e))666 except DebugFilesKeyError as e:667 self.assert_in('no file contents were transmitted', str(e))668 self.assert_in('This was submitted: "index.txt"', str(e))669 else:670 self.fail('Expected exception')671672 def test_response_creation(self):
13 unmodified lines
686 c = app.test_client()687 self.assert_equal(c.get('/unicode').data, u'Hällo Wörld'.encode('utf-8'))688 self.assert_equal(c.get('/string').data, u'Hällo Wörld'.encode('utf-8'))689 rv = c.get('/args')691 self.assert_equal(rv.data, 'Meh')690 self.assert_equal(rv.data, b'Meh')691 self.assert_equal(rv.headers['X-Foo'], 'Testing')692 self.assert_equal(rv.status_code, 400)693 self.assert_equal(rv.mimetype, 'text/plain')694
1 unmodified line
696 app = flask.Flask(__name__)697 with app.test_request_context():698 rv = flask.make_response()699 self.assert_equal(rv.status_code, 200)701 self.assert_equal(rv.data, '')700 self.assert_equal(rv.data, b'')701 self.assert_equal(rv.mimetype, 'text/html')702703 rv = flask.make_response('Awesome')704 self.assert_equal(rv.status_code, 200)706 self.assert_equal(rv.data, 'Awesome')705 self.assert_equal(rv.data, b'Awesome')706 self.assert_equal(rv.mimetype, 'text/html')707708 rv = flask.make_response('W00t', 404)709 self.assert_equal(rv.status_code, 404)711 self.assert_equal(rv.data, 'W00t')710 self.assert_equal(rv.data, b'W00t')711 self.assert_equal(rv.mimetype, 'text/html')712713 def test_make_response_with_response_instance(self):714 app = flask.Flask(__name__)715 with app.test_request_context():716 rv = flask.make_response(717 flask.jsonify({'msg': 'W00t'}), 400)718 self.assertEqual(rv.status_code, 400)720 self.assertEqual(rv.data,721 '{\n "msg": "W00t"\n}')719 self.assertEqual(rv.data, b'{\n "msg": "W00t"\n}')720 self.assertEqual(rv.mimetype, 'application/json')721722 rv = flask.make_response(723 flask.Response(''), 400)724 self.assertEqual(rv.status_code, 400)727 self.assertEqual(rv.data, '')725 self.assertEqual(rv.data, b'')726 self.assertEqual(rv.mimetype, 'text/html')727728 rv = flask.make_response(729 flask.Response('', headers={'Content-Type': 'text/html'}),
22 unmodified lines
752 # Verify the error is re-raised if not the current exception.753 try:754 with app.test_request_context():755 flask.url_for('spam')758 except BuildError, error:759 pass756 except BuildError as err:757 error = err758 try:759 raise RuntimeError('Test case where BuildError is not current.')760 except RuntimeError:761 self.assertRaises(BuildError, app.handle_url_build_error, error, 'spam', {})
19 unmodified lines
781 @app.route('/<list:args>')782 def index(args):783 return '|'.join(args)784 c = app.test_client()787 self.assert_equal(c.get('/1,2,3').data, '1|2|3')785 self.assert_equal(c.get('/1,2,3').data, b'1|2|3')786787 def test_static_files(self):788 app = flask.Flask(__name__)789 app.testing = True790 rv = app.test_client().get('/static/index.html')791 self.assert_equal(rv.status_code, 200)793 self.assert_equal(rv.data.strip(), '<h1>Hello World!</h1>')792 self.assert_equal(rv.data.strip(), b'<h1>Hello World!</h1>')793 with app.test_request_context():794 self.assert_equal(flask.url_for('static', filename='index.html'),795 '/static/index.html')796 rv.close()797798 def test_none_response(self):799 app = flask.Flask(__name__)800 @app.route('/')801 def test():802 return None803 try:804 app.test_client().get('/')805 except ValueError, e:805 except ValueError as e:806 self.assert_equal(str(e), 'View function did not return a response')807 pass808 else:809 self.assert_("Expected ValueError")809 self.assert_true("Expected ValueError")810811 def test_request_locals(self):812 self.assert_equal(repr(flask.g), '<LocalProxy unbound>')813 self.assertFalse(flask.g)
11 unmodified lines
825 def subdomain():826 return 'Foo SubDomain'827828 rv = app.test_client().get('/')829 self.assert_equal(rv.data, 'Foo')829 self.assert_equal(rv.data, b'Foo')830831 rv = app.test_client().get('/', 'http://localhost.localdomain:5000')832 self.assert_equal(rv.data, 'Foo')832 self.assert_equal(rv.data, b'Foo')833834 rv = app.test_client().get('/', 'https://localhost.localdomain:5000')835 self.assert_equal(rv.data, 'Foo')835 self.assert_equal(rv.data, b'Foo')836837 app.config.update(SERVER_NAME='localhost.localdomain')838 rv = app.test_client().get('/', 'https://localhost.localdomain')839 self.assert_equal(rv.data, 'Foo')839 self.assert_equal(rv.data, b'Foo')840841 try:842 app.config.update(SERVER_NAME='localhost.localdomain:443')843 rv = app.test_client().get('/', 'https://localhost.localdomain')844 # Werkzeug 0.8845 self.assert_equal(rv.status_code, 404)846 except ValueError, e:846 except ValueError as e:847 # Werkzeug 0.7848 self.assert_equal(str(e), "the server name provided " +849 "('localhost.localdomain:443') does not match the " + \850 "server name from the WSGI environment ('localhost.localdomain')")
2 unmodified lines
853 app.config.update(SERVER_NAME='localhost.localdomain')854 rv = app.test_client().get('/', 'http://foo.localhost')855 # Werkzeug 0.8856 self.assert_equal(rv.status_code, 404)857 except ValueError, e:857 except ValueError as e:858 # Werkzeug 0.7859 self.assert_equal(str(e), "the server name provided " + \860 "('localhost.localdomain') does not match the " + \861 "server name from the WSGI environment ('foo.localhost')")862863 rv = app.test_client().get('/', 'http://foo.localhost.localdomain')864 self.assert_equal(rv.data, 'Foo SubDomain')864 self.assert_equal(rv.data, b'Foo SubDomain')865866 def test_exception_propagation(self):867 def apprunner(configkey):868 app = flask.Flask(__name__)869 @app.route('/')870 def index():871 1/0871 1 // 0872 c = app.test_client()873 if config_key is not None:874 app.config[config_key] = True875 try:
19 unmodified lines
895 app.config['MAX_CONTENT_LENGTH'] = 64896 @app.before_request897 def always_first():898 flask.request.form['myfile']899 self.assert_(False)899 self.assert_true(False)900 @app.route('/accept', methods=['POST'])901 def accept_file():902 flask.request.form['myfile']903 self.assert_(False)903 self.assert_true(False)904 @app.errorhandler(413)905 def catcher(error):906 return '42'907908 c = app.test_client()909 rv = c.post('/accept', data={'myfile': 'foo' * 100})910 self.assert_equal(rv.data, '42')910 self.assert_equal(rv.data, b'42')911912 def test_url_processors(self):913 app = flask.Flask(__name__)914
20 unmodified lines
935 return flask.url_for('about', lang_code='en')936937 c = app.test_client()938939 self.assert_equal(c.get('/de/').data, '/de/about')940 self.assert_equal(c.get('/de/about').data, '/foo')941 self.assert_equal(c.get('/foo').data, '/en/about')942 939 self.assert_equal(c.get('/de/').data, b'/de/about')940 self.assert_equal(c.get('/de/about').data, b'/foo')941 self.assert_equal(c.get('/foo').data, b'/en/about')942943 def test_inject_blueprint_url_defaults(self):944 app = flask.Flask(__name__)945 bp = flask.Blueprint('foo.bar.baz', __name__, 945 bp = flask.Blueprint('foo.bar.baz', __name__,946 template_folder='template')947948 @bp.url_defaults949 def bp_defaults(endpoint, values):
18 unmodified lines
968 app.debug = True969 @app.route('/')970 def index():971 return 'Awesome'972 self.assert_(not app.got_first_request)973 self.assert_equal(app.test_client().get('/').data, 'Awesome')972 self.assert_false(app.got_first_request)973 self.assert_equal(app.test_client().get('/').data, b'Awesome')974 try:975 @app.route('/foo')976 def broken():977 return 'Meh'978 except AssertionError, e:979 self.assert_('A setup function was called' in str(e))978 except AssertionError as e:979 self.assert_in('A setup function was called', str(e))980 else:981 self.fail('Expected exception')982983 app.debug = False984 @app.route('/foo')985 def working():986 return 'Meh'987 self.assert_equal(app.test_client().get('/foo').data, 'Meh')988 self.assert_(app.got_first_request)987 self.assert_equal(app.test_client().get('/foo').data, b'Meh')988 self.assert_true(app.got_first_request)989990 def test_before_first_request_functions(self):991 got = []992 app = flask.Flask(__name__)
4 unmodified lines
997 c.get('/')998 self.assert_equal(got, [42])999 c.get('/')1000 self.assert_equal(got, [42])1001 self.assert_(app.got_first_request)1001 self.assert_true(app.got_first_request)10021003 def test_routing_redirect_debugging(self):1004 app = flask.Flask(__name__)1005 app.debug = True
2 unmodified lines
1008 return 'success'1009 with app.test_client() as c:1010 try:1011 c.post('/foo', data={})1012 except AssertionError, e:1013 self.assert_('http://localhost/foo/' in str(e))1014 self.assert_('Make sure to directly send your POST-request '1015 'to this URL' in str(e))1012 except AssertionError as e:1013 self.assert_in('http://localhost/foo/', str(e))1014 self.assert_in('Make sure to directly send your POST-request '1015 'to this URL', str(e))1016 else:1017 self.fail('Expected exception')10181019 rv = c.get('/foo', data={}, follow_redirects=True)1020 self.assert_equal(rv.data, 'success')1020 self.assert_equal(rv.data, b'success')10211022 app.debug = False1023 with app.test_client() as c:1024 rv = c.post('/foo', data={}, follow_redirects=True)1025 self.assert_equal(rv.data, 'success')1025 self.assert_equal(rv.data, b'success')10261027 def test_route_decorator_custom_endpoint(self):1028 app = flask.Flask(__name__)1029 app.debug = True
15 unmodified lines
1045 assert flask.url_for('bar') == '/bar/'1046 assert flask.url_for('123') == '/bar/123'10471048 c = app.test_client()1049 self.assertEqual(c.get('/foo/').data, 'foo')1050 self.assertEqual(c.get('/bar/').data, 'bar')1051 self.assertEqual(c.get('/bar/123').data, '123')1049 self.assertEqual(c.get('/foo/').data, b'foo')1050 self.assertEqual(c.get('/bar/').data, b'bar')1051 self.assertEqual(c.get('/bar/123').data, b'123')10521053 def test_preserve_only_once(self):1054 app = flask.Flask(__name__)1055 app.debug = True10561057 @app.route('/fail')1058 def fail_func():1059 1/01059 1 // 010601061 c = app.test_client()1062 for x in xrange(3):1062 for x in range(3):1063 with self.assert_raises(ZeroDivisionError):1064 c.get('/fail')10651066 self.assert_(flask._request_ctx_stack.top is not None)1067 self.assert_(flask._app_ctx_stack.top is not None)1066 self.assert_true(flask._request_ctx_stack.top is not None)1067 self.assert_true(flask._app_ctx_stack.top is not None)1068 # implicit appctx disappears too1069 flask._request_ctx_stack.top.pop()1070 self.assert_(flask._request_ctx_stack.top is None)1071 self.assert_(flask._app_ctx_stack.top is None)1070 self.assert_true(flask._request_ctx_stack.top is None)1071 self.assert_true(flask._app_ctx_stack.top is None)107210731074class SubdomainTestCase(FlaskTestCase):1075
8 unmodified lines
1084 return 'test index'10851086 c = app.test_client()1087 rv = c.get('/', 'http://localhost/')1088 self.assert_equal(rv.data, 'normal index')1088 self.assert_equal(rv.data, b'normal index')10891090 rv = c.get('/', 'http://test.localhost/')1091 self.assert_equal(rv.data, 'test index')1091 self.assert_equal(rv.data, b'test index')10921093 @emits_module_deprecation_warning1094 def test_module_static_path_subdomain(self):1095 app = flask.Flask(__name__)
1 unmodified line
1097 from subdomaintestmodule import mod1098 app.register_module(mod)1099 c = app.test_client()1100 rv = c.get('/static/hello.txt', 'http://foo.example.com/')1101 rv.direct_passthrough = False1101 self.assert_equal(rv.data.strip(), 'Hello Subdomain')1102 self.assert_equal(rv.data.strip(), b'Hello Subdomain')1103 rv.close()11041105 def test_subdomain_matching(self):1106 app = flask.Flask(__name__)1107 app.config['SERVER_NAME'] = 'localhost'
2 unmodified lines
1110 return 'index for %s' % user11111112 c = app.test_client()1113 rv = c.get('/', 'http://mitsuhiko.localhost/')1112 self.assert_equal(rv.data, 'index for mitsuhiko')1114 self.assert_equal(rv.data, b'index for mitsuhiko')11151116 def test_subdomain_matching_with_ports(self):1117 app = flask.Flask(__name__)1118 app.config['SERVER_NAME'] = 'localhost:3000'
2 unmodified lines
1121 return 'index for %s' % user11221123 c = app.test_client()1124 rv = c.get('/', 'http://mitsuhiko.localhost:3000/')1123 self.assert_equal(rv.data, 'index for mitsuhiko')1125 self.assert_equal(rv.data, b'index for mitsuhiko')11261127 @emits_module_deprecation_warning1128 def test_module_subdomain_support(self):1129 app = flask.Flask(__name__)
11 unmodified lines
1141 app.register_module(mod)11421143 c = app.test_client()1144 rv = c.get('/test', 'http://testing.localhost/')1143 self.assert_equal(rv.data, 'Test')1145 self.assert_equal(rv.data, b'Test')1146 rv = c.get('/outside', 'http://xtesting.localhost/')1145 self.assert_equal(rv.data, 'Outside')1147 self.assert_equal(rv.data, b'Outside')114811491150def suite():1151 suite = unittest.TestSuite()
3 unmodified lines
modified:flask/testsuite/blueprints.py+83 added-78 removed
7 unmodified lines
8 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112from __future__ import with_statement1312import flask13import unittest14import warnings15from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning16from flask._compat import text_type17from werkzeug.exceptions import NotFound18from werkzeug.http import parse_cache_control_header19from jinja2 import TemplateNotFound20
24 unmodified lines
45 def index():46 return 'the index'47 app.register_module(admin)48 c = app.test_client()50 self.assert_equal(c.get('/').data, 'the index')51 self.assert_equal(c.get('/admin/').data, 'admin index')52 self.assert_equal(c.get('/admin/login').data, 'admin login')53 self.assert_equal(c.get('/admin/logout').data, 'admin logout')49 self.assert_equal(c.get('/').data, b'the index')50 self.assert_equal(c.get('/admin/').data, b'admin index')51 self.assert_equal(c.get('/admin/login').data, b'admin login')52 self.assert_equal(c.get('/admin/logout').data, b'admin logout')5354 @emits_module_deprecation_warning55 def test_default_endpoint_name(self):56 app = flask.Flask(__name__)
2 unmodified lines
59 return 'Awesome'60 mod.add_url_rule('/', view_func=index)61 app.register_module(mod)62 rv = app.test_client().get('/')64 self.assert_equal(rv.data, 'Awesome')63 self.assert_equal(rv.data, b'Awesome')64 with app.test_request_context():65 self.assert_equal(flask.url_for('frontend.index'), '/')6667 @emits_module_deprecation_warning
23 unmodified lines
91 return 'the index'92 app.register_module(admin)93 c = app.test_client()9496 self.assert_equal(c.get('/').data, 'the index')95 self.assert_equal(c.get('/').data, b'the index')96 self.assert_equal(catched, ['before-app', 'after-app'])97 del catched[:]98100 self.assert_equal(c.get('/admin/').data, 'the admin')99 self.assert_equal(c.get('/admin/').data, b'the admin')100 self.assert_equal(catched, ['before-app', 'before-admin',101 'after-admin', 'after-app'])102103 @emits_module_deprecation_warning104 def test_context_processors(self):105 app = flask.Flask(__name__)106 admin = flask.Module(__name__, 'admin', url_prefix='/admin')107 @app.context_processor109 def inject_all_regualr():108 def inject_all_regular():109 return {'a': 1}110 @admin.context_processor111 def inject_admin():112 return {'b': 2}
7 unmodified lines
120 def admin_index():121 return flask.render_template_string('{{ a }}{{ b }}{{ c }}')122 app.register_module(admin)123 c = app.test_client()125 self.assert_equal(c.get('/').data, '13')126 self.assert_equal(c.get('/admin/').data, '123')124 self.assert_equal(c.get('/').data, b'13')125 self.assert_equal(c.get('/admin/').data, b'123')126127 @emits_module_deprecation_warning128 def test_late_binding(self):129 app = flask.Flask(__name__)
1 unmodified line
131 @admin.route('/')132 def index():133 return '42'134 app.register_module(admin, url_prefix='/admin')136 self.assert_equal(app.test_client().get('/admin/').data, '42')135 self.assert_equal(app.test_client().get('/admin/').data, b'42')136137 @emits_module_deprecation_warning138 def test_error_handling(self):139 app = flask.Flask(__name__)
13 unmodified lines
153 app.register_module(admin)154 c = app.test_client()155 rv = c.get('/')156 self.assert_equal(rv.status_code, 404)158 self.assert_equal(rv.data, 'not found')157 self.assert_equal(rv.data, b'not found')158 rv = c.get('/error')159 self.assert_equal(rv.status_code, 500)161 self.assert_equal('internal server error', rv.data)160 self.assert_equal(b'internal server error', rv.data)161162 def test_templates_and_static(self):163 app = moduleapp164 app.testing = True165 c = app.test_client()166167 rv = c.get('/')169 self.assert_equal(rv.data, 'Hello from the Frontend')168 self.assert_equal(rv.data, b'Hello from the Frontend')169 rv = c.get('/admin/')171 self.assert_equal(rv.data, 'Hello from the Admin')170 self.assert_equal(rv.data, b'Hello from the Admin')171 rv = c.get('/admin/index2')173 self.assert_equal(rv.data, 'Hello from the Admin')172 self.assert_equal(rv.data, b'Hello from the Admin')173 rv = c.get('/admin/static/test.txt')175 self.assert_equal(rv.data.strip(), 'Admin File')174 self.assert_equal(rv.data.strip(), b'Admin File')175 rv.close()176 rv = c.get('/admin/static/css/test.css')177 self.assert_equal(rv.data.strip(), '/* nested file */')177 self.assert_equal(rv.data.strip(), b'/* nested file */')178 rv.close()179180 with app.test_request_context():181 self.assert_equal(flask.url_for('admin.static', filename='test.txt'),182 '/admin/static/test.txt')183184 with app.test_request_context():185 try:186 flask.render_template('missing.html')186 except TemplateNotFound, e:187 except TemplateNotFound as e:188 self.assert_equal(e.name, 'missing.html')189 else:189 self.assert_(0, 'expected exception')190 self.assert_true(0, 'expected exception')191192 with flask.Flask(__name__).test_request_context():193 self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested')194
7 unmodified lines
202 f('/etc/passwd')203 except NotFound:204 pass205 else:205 self.assert_(0, 'expected exception')206 self.assert_true(0, 'expected exception')207 try:208 f('../__init__.py')209 except NotFound:210 pass211 else:211 self.assert_(0, 'expected exception')212 self.assert_true(0, 'expected exception')213214 # testcase for a security issue that may exist on windows systems215 import os216 import ntpath
4 unmodified lines
221 f('..\\__init__.py')222 except NotFound:223 pass224 else:224 self.assert_(0, 'expected exception')225 self.assert_true(0, 'expected exception')226 finally:227 os.path = old_path228229 @emits_module_deprecation_warning
19 unmodified lines
249250 app.register_module(module)251252 c = app.test_client()252 self.assert_equal(c.get('/foo/').data, 'index')253 self.assert_equal(c.get('/foo/bar').data, 'bar')253 self.assert_equal(c.get('/foo/').data, b'index')254 self.assert_equal(c.get('/foo/bar').data, b'bar')255256257class BlueprintTestCase(FlaskTestCase):258
32 unmodified lines
291 return 'application itself says no', 403292293 c = app.test_client()294294 self.assert_equal(c.get('/frontend-no').data, 'frontend says no')295 self.assert_equal(c.get('/backend-no').data, 'backend says no')296 self.assert_equal(c.get('/what-is-a-sideend').data, 'application itself says no')295 self.assert_equal(c.get('/frontend-no').data, b'frontend says no')296 self.assert_equal(c.get('/backend-no').data, b'backend says no')297 self.assert_equal(c.get('/what-is-a-sideend').data, b'application itself says no')298299 def test_blueprint_url_definitions(self):300 bp = flask.Blueprint('test', __name__)301
2 unmodified lines
304 return '%s/%d' % (bar, baz)305306 @bp.route('/bar')307 def bar(bar):307 return unicode(bar)308 return text_type(bar)309310 app = flask.Flask(__name__)311 app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23})312 app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19})313314 c = app.test_client()314 self.assert_equal(c.get('/1/foo').data, u'23/42')315 self.assert_equal(c.get('/2/foo').data, u'19/42')316 self.assert_equal(c.get('/1/bar').data, u'23')317 self.assert_equal(c.get('/2/bar').data, u'19')315 self.assert_equal(c.get('/1/foo').data, b'23/42')316 self.assert_equal(c.get('/2/foo').data, b'19/42')317 self.assert_equal(c.get('/1/bar').data, b'23')318 self.assert_equal(c.get('/2/bar').data, b'19')319320 def test_blueprint_url_processors(self):321 bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')322
17 unmodified lines
340 app.register_blueprint(bp)341342 c = app.test_client()343343 self.assert_equal(c.get('/de/').data, '/de/about')344 self.assert_equal(c.get('/de/about').data, '/de/')344 self.assert_equal(c.get('/de/').data, b'/de/about')345 self.assert_equal(c.get('/de/about').data, b'/de/')346347 def test_templates_and_static(self):348 from blueprintapp import app349 c = app.test_client()350351 rv = c.get('/')351 self.assert_equal(rv.data, 'Hello from the Frontend')352 self.assert_equal(rv.data, b'Hello from the Frontend')353 rv = c.get('/admin/')353 self.assert_equal(rv.data, 'Hello from the Admin')354 self.assert_equal(rv.data, b'Hello from the Admin')355 rv = c.get('/admin/index2')355 self.assert_equal(rv.data, 'Hello from the Admin')356 self.assert_equal(rv.data, b'Hello from the Admin')357 rv = c.get('/admin/static/test.txt')357 self.assert_equal(rv.data.strip(), 'Admin File')358 self.assert_equal(rv.data.strip(), b'Admin File')359 rv.close()360 rv = c.get('/admin/static/css/test.css')359 self.assert_equal(rv.data.strip(), '/* nested file */')361 self.assert_equal(rv.data.strip(), b'/* nested file */')362 rv.close()363364 # try/finally, in case other tests use this app for Blueprint tests.365 max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']366 try:
3 unmodified lines
370 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age371 rv = c.get('/admin/static/css/test.css')372 cc = parse_cache_control_header(rv.headers['Cache-Control'])373 self.assert_equal(cc.max_age, expected_max_age)374 rv.close()375 finally:376 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default377378 with app.test_request_context():
2 unmodified lines
381382 with app.test_request_context():383 try:384 flask.render_template('missing.html')381 except TemplateNotFound, e:385 except TemplateNotFound as e:386 self.assert_equal(e.name, 'missing.html')387 else:384 self.assert_(0, 'expected exception')388 self.assert_true(0, 'expected exception')389390 with flask.Flask(__name__).test_request_context():391 self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested')392
16 unmodified lines
409 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = unexpected_max_age410 rv = blueprint.send_static_file('index.html')411 cc = parse_cache_control_header(rv.headers['Cache-Control'])412 self.assert_equal(cc.max_age, 100)413 rv.close()414 finally:415 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default416417 def test_templates_list(self):
22 unmodified lines
440 app.register_blueprint(frontend)441 app.register_blueprint(backend)442443 c = app.test_client()439 self.assert_equal(c.get('/fe').data.strip(), '/be')440 self.assert_equal(c.get('/fe2').data.strip(), '/fe')441 self.assert_equal(c.get('/be').data.strip(), '/fe')444 self.assert_equal(c.get('/fe').data.strip(), b'/be')445 self.assert_equal(c.get('/fe2').data.strip(), b'/fe')446 self.assert_equal(c.get('/be').data.strip(), b'/fe')447448 def test_empty_url_defaults(self):449 bp = flask.Blueprint('bp', __name__)450
5 unmodified lines
456 app = flask.Flask(__name__)457 app.register_blueprint(bp)458459 c = app.test_client()455 self.assert_equal(c.get('/').data, '1')456 self.assert_equal(c.get('/page/2').data, '2')460 self.assert_equal(c.get('/').data, b'1')461 self.assert_equal(c.get('/page/2').data, b'2')462463 def test_route_decorator_custom_endpoint(self):464465 bp = flask.Blueprint('bp', __name__)
21 unmodified lines
487 def index():488 return flask.request.endpoint489490 c = app.test_client()486 self.assertEqual(c.get('/').data, 'index')487 self.assertEqual(c.get('/py/foo').data, 'bp.foo')488 self.assertEqual(c.get('/py/bar').data, 'bp.bar')489 self.assertEqual(c.get('/py/bar/123').data, 'bp.123')490 self.assertEqual(c.get('/py/bar/foo').data, 'bp.bar_foo')491 self.assertEqual(c.get('/').data, b'index')492 self.assertEqual(c.get('/py/foo').data, b'bp.foo')493 self.assertEqual(c.get('/py/bar').data, b'bp.bar')494 self.assertEqual(c.get('/py/bar/123').data, b'bp.123')495 self.assertEqual(c.get('/py/bar/foo').data, b'bp.bar_foo')496497 def test_route_decorator_custom_endpoint_with_dots(self):498 bp = flask.Blueprint('bp', __name__)499
38 unmodified lines
538 app = flask.Flask(__name__)539 app.register_blueprint(bp, url_prefix='/py')540541 c = app.test_client()537 self.assertEqual(c.get('/py/foo').data, 'bp.foo')538 # The rule's din't actually made it through542 self.assertEqual(c.get('/py/foo').data, b'bp.foo')543 # The rule's didn't actually made it through544 rv = c.get('/py/bar')545 assert rv.status_code == 404546 rv = c.get('/py/bar/123')547 assert rv.status_code == 404
4 unmodified lines
552 def my_reverse(s):553 return s[::-1]554 app = flask.Flask(__name__)555 app.register_blueprint(bp, url_prefix='/py')551 self.assert_('my_reverse' in app.jinja_env.filters.keys())556 self.assert_in('my_reverse', app.jinja_env.filters.keys())557 self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)558 self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba')559560 def test_add_template_filter(self):
2 unmodified lines
563 return s[::-1]564 bp.add_app_template_filter(my_reverse)565 app = flask.Flask(__name__)566 app.register_blueprint(bp, url_prefix='/py')562 self.assert_('my_reverse' in app.jinja_env.filters.keys())567 self.assert_in('my_reverse', app.jinja_env.filters.keys())568 self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)569 self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba')570571 def test_template_filter_with_name(self):
2 unmodified lines
574 def my_reverse(s):575 return s[::-1]576 app = flask.Flask(__name__)577 app.register_blueprint(bp, url_prefix='/py')573 self.assert_('strrev' in app.jinja_env.filters.keys())578 self.assert_in('strrev', app.jinja_env.filters.keys())579 self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)580 self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba')581582 def test_add_template_filter_with_name(self):
2 unmodified lines
585 return s[::-1]586 bp.add_app_template_filter(my_reverse, 'strrev')587 app = flask.Flask(__name__)588 app.register_blueprint(bp, url_prefix='/py')584 self.assert_('strrev' in app.jinja_env.filters.keys())589 self.assert_in('strrev', app.jinja_env.filters.keys())590 self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)591 self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba')592593 def test_template_filter_with_template(self):
6 unmodified lines
600 @app.route('/')601 def index():602 return flask.render_template('template_filter.html', value='abcd')603 rv = app.test_client().get('/')599 self.assert_equal(rv.data, 'dcba')604 self.assert_equal(rv.data, b'dcba')605606 def test_template_filter_after_route_with_template(self):607 app = flask.Flask(__name__)608 @app.route('/')
4 unmodified lines
613 def super_reverse(s):614 return s[::-1]615 app.register_blueprint(bp, url_prefix='/py')616 rv = app.test_client().get('/')612 self.assert_equal(rv.data, 'dcba')617 self.assert_equal(rv.data, b'dcba')618619 def test_add_template_filter_with_template(self):620 bp = flask.Blueprint('bp', __name__)621 def super_reverse(s):
4 unmodified lines
626 @app.route('/')627 def index():628 return flask.render_template('template_filter.html', value='abcd')629 rv = app.test_client().get('/')625 self.assert_equal(rv.data, 'dcba')630 self.assert_equal(rv.data, b'dcba')631632 def test_template_filter_with_name_and_template(self):633 bp = flask.Blueprint('bp', __name__)634 @bp.app_template_filter('super_reverse')
4 unmodified lines
639 @app.route('/')640 def index():641 return flask.render_template('template_filter.html', value='abcd')642 rv = app.test_client().get('/')638 self.assert_equal(rv.data, 'dcba')643 self.assert_equal(rv.data, b'dcba')644645 def test_add_template_filter_with_name_and_template(self):646 bp = flask.Blueprint('bp', __name__)647 def my_reverse(s):
4 unmodified lines
652 @app.route('/')653 def index():654 return flask.render_template('template_filter.html', value='abcd')655 rv = app.test_client().get('/')651 self.assert_equal(rv.data, 'dcba')656 self.assert_equal(rv.data, b'dcba')657658 def test_template_test(self):659 bp = flask.Blueprint('bp', __name__)660 @bp.app_template_test()661 def is_boolean(value):662 return isinstance(value, bool)663 app = flask.Flask(__name__)664 app.register_blueprint(bp, url_prefix='/py')660 self.assert_('is_boolean' in app.jinja_env.tests.keys())665 self.assert_in('is_boolean', app.jinja_env.tests.keys())666 self.assert_equal(app.jinja_env.tests['is_boolean'], is_boolean)662 self.assert_(app.jinja_env.tests['is_boolean'](False))667 self.assert_true(app.jinja_env.tests['is_boolean'](False))668669 def test_add_template_test(self):670 bp = flask.Blueprint('bp', __name__)671 def is_boolean(value):672 return isinstance(value, bool)673 bp.add_app_template_test(is_boolean)674 app = flask.Flask(__name__)675 app.register_blueprint(bp, url_prefix='/py')671 self.assert_('is_boolean' in app.jinja_env.tests.keys())676 self.assert_in('is_boolean', app.jinja_env.tests.keys())677 self.assert_equal(app.jinja_env.tests['is_boolean'], is_boolean)673 self.assert_(app.jinja_env.tests['is_boolean'](False))678 self.assert_true(app.jinja_env.tests['is_boolean'](False))679680 def test_template_test_with_name(self):681 bp = flask.Blueprint('bp', __name__)682 @bp.app_template_test('boolean')683 def is_boolean(value):684 return isinstance(value, bool)685 app = flask.Flask(__name__)686 app.register_blueprint(bp, url_prefix='/py')682 self.assert_('boolean' in app.jinja_env.tests.keys())687 self.assert_in('boolean', app.jinja_env.tests.keys())688 self.assert_equal(app.jinja_env.tests['boolean'], is_boolean)684 self.assert_(app.jinja_env.tests['boolean'](False))689 self.assert_true(app.jinja_env.tests['boolean'](False))690691 def test_add_template_test_with_name(self):692 bp = flask.Blueprint('bp', __name__)693 def is_boolean(value):694 return isinstance(value, bool)695 bp.add_app_template_test(is_boolean, 'boolean')696 app = flask.Flask(__name__)697 app.register_blueprint(bp, url_prefix='/py')693 self.assert_('boolean' in app.jinja_env.tests.keys())698 self.assert_in('boolean', app.jinja_env.tests.keys())699 self.assert_equal(app.jinja_env.tests['boolean'], is_boolean)695 self.assert_(app.jinja_env.tests['boolean'](False))700 self.assert_true(app.jinja_env.tests['boolean'](False))701702 def test_template_test_with_template(self):703 bp = flask.Blueprint('bp', __name__)704 @bp.app_template_test()
4 unmodified lines
709 @app.route('/')710 def index():711 return flask.render_template('template_test.html', value=False)712 rv = app.test_client().get('/')708 self.assert_('Success!' in rv.data)713 self.assert_in(b'Success!', rv.data)714715 def test_template_test_after_route_with_template(self):716 app = flask.Flask(__name__)717 @app.route('/')
4 unmodified lines
722 def boolean(value):723 return isinstance(value, bool)724 app.register_blueprint(bp, url_prefix='/py')725 rv = app.test_client().get('/')721 self.assert_('Success!' in rv.data)726 self.assert_in(b'Success!', rv.data)727728 def test_add_template_test_with_template(self):729 bp = flask.Blueprint('bp', __name__)730 def boolean(value):
4 unmodified lines
735 @app.route('/')736 def index():737 return flask.render_template('template_test.html', value=False)738 rv = app.test_client().get('/')734 self.assert_('Success!' in rv.data)739 self.assert_in(b'Success!', rv.data)740741 def test_template_test_with_name_and_template(self):742 bp = flask.Blueprint('bp', __name__)743 @bp.app_template_test('boolean')
4 unmodified lines
748 @app.route('/')749 def index():750 return flask.render_template('template_test.html', value=False)751 rv = app.test_client().get('/')747 self.assert_('Success!' in rv.data)752 self.assert_in(b'Success!', rv.data)753754 def test_add_template_test_with_name_and_template(self):755 bp = flask.Blueprint('bp', __name__)756 def is_boolean(value):
4 unmodified lines
761 @app.route('/')762 def index():763 return flask.render_template('template_test.html', value=False)764 rv = app.test_client().get('/')760 self.assert_('Success!' in rv.data)765 self.assert_in(b'Success!', rv.data)766767def suite():768 suite = unittest.TestSuite()769 suite.addTest(unittest.makeSuite(BlueprintTestCase))
2 unmodified lines
modified:flask/testsuite/config.py+17 added-18 removed
6 unmodified lines
78 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from __future__ import with_statement1112import os13import sys14import flask
12 unmodified lines
2728 def common_object_test(self, app):29 self.assert_equal(app.secret_key, 'devkey')30 self.assert_equal(app.config['TEST_KEY'], 'foo')32 self.assert_('ConfigTestCase' not in app.config)31 self.assert_not_in('ConfigTestCase', app.config)3233 def test_config_from_file(self):34 app = flask.Flask(__name__)35 app.config.from_pyfile(__file__.rsplit('.', 1)[0] + '.py')
19 unmodified lines
55 os.environ = {}56 app = flask.Flask(__name__)57 try:58 app.config.from_envvar('FOO_SETTINGS')60 except RuntimeError, e:61 self.assert_("'FOO_SETTINGS' is not set" in str(e))59 except RuntimeError as e:60 self.assert_true("'FOO_SETTINGS' is not set" in str(e))61 else:63 self.assert_(0, 'expected exception')64 self.assert_(not app.config.from_envvar('FOO_SETTINGS', silent=True))62 self.assert_true(0, 'expected exception')63 self.assert_false(app.config.from_envvar('FOO_SETTINGS', silent=True))6465 os.environ = {'FOO_SETTINGS': __file__.rsplit('.', 1)[0] + '.py'}67 self.assert_(app.config.from_envvar('FOO_SETTINGS'))66 self.assert_true(app.config.from_envvar('FOO_SETTINGS'))67 self.common_object_test(app)68 finally:69 os.environ = env70
3 unmodified lines
74 os.environ = {'FOO_SETTINGS': 'missing.cfg'}75 try:76 app = flask.Flask(__name__)77 app.config.from_envvar('FOO_SETTINGS')79 except IOError, e:78 except IOError as e:79 msg = str(e)81 self.assert_(msg.startswith('[Errno 2] Unable to load configuration '80 self.assert_true(msg.startswith('[Errno 2] Unable to load configuration '81 'file (No such file or directory):'))83 self.assert_(msg.endswith("missing.cfg'"))82 self.assert_true(msg.endswith("missing.cfg'"))83 else:84 self.fail('expected IOError')85 self.assertFalse(app.config.from_envvar('FOO_SETTINGS', silent=True))86 finally:
2 unmodified lines
89 def test_config_missing(self):90 app = flask.Flask(__name__)91 try:92 app.config.from_pyfile('missing.cfg')94 except IOError, e:93 except IOError as e:94 msg = str(e)96 self.assert_(msg.startswith('[Errno 2] Unable to load configuration '95 self.assert_true(msg.startswith('[Errno 2] Unable to load configuration '96 'file (No such file or directory):'))98 self.assert_(msg.endswith("missing.cfg'"))97 self.assert_true(msg.endswith("missing.cfg'"))98 else:100 self.assert_(0, 'expected config')101 self.assert_(not app.config.from_pyfile('missing.cfg', silent=True))99 self.assert_true(0, 'expected config')100 self.assert_false(app.config.from_pyfile('missing.cfg', silent=True))101102 def test_session_lifetime(self):103 app = flask.Flask(__name__)104 app.config['PERMANENT_SESSION_LIFETIME'] = 42
6 unmodified lines
111112 def __getattr__(self, name):113 if name in ('archive', 'get_filename'):114 msg = 'Mocking a loader which does not have `%s.`' % name116 raise AttributeError, msg115 raise AttributeError(msg)116 return getattr(self.loader, name)117118119@contextmanager
19 unmodified lines
139 def test_explicit_instance_paths(self):140 here = os.path.abspath(os.path.dirname(__file__))141 try:142 flask.Flask(__name__, instance_path='instance')144 except ValueError, e:145 self.assert_('must be absolute' in str(e))143 except ValueError as e:144 self.assert_in('must be absolute', str(e))145 else:146 self.fail('Expected value error')147148 app = flask.Flask(__name__, instance_path=here)
151 unmodified lines
modified:flask/testsuite/deprecations.py+1 added-18 removed
7 unmodified lines
8 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112from __future__ import with_statement1312import flask13import unittest14from flask.testsuite import FlaskTestCase, catch_warnings151617class DeprecationsTestCase(FlaskTestCase):18 """not used currently"""1921 def test_init_jinja_globals(self):22 class MyFlask(flask.Flask):23 def init_jinja_globals(self):24 self.jinja_env.globals['foo'] = '42'2026 with catch_warnings() as log:27 app = MyFlask(__name__)28 @app.route('/')29 def foo():30 return app.jinja_env.globals['foo']3132 c = app.test_client()33 self.assert_equal(c.get('/').data, '42')34 self.assert_equal(len(log), 1)35 self.assert_('init_jinja_globals' in str(log[0]['message']))363721def suite():22 suite = unittest.TestSuite()23 suite.addTest(unittest.makeSuite(DeprecationsTestCase))24 return suite
modified:flask/testsuite/ext.py+22 added-11 removed
6 unmodified lines
78 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from __future__ import with_statement1112import sys13import unittest14try:15 from imp import reload as reload_module16except ImportError:17 reload_module = reload18from flask.testsuite import FlaskTestCase19from flask._compat import PY2201721class ExtImportHookTestCase(FlaskTestCase):2223 def setup(self):24 # we clear this out for various reasons. The most important one is25 # that a real flaskext could be in there which would disable our26 # fake package. Secondly we want to make sure that the flaskext27 # import hook does not break on reloading.25 for entry, value in sys.modules.items():28 for entry, value in list(sys.modules.items()):29 if (entry.startswith('flask.ext.') or30 entry.startswith('flask_') or31 entry.startswith('flaskext.') or32 entry == 'flaskext') and value is not None:33 sys.modules.pop(entry, None)34 from flask import ext32 reload(ext)35 reload_module(ext)3637 # reloading must not add more hooks38 import_hooks = 039 for item in sys.meta_path:
5 unmodified lines
4546 def teardown(self):47 from flask import ext48 for key in ext.__dict__:46 self.assert_('.' not in key)49 self.assert_not_in('.', key)5051 def test_flaskext_new_simple_import_normal(self):52 from flask.ext.newext_simple import ext_id53 self.assert_equal(ext_id, 'newext_simple')
48 unmodified lines
102 from flask.ext.oldext_package.submodule import test_function103 self.assert_equal(test_function(), 42)104105 def test_flaskext_broken_package_no_module_caching(self):103 for x in xrange(2):106 for x in range(2):107 with self.assert_raises(ImportError):108 import flask.ext.broken109110 def test_no_error_swallowing(self):111 try:112 import flask.ext.broken113 except ImportError:114 exc_type, exc_value, tb = sys.exc_info()112 self.assert_(exc_type is ImportError)113 self.assert_equal(str(exc_value), 'No module named missing_module')114 self.assert_(tb.tb_frame.f_globals is globals())115 self.assert_true(exc_type is ImportError)116 if PY2:117 message = 'No module named missing_module'118 else:119 message = 'No module named \'missing_module\''120 self.assert_equal(str(exc_value), message)121 self.assert_true(tb.tb_frame.f_globals is globals())122123 # reraise() adds a second frame so we need to skip that one too.124 # On PY3 we even have another one :(125 next = tb.tb_next.tb_next126 if not PY2:116 next = tb.tb_next117 self.assert_('flask_broken/__init__.py' in next.tb_frame.f_code.co_filename)127 next = next.tb_next128 self.assert_in('flask_broken/__init__.py', next.tb_frame.f_code.co_filename)129130131def suite():132 suite = unittest.TestSuite()
2 unmodified lines
modified:flask/testsuite/helpers.py+56 added-36 removed
7 unmodified lines
8 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112from __future__ import with_statement1312import os13import flask14import unittest15from logging import StreamHandler18from StringIO import StringIO16from flask.testsuite import FlaskTestCase, catch_warnings, catch_stderr17from werkzeug.http import parse_cache_control_header, parse_options_header18from flask._compat import StringIO, text_type, implements_iterator192021def has_encoding(name):22 try:
9 unmodified lines
32 def test_json_bad_requests(self):33 app = flask.Flask(__name__)34 @app.route('/json', methods=['POST'])35 def return_json():38 return flask.jsonify(foo=unicode(flask.request.json))36 return flask.jsonify(foo=text_type(flask.request.json))37 c = app.test_client()38 rv = c.post('/json', data='malformed', content_type='application/json')39 self.assert_equal(rv.status_code, 400)40
40 unmodified lines
81 def test_json_attr(self):82 app = flask.Flask(__name__)83 @app.route('/add', methods=['POST'])84 def add():87 return unicode(flask.request.json['a'] + flask.request.json['b'])85 return text_type(flask.request.json['a'] + flask.request.json['b'])86 c = app.test_client()87 rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),88 content_type='application/json')91 self.assert_equal(rv.data, '3')89 self.assert_equal(rv.data, b'3')9091 def test_template_escaping(self):92 app = flask.Flask(__name__)93 render = flask.render_template_string
32 unmodified lines
126 c = app.test_client()127 rv = c.post('/', data=flask.json.dumps({128 'x': {'_foo': 42}129 }), content_type='application/json')132 self.assertEqual(rv.data, '"<42>"')130 self.assertEqual(rv.data, b'"<42>"')131132 def test_modified_url_encoding(self):133 class ModifiedRequest(flask.Request):134 url_charset = 'euc-kr'135 app = flask.Flask(__name__)136 app.testing = True137 app.request_class = ModifiedRequest138 app.url_map.charset = 'euc-kr'139140 @app.route('/')
13 unmodified lines
154 def test_send_file_regular(self):155 app = flask.Flask(__name__)156 with app.test_request_context():157 rv = flask.send_file('static/index.html')159 self.assert_(rv.direct_passthrough)158 self.assert_true(rv.direct_passthrough)159 self.assert_equal(rv.mimetype, 'text/html')160 with app.open_resource('static/index.html') as f:161 rv.direct_passthrough = False162 self.assert_equal(rv.data, f.read())163 rv.close()164165 def test_send_file_xsendfile(self):166 app = flask.Flask(__name__)167 app.use_x_sendfile = True168 with app.test_request_context():169 rv = flask.send_file('static/index.html')169 self.assert_(rv.direct_passthrough)170 self.assert_('x-sendfile' in rv.headers)170 self.assert_true(rv.direct_passthrough)171 self.assert_in('x-sendfile', rv.headers)172 self.assert_equal(rv.headers['x-sendfile'],173 os.path.join(app.root_path, 'static/index.html'))174 self.assert_equal(rv.mimetype, 'text/html')175 rv.close()176177 def test_send_file_object(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)183 rv.direct_passthrough = False184 with app.open_resource('static/index.html') as f:185 self.assert_equal(rv.data, f.read())186 self.assert_equal(rv.mimetype, 'text/html')187 rv.close()188 # mimetypes + etag189 self.assert_equal(len(captured), 2)190191 app.use_x_sendfile = True
1 unmodified line
193 with app.test_request_context():194 f = open(os.path.join(app.root_path, 'static/index.html'))195 rv = flask.send_file(f)196 self.assert_equal(rv.mimetype, 'text/html')193 self.assert_('x-sendfile' in rv.headers)197 self.assert_in('x-sendfile', rv.headers)198 self.assert_equal(rv.headers['x-sendfile'],199 os.path.join(app.root_path, 'static/index.html'))200 rv.close()201 # mimetypes + etag202 self.assert_equal(len(captured), 2)203204 app.use_x_sendfile = False205 with app.test_request_context():206 with catch_warnings() as captured:207 f = StringIO('Test')208 rv = flask.send_file(f)209 rv.direct_passthrough = False204 self.assert_equal(rv.data, 'Test')210 self.assert_equal(rv.data, b'Test')211 self.assert_equal(rv.mimetype, 'application/octet-stream')212 rv.close()213 # etags214 self.assert_equal(len(captured), 1)215 with catch_warnings() as captured:216 f = StringIO('Test')217 rv = flask.send_file(f, mimetype='text/plain')218 rv.direct_passthrough = False211 self.assert_equal(rv.data, 'Test')219 self.assert_equal(rv.data, b'Test')220 self.assert_equal(rv.mimetype, 'text/plain')221 rv.close()222 # etags223 self.assert_equal(len(captured), 1)224225 app.use_x_sendfile = True226 with catch_warnings() as captured:227 with app.test_request_context():228 f = StringIO('Test')229 rv = flask.send_file(f)221 self.assert_('x-sendfile' not in rv.headers)230 self.assert_not_in('x-sendfile', rv.headers)231 rv.close()232 # etags233 self.assert_equal(len(captured), 1)234235 def test_attachment(self):
3 unmodified lines
239 f = open(os.path.join(app.root_path, 'static/index.html'))240 rv = flask.send_file(f, as_attachment=True)241 value, options = parse_options_header(rv.headers['Content-Disposition'])242 self.assert_equal(value, 'attachment')243 rv.close()244 # mimetypes + etag245 self.assert_equal(len(captured), 2)246247 with app.test_request_context():
1 unmodified line
249 rv = flask.send_file('static/index.html', as_attachment=True)250 value, options = parse_options_header(rv.headers['Content-Disposition'])251 self.assert_equal(value, 'attachment')252 self.assert_equal(options['filename'], 'index.html')253 rv.close()254255 with app.test_request_context():256 rv = flask.send_file(StringIO('Test'), as_attachment=True,257 attachment_filename='index.txt',
1 unmodified line
259 self.assert_equal(rv.mimetype, 'text/plain')260 value, options = parse_options_header(rv.headers['Content-Disposition'])261 self.assert_equal(value, 'attachment')262 self.assert_equal(options['filename'], 'index.txt')263 rv.close()264265 def test_static_file(self):266 app = flask.Flask(__name__)267 # default cache timeout is 12 hours
1 unmodified line
269 # Test with static file handler.270 rv = app.send_static_file('index.html')271 cc = parse_cache_control_header(rv.headers['Cache-Control'])272 self.assert_equal(cc.max_age, 12 * 60 * 60)273 rv.close()274 # Test again with direct use of send_file utility.275 rv = flask.send_file('static/index.html')276 cc = parse_cache_control_header(rv.headers['Cache-Control'])277 self.assert_equal(cc.max_age, 12 * 60 * 60)278 rv.close()279 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600280 with app.test_request_context():281 # Test with static file handler.282 rv = app.send_static_file('index.html')283 cc = parse_cache_control_header(rv.headers['Cache-Control'])284 self.assert_equal(cc.max_age, 3600)285 rv.close()286 # Test again with direct use of send_file utility.287 rv = flask.send_file('static/index.html')288 cc = parse_cache_control_header(rv.headers['Cache-Control'])289 self.assert_equal(cc.max_age, 3600)290 rv.close()291 class StaticFileApp(flask.Flask):292 def get_send_file_max_age(self, filename):293 return 10294 app = StaticFileApp(__name__)
1 unmodified line
296 # Test with static file handler.297 rv = app.send_static_file('index.html')298 cc = parse_cache_control_header(rv.headers['Cache-Control'])299 self.assert_equal(cc.max_age, 10)300 rv.close()301 # Test again with direct use of send_file utility.302 rv = flask.send_file('static/index.html')303 cc = parse_cache_control_header(rv.headers['Cache-Control'])304 self.assert_equal(cc.max_age, 10)305 rv.close()306307308class LoggingTestCase(FlaskTestCase):309310 def test_logger_cache(self):311 app = flask.Flask(__name__)312 logger1 = app.logger294 self.assert_(app.logger is logger1)313 self.assert_true(app.logger is logger1)314 self.assert_equal(logger1.name, __name__)315 app.logger_name = __name__ + '/test_logger_cache'297 self.assert_(app.logger is not logger1)316 self.assert_true(app.logger is not logger1)317318 def test_debug_log(self):319 app = flask.Flask(__name__)320 app.debug = True
5 unmodified lines
326 return ''327328 @app.route('/exc')329 def exc():311 1/0330 1 // 0331332 with app.test_client() as c:333 with catch_stderr() as err:334 c.get('/')335 out = err.getvalue()317 self.assert_('WARNING in helpers [' in out)318 self.assert_(os.path.basename(__file__.rsplit('.', 1)[0] + '.py') in out)319 self.assert_('the standard library is dead' in out)320 self.assert_('this is a debug statement' in out)336 self.assert_in('WARNING in helpers [', out)337 self.assert_in(os.path.basename(__file__.rsplit('.', 1)[0] + '.py'), out)338 self.assert_in('the standard library is dead', out)339 self.assert_in('this is a debug statement', out)340341 with catch_stderr() as err:342 try:343 c.get('/exc')344 except ZeroDivisionError:345 pass346 else:328 self.assert_(False, 'debug log ate the exception')347 self.assert_true(False, 'debug log ate the exception')348349 def test_debug_log_override(self):350 app = flask.Flask(__name__)351 app.debug = True
8 unmodified lines
360 app.logger.addHandler(StreamHandler(out))361362 @app.route('/')363 def index():345 1/0364 1 // 0365366 rv = app.test_client().get('/')367 self.assert_equal(rv.status_code, 500)349 self.assert_('Internal Server Error' in rv.data)368 self.assert_in(b'Internal Server Error', rv.data)369370 err = out.getvalue()352 self.assert_('Exception on / [GET]' in err)353 self.assert_('Traceback (most recent call last):' in err)354 self.assert_('1/0' in err)355 self.assert_('ZeroDivisionError:' in err)371 self.assert_in('Exception on / [GET]', err)372 self.assert_in('Traceback (most recent call last):', err)373 self.assert_in('1 // 0', err)374 self.assert_in('ZeroDivisionError:', err)375376 def test_processor_exceptions(self):377 app = flask.Flask(__name__)378 @app.before_request379 def before_request():380 if trigger == 'before':362 1/0381 1 // 0382 @app.after_request383 def after_request(response):384 if trigger == 'after':366 1/0385 1 // 0386 return response387 @app.route('/')388 def index():389 return 'Foo'
2 unmodified lines
392 return 'Hello Server Error', 500393 for trigger in 'before', 'after':394 rv = app.test_client().get('/')395 self.assert_equal(rv.status_code, 500)377 self.assert_equal(rv.data, 'Hello Server Error')396 self.assert_equal(rv.data, b'Hello Server Error')397398 def test_url_for_with_anchor(self):399 app = flask.Flask(__name__)400 @app.route('/')
83 unmodified lines
484 yield '!'485 return flask.Response(flask.stream_with_context(generate()))486 c = app.test_client()487 rv = c.get('/?name=World')469 self.assertEqual(rv.data, 'Hello World!')488 self.assertEqual(rv.data, b'Hello World!')489490 def test_streaming_with_context_as_decorator(self):491 app = flask.Flask(__name__)492 app.testing = True
6 unmodified lines
499 yield '!'500 return flask.Response(generate())501 c = app.test_client()502 rv = c.get('/?name=World')484 self.assertEqual(rv.data, 'Hello World!')503 self.assertEqual(rv.data, b'Hello World!')504505 def test_streaming_with_context_and_custom_close(self):506 app = flask.Flask(__name__)507 app.testing = True508 called = []509 @implements_iterator510 class Wrapper(object):511 def __init__(self, gen):512 self._gen = gen513 def __iter__(self):514 return self515 def close(self):516 called.append(42)497 def next(self):498 return self._gen.next()517 def __next__(self):518 return next(self._gen)519 @app.route('/')520 def index():521 def generate():522 yield 'Hello '
2 unmodified lines
525 return flask.Response(flask.stream_with_context(526 Wrapper(generate())))527 c = app.test_client()528 rv = c.get('/?name=World')509 self.assertEqual(rv.data, 'Hello World!')529 self.assertEqual(rv.data, b'Hello World!')530 self.assertEqual(called, [42])531532533def suite():
8 unmodified lines
modified:flask/testsuite/regression.py+3 added-5 removed
7 unmodified lines
8 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112from __future__ import with_statement1312import os13import gc14import sys15import flask
49 unmodified lines
65 def fire():66 with app.test_client() as c:67 rv = c.get('/')68 self.assert_equal(rv.status_code, 200)71 self.assert_equal(rv.data, '<h1>42</h1>')69 self.assert_equal(rv.data, b'<h1>42</h1>')7071 # Trigger caches72 fire()7374 # This test only works on CPython 2.7.75 if sys.version_info >= (2, 7) and \76 not hasattr(sys, 'pypy_translation_info'):77 with self.assert_no_leak():80 for x in xrange(10):78 for x in range(10):79 fire()8081 def test_safe_join_toplevel_pardir(self):82 from flask.helpers import safe_join
21 unmodified lines
104 with app.test_client() as c:105 rv = c.get('/')106 self.assertEqual(rv.headers['Location'], 'http://localhost/test')107 rv = c.get('/test')110 self.assertEqual(rv.data, '42')108 self.assertEqual(rv.data, b'42')109110111def suite():112 suite = unittest.TestSuite()
4 unmodified lines
modified:flask/testsuite/reqctx.py+17 added-19 removed
7 unmodified lines
8 :copyright: (c) 2012 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112from __future__ import with_statement1312import flask13import unittest14try:15 from greenlet import greenlet
39 unmodified lines
5556 try:57 with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}):58 pass61 except Exception, e:62 self.assert_(isinstance(e, ValueError))59 except Exception as e:60 self.assert_true(isinstance(e, ValueError))61 self.assert_equal(str(e), "the server name provided " +62 "('localhost.localdomain:5000') does not match the " + \63 "server name from the WSGI environment ('localhost')")6465 try:66 app.config.update(SERVER_NAME='localhost')67 with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}):68 pass71 except ValueError, e:69 except ValueError as e:70 raise ValueError(71 "No ValueError exception should have been raised \"%s\"" % e72 )7374 try:75 app.config.update(SERVER_NAME='localhost:80')76 with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}):77 pass80 except ValueError, e:78 except ValueError as e:79 raise ValueError(80 "No ValueError exception should have been raised \"%s\"" % e81 )82
9 unmodified lines
92 with app.test_request_context('/?name=World'):93 self.assert_equal(index(), 'Hello World!')94 with app.test_request_context('/meh'):95 self.assert_equal(meh(), 'http://localhost/meh')98 self.assert_(flask._request_ctx_stack.top is None)96 self.assert_true(flask._request_ctx_stack.top is None)9798 def test_context_test(self):99 app = flask.Flask(__name__)102 self.assert_(not flask.request)103 self.assert_(not flask.has_request_context())100 self.assert_false(flask.request)101 self.assert_false(flask.has_request_context())102 ctx = app.test_request_context()103 ctx.push()104 try:107 self.assert_(flask.request)108 self.assert_(flask.has_request_context())105 self.assert_true(flask.request)106 self.assert_true(flask.has_request_context())107 finally:108 ctx.pop()109110 def test_manual_context_binding(self):
10 unmodified lines
121 index()122 except RuntimeError:123 pass124 else:127 self.assert_(0, 'expected runtime error')125 self.assert_true(0, 'expected runtime error')126127 def test_greenlet_context_copying(self):128 app = flask.Flask(__name__)129 greenlets = []
1 unmodified line
131 @app.route('/')132 def index():133 reqctx = flask._request_ctx_stack.top.copy()134 def g():137 self.assert_(not flask.request)138 self.assert_(not flask.current_app)135 self.assert_false(flask.request)136 self.assert_false(flask.current_app)137 with reqctx:140 self.assert_(flask.request)138 self.assert_true(flask.request)139 self.assert_equal(flask.current_app, app)140 self.assert_equal(flask.request.path, '/')141 self.assert_equal(flask.request.args['foo'], 'bar')144 self.assert_(not flask.request)142 self.assert_false(flask.request)143 return 42144 greenlets.append(greenlet(g))145 return 'Hello World!'146147 rv = app.test_client().get('/?foo=bar')150 self.assert_equal(rv.data, 'Hello World!')148 self.assert_equal(rv.data, b'Hello World!')149150 result = greenlets[0].run()151 self.assert_equal(result, 42)152
5 unmodified lines
158 def index():159 reqctx = flask._request_ctx_stack.top.copy()160 @flask.copy_current_request_context161 def g():164 self.assert_(flask.request)162 self.assert_true(flask.request)163 self.assert_equal(flask.current_app, app)164 self.assert_equal(flask.request.path, '/')165 self.assert_equal(flask.request.args['foo'], 'bar')166 return 42167 greenlets.append(greenlet(g))168 return 'Hello World!'169170 rv = app.test_client().get('/?foo=bar')173 self.assert_equal(rv.data, 'Hello World!')171 self.assert_equal(rv.data, b'Hello World!')172173 result = greenlets[0].run()174 self.assert_equal(result, 42)175
10 unmodified lines
modified:flask/testsuite/signals.py+4 added-5 removed
6 unmodified lines
78 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from __future__ import with_statement1112import flask13import unittest14from flask.testsuite import FlaskTestCase
29 unmodified lines
44 def before_request_signal(sender):45 calls.append('before-signal')4647 def after_request_signal(sender, response):49 self.assert_equal(response.data, 'stuff')48 self.assert_equal(response.data, b'stuff')49 calls.append('after-signal')5051 @app.before_request52 def before_request_handler():
14 unmodified lines
67 flask.request_finished.connect(after_request_signal, app)6869 try:70 rv = app.test_client().get('/')72 self.assert_equal(rv.data, 'stuff')71 self.assert_equal(rv.data, b'stuff')7273 self.assert_equal(calls, ['before-signal', 'before-handler',74 'handler', 'after-handler',75 'after-signal'])
6 unmodified lines
82 recorded = []8384 @app.route('/')85 def index():87 1/086 1 // 08788 def record(sender, exception):89 recorded.append(exception)9091 flask.got_request_exception.connect(record, app)92 try:93 self.assert_equal(app.test_client().get('/').status_code, 500)94 self.assert_equal(len(recorded), 1)96 self.assert_(isinstance(recorded[0], ZeroDivisionError))95 self.assert_true(isinstance(recorded[0], ZeroDivisionError))96 finally:97 flask.got_request_exception.disconnect(record, app)9899 def test_flash_signal(self):
30 unmodified lines
modified:flask/testsuite/subclassing.py+3 added-3 removed
9 unmodified lines
10 :license: BSD, see LICENSE for more details.11"""12import flask13import unittest14from StringIO import StringIO14from logging import StreamHandler15from flask.testsuite import FlaskTestCase16from flask._compat import StringIO171819class FlaskSubclassingTestCase(FlaskTestCase):20
8 unmodified lines
29 app.logger.addHandler(StreamHandler(out))3031 @app.route('/')32 def index():33 1/033 1 // 03435 rv = app.test_client().get('/')36 self.assert_equal(rv.status_code, 500)37 self.assert_('Internal Server Error' in rv.data)37 self.assert_in(b'Internal Server Error', rv.data)3839 err = out.getvalue()40 self.assert_equal(err, '')41
5 unmodified lines
modified:flask/testsuite/templating.py+33 added-35 removed
7 unmodified lines
8 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112from __future__ import with_statement1312import flask13import unittest14from flask.testsuite import FlaskTestCase15
8 unmodified lines
24 @app.route('/')25 def index():26 return flask.render_template('context_template.html', value=23)27 rv = app.test_client().get('/')30 self.assert_equal(rv.data, '<p>23|42')28 self.assert_equal(rv.data, b'<p>23|42')2930 def test_original_win(self):31 app = flask.Flask(__name__)32 @app.route('/')33 def index():34 return flask.render_template_string('{{ config }}', config=42)35 rv = app.test_client().get('/')38 self.assert_equal(rv.data, '42')36 self.assert_equal(rv.data, b'42')3738 def test_request_less_rendering(self):39 app = flask.Flask(__name__)40 app.config['WORLD_NAME'] = 'Special World'
19 unmodified lines
60 {{ config.DEBUG }}61 {{ session.test }}62 ''')63 rv = app.test_client().get('/?foo=42')66 self.assert_equal(rv.data.split(), ['42', '23', 'False', 'aha'])64 self.assert_equal(rv.data.split(), [b'42', b'23', b'False', b'aha'])6566 def test_escaping(self):67 text = '<p>Hello World!'68 app = flask.Flask(__name__)
2 unmodified lines
71 return flask.render_template('escaping_template.html', text=text,72 html=flask.Markup(text))73 lines = app.test_client().get('/').data.splitlines()74 self.assert_equal(lines, [77 '&lt;p&gt;Hello World!',78 '<p>Hello World!',79 '<p>Hello World!',80 '<p>Hello World!',81 '&lt;p&gt;Hello World!',82 '<p>Hello World!'75 b'&lt;p&gt;Hello World!',76 b'<p>Hello World!',77 b'<p>Hello World!',78 b'<p>Hello World!',79 b'&lt;p&gt;Hello World!',80 b'<p>Hello World!'81 ])8283 def test_no_escaping(self):84 app = flask.Flask(__name__)
13 unmodified lines
98 app = flask.Flask(__name__)99 @app.template_filter()100 def my_reverse(s):101 return s[::-1]104 self.assert_('my_reverse' in app.jinja_env.filters.keys())102 self.assert_in('my_reverse', app.jinja_env.filters.keys())103 self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)104 self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba')105106 def test_add_template_filter(self):107 app = flask.Flask(__name__)108 def my_reverse(s):109 return s[::-1]110 app.add_template_filter(my_reverse)113 self.assert_('my_reverse' in app.jinja_env.filters.keys())111 self.assert_in('my_reverse', app.jinja_env.filters.keys())112 self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)113 self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba')114115 def test_template_filter_with_name(self):116 app = flask.Flask(__name__)117 @app.template_filter('strrev')118 def my_reverse(s):119 return s[::-1]122 self.assert_('strrev' in app.jinja_env.filters.keys())120 self.assert_in('strrev', app.jinja_env.filters.keys())121 self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)122 self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba')123124 def test_add_template_filter_with_name(self):125 app = flask.Flask(__name__)126 def my_reverse(s):127 return s[::-1]128 app.add_template_filter(my_reverse, 'strrev')131 self.assert_('strrev' in app.jinja_env.filters.keys())129 self.assert_in('strrev', app.jinja_env.filters.keys())130 self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)131 self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba')132133 def test_template_filter_with_template(self):
4 unmodified lines
138 @app.route('/')139 def index():140 return flask.render_template('template_filter.html', value='abcd')141 rv = app.test_client().get('/')144 self.assert_equal(rv.data, 'dcba')142 self.assert_equal(rv.data, b'dcba')143144 def test_add_template_filter_with_template(self):145 app = flask.Flask(__name__)146 def super_reverse(s):
2 unmodified lines
149 @app.route('/')150 def index():151 return flask.render_template('template_filter.html', value='abcd')152 rv = app.test_client().get('/')155 self.assert_equal(rv.data, 'dcba')153 self.assert_equal(rv.data, b'dcba')154155 def test_template_filter_with_name_and_template(self):156 app = flask.Flask(__name__)157 @app.template_filter('super_reverse')
2 unmodified lines
160 @app.route('/')161 def index():162 return flask.render_template('template_filter.html', value='abcd')163 rv = app.test_client().get('/')166 self.assert_equal(rv.data, 'dcba')164 self.assert_equal(rv.data, b'dcba')165166 def test_add_template_filter_with_name_and_template(self):167 app = flask.Flask(__name__)168 def my_reverse(s):
2 unmodified lines
171 @app.route('/')172 def index():173 return flask.render_template('template_filter.html', value='abcd')174 rv = app.test_client().get('/')177 self.assert_equal(rv.data, 'dcba')175 self.assert_equal(rv.data, b'dcba')176177 def test_template_test(self):178 app = flask.Flask(__name__)179 @app.template_test()180 def boolean(value):181 return isinstance(value, bool)184 self.assert_('boolean' in app.jinja_env.tests.keys())182 self.assert_in('boolean', app.jinja_env.tests.keys())183 self.assert_equal(app.jinja_env.tests['boolean'], boolean)186 self.assert_(app.jinja_env.tests['boolean'](False))184 self.assert_true(app.jinja_env.tests['boolean'](False))185186 def test_add_template_test(self):187 app = flask.Flask(__name__)188 def boolean(value):189 return isinstance(value, bool)190 app.add_template_test(boolean)193 self.assert_('boolean' in app.jinja_env.tests.keys())191 self.assert_in('boolean', app.jinja_env.tests.keys())192 self.assert_equal(app.jinja_env.tests['boolean'], boolean)195 self.assert_(app.jinja_env.tests['boolean'](False))193 self.assert_true(app.jinja_env.tests['boolean'](False))194195 def test_template_test_with_name(self):196 app = flask.Flask(__name__)197 @app.template_test('boolean')198 def is_boolean(value):199 return isinstance(value, bool)202 self.assert_('boolean' in app.jinja_env.tests.keys())200 self.assert_in('boolean', app.jinja_env.tests.keys())201 self.assert_equal(app.jinja_env.tests['boolean'], is_boolean)204 self.assert_(app.jinja_env.tests['boolean'](False))202 self.assert_true(app.jinja_env.tests['boolean'](False))203204 def test_add_template_test_with_name(self):205 app = flask.Flask(__name__)206 def is_boolean(value):207 return isinstance(value, bool)208 app.add_template_test(is_boolean, 'boolean')211 self.assert_('boolean' in app.jinja_env.tests.keys())209 self.assert_in('boolean', app.jinja_env.tests.keys())210 self.assert_equal(app.jinja_env.tests['boolean'], is_boolean)213 self.assert_(app.jinja_env.tests['boolean'](False))211 self.assert_true(app.jinja_env.tests['boolean'](False))212213 def test_template_test_with_template(self):214 app = flask.Flask(__name__)215 @app.template_test()
2 unmodified lines
218 @app.route('/')219 def index():220 return flask.render_template('template_test.html', value=False)221 rv = app.test_client().get('/')224 self.assert_('Success!' in rv.data)222 self.assert_in(b'Success!', rv.data)223224 def test_add_template_test_with_template(self):225 app = flask.Flask(__name__)226 def boolean(value):
2 unmodified lines
229 @app.route('/')230 def index():231 return flask.render_template('template_test.html', value=False)232 rv = app.test_client().get('/')235 self.assert_('Success!' in rv.data)233 self.assert_in(b'Success!', rv.data)234235 def test_template_test_with_name_and_template(self):236 app = flask.Flask(__name__)237 @app.template_test('boolean')
2 unmodified lines
240 @app.route('/')241 def index():242 return flask.render_template('template_test.html', value=False)243 rv = app.test_client().get('/')246 self.assert_('Success!' in rv.data)244 self.assert_in(b'Success!', rv.data)245246 def test_add_template_test_with_name_and_template(self):247 app = flask.Flask(__name__)248 def is_boolean(value):
2 unmodified lines
251 @app.route('/')252 def index():253 return flask.render_template('template_test.html', value=False)254 rv = app.test_client().get('/')257 self.assert_('Success!' in rv.data)255 self.assert_in(b'Success!', rv.data)256257 def test_add_template_global(self):258 app = flask.Flask(__name__)259 @app.template_global()260 def get_stuff():261 return 42264 self.assert_('get_stuff' in app.jinja_env.globals.keys())262 self.assert_in('get_stuff', app.jinja_env.globals.keys())263 self.assert_equal(app.jinja_env.globals['get_stuff'], get_stuff)266 self.assert_(app.jinja_env.globals['get_stuff'](), 42)264 self.assert_true(app.jinja_env.globals['get_stuff'](), 42)265 with app.app_context():266 rv = flask.render_template_string('{{ get_stuff() }}')267 self.assert_equal(rv, '42')268
7 unmodified lines
276 def index():277 return flask.render_template('index.html')278 c = app.test_client()279 rv = c.get('/')282 self.assert_equal(rv.data, 'Hello Custom World!')280 self.assert_equal(rv.data, b'Hello Custom World!')281282 def test_iterable_loader(self):283 app = flask.Flask(__name__)284 @app.context_processor
7 unmodified lines
292 'context_template.html'],293 value=23)294295 rv = app.test_client().get('/')298 self.assert_equal(rv.data, '<h1>Jameson</h1>')296 self.assert_equal(rv.data, b'<h1>Jameson</h1>')297298299def suite():300 suite = unittest.TestSuite()
2 unmodified lines
modified:flask/testsuite/testing.py+23 added-24 removed
7 unmodified lines
8 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112from __future__ import with_statement1312import flask13import unittest14from flask.testsuite import FlaskTestCase15from flask._compat import text_type161718class TestToolsTestCase(FlaskTestCase):19
9 unmodified lines
29 ctx = app.test_request_context()30 self.assert_equal(ctx.request.url, 'http://example.com:1234/foo/')31 with app.test_client() as c:32 rv = c.get('/')34 self.assert_equal(rv.data, 'http://example.com:1234/foo/')33 self.assert_equal(rv.data, b'http://example.com:1234/foo/')3435 def test_environ_defaults(self):36 app = flask.Flask(__name__)37 app.testing = True
4 unmodified lines
42 ctx = app.test_request_context()43 self.assert_equal(ctx.request.url, 'http://localhost/')44 with app.test_client() as c:45 rv = c.get('/')47 self.assert_equal(rv.data, 'http://localhost/')46 self.assert_equal(rv.data, b'http://localhost/')4748 def test_redirect_keep_session(self):49 app = flask.Flask(__name__)50 app.secret_key = 'testing'
10 unmodified lines
61 return flask.session.get('data', '<missing>')6263 with app.test_client() as c:64 rv = c.get('/getsession')66 assert rv.data == '<missing>'65 assert rv.data == b'<missing>'6667 rv = c.get('/')69 assert rv.data == 'index'68 assert rv.data == b'index'69 assert flask.session.get('data') == 'foo'70 rv = c.post('/', data={}, follow_redirects=True)72 assert rv.data == 'foo'71 assert rv.data == b'foo'7273 # This support requires a new Werkzeug version74 if not hasattr(c, 'redirect_client'):75 assert flask.session.get('data') == 'foo'7677 rv = c.get('/getsession')79 assert rv.data == 'foo'78 assert rv.data == b'foo'7980 def test_session_transactions(self):81 app = flask.Flask(__name__)82 app.testing = True83 app.secret_key = 'testing'8485 @app.route('/')86 def index():88 return unicode(flask.session['foo'])87 return text_type(flask.session['foo'])8889 with app.test_client() as c:90 with c.session_transaction() as sess:91 self.assert_equal(len(sess), 0)92 sess['foo'] = [42]93 self.assert_equal(len(sess), 1)94 rv = c.get('/')96 self.assert_equal(rv.data, '[42]')95 self.assert_equal(rv.data, b'[42]')96 with c.session_transaction() as sess:97 self.assert_equal(len(sess), 1)98 self.assert_equal(sess['foo'], [42])99
4 unmodified lines
104 with app.test_client() as c:105 try:106 with c.session_transaction() as sess:107 pass109 except RuntimeError, e:110 self.assert_('Session backend did not open a session' in str(e))108 except RuntimeError as e:109 self.assert_in('Session backend did not open a session', str(e))110 else:111 self.fail('Expected runtime error')112113 def test_session_transactions_keep_context(self):
3 unmodified lines
117118 with app.test_client() as c:119 rv = c.get('/')120 req = flask.request._get_current_object()122 self.assert_(req is not None)121 self.assert_true(req is not None)122 with c.session_transaction():124 self.assert_(req is flask.request._get_current_object())123 self.assert_true(req is flask.request._get_current_object())124125 def test_session_transaction_needs_cookies(self):126 app = flask.Flask(__name__)127 app.testing = True128 c = app.test_client(use_cookies=False)129 try:130 with c.session_transaction() as s:131 pass133 except RuntimeError, e:134 self.assert_('cookies' in str(e))132 except RuntimeError as e:133 self.assert_in('cookies', str(e))134 else:135 self.fail('Expected runtime error')136137 def test_test_client_context_binding(self):
4 unmodified lines
142 return 'Hello World!'143144 @app.route('/other')145 def other():147 1/0146 1 // 0147148 with app.test_client() as c:149 resp = c.get('/')150 self.assert_equal(flask.g.value, 42)152 self.assert_equal(resp.data, 'Hello World!')151 self.assert_equal(resp.data, b'Hello World!')152 self.assert_equal(resp.status_code, 200)153154 resp = c.get('/other')156 self.assert_(not hasattr(flask.g, 'value'))157 self.assert_('Internal Server Error' in resp.data)155 self.assert_false(hasattr(flask.g, 'value'))156 self.assert_in(b'Internal Server Error', resp.data)157 self.assert_equal(resp.status_code, 500)158 flask.g.value = 23159160 try:
57 unmodified lines
218219 url = flask.url_for('view', company_id='xxx')220 response = self.client.get(url)221223 self.assertEquals(200, response.status_code)224 self.assertEquals('xxx', response.data)222 self.assert_equal(200, response.status_code)223 self.assert_equal(b'xxx', response.data)224225226 def test_nosubdomain(self):227 @self.app.route('/<company_id>')
2 unmodified lines
230231 url = flask.url_for('view', company_id='xxx')232 response = self.client.get(url)233235 self.assertEquals(200, response.status_code)236 self.assertEquals('xxx', response.data)234 self.assert_equal(200, response.status_code)235 self.assert_equal(b'xxx', response.data)236237238def suite():239 suite = unittest.TestSuite()
3 unmodified lines
modified:flask/testsuite/views.py+10 added-10 removed
6 unmodified lines
78 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from __future__ import with_statement1112import flask13import flask.views14import unittest15from flask.testsuite import FlaskTestCase
3 unmodified lines
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')23 self.assert_equal(c.get('/').data, b'GET')24 self.assert_equal(c.post('/').data, b'POST')25 self.assert_equal(c.put('/').status_code, 405)26 meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])27 self.assert_equal(sorted(meths), ['GET', 'HEAD', 'OPTIONS', 'POST'])28
25 unmodified lines
54 app = flask.Flask(__name__)5556 class Index(flask.views.MethodView):57 def get(self):58 1/058 1 // 059 def post(self):60 1/060 1 // 06162 class Other(Index):63 def get(self):64 return 'GET'
42 unmodified lines
107 app.add_url_rule('/', view_func=Index.as_view('index'))108 c = app.test_client()109 rv = c.get('/')110 self.assert_equal(rv.headers['X-Parachute'], 'awesome')111 self.assert_equal(rv.data, 'Awesome')111 self.assert_equal(rv.data, b'Awesome')112113 def test_implicit_head(self):114 app = flask.Flask(__name__)115
5 unmodified lines
121122 app.add_url_rule('/', view_func=Index.as_view('index'))123 c = app.test_client()124 rv = c.get('/')125 self.assert_equal(rv.data, 'Blub')125 self.assert_equal(rv.data, b'Blub')126 self.assert_equal(rv.headers['X-Method'], 'GET')127 rv = c.head('/')128 self.assert_equal(rv.data, '')128 self.assert_equal(rv.data, b'')129 self.assert_equal(rv.headers['X-Method'], 'HEAD')130131 def test_explicit_head(self):132 app = flask.Flask(__name__)
6 unmodified lines
139140 app.add_url_rule('/', view_func=Index.as_view('index'))141 c = app.test_client()142 rv = c.get('/')143 self.assert_equal(rv.data, 'GET')143 self.assert_equal(rv.data, b'GET')144 rv = c.head('/')145 self.assert_equal(rv.data, '')145 self.assert_equal(rv.data, b'')146 self.assert_equal(rv.headers['X-Method'], 'HEAD')147148 def test_endpoint_override(self):149 app = flask.Flask(__name__)
20 unmodified lines
added:flask/_compat.py+111 added
1# -*- coding: utf-8 -*-2"""3 flask._compat4 ~~~~~~~~~~~~~56 Some py2/py3 compatibility support based on a stripped down7 version of six so we don't have to depend on a specific version8 of it.910 :copyright: (c) 2013 by Armin Ronacher.11 :license: BSD, see LICENSE for more details.12"""13import sys1415PY2 = sys.version_info[0] == 216PYPY = hasattr(sys, 'pypy_translation_info')17_identity = lambda x: x181920if not PY2:21 unichr = chr22 range_type = range23 text_type = str24 string_types = (str,)25 integer_types = (int, )2627 iterkeys = lambda d: iter(d.keys())28 itervalues = lambda d: iter(d.values())29 iteritems = lambda d: iter(d.items())3031 import pickle32 from io import BytesIO, StringIO33 NativeStringIO = StringIO3435 def reraise(tp, value, tb=None):36 if value.__traceback__ is not tb:37 raise value.with_traceback(tb)38 raise value3940 ifilter = filter41 imap = map42 izip = zip43 intern = sys.intern4445 implements_iterator = _identity46 implements_to_string = _identity47 encode_filename = _identity48 get_next = lambda x: x.__next__4950else:51 unichr = unichr52 text_type = unicode53 range_type = xrange54 string_types = (str, unicode)55 integer_types = (int, long)5657 iterkeys = lambda d: d.iterkeys()58 itervalues = lambda d: d.itervalues()59 iteritems = lambda d: d.iteritems()6061 import cPickle as pickle62 from cStringIO import StringIO as BytesIO, StringIO63 NativeStringIO = BytesIO6465 exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')6667 from itertools import imap, izip, ifilter68 intern = intern6970 def implements_iterator(cls):71 cls.next = cls.__next__72 del cls.__next__73 return cls7475 def implements_to_string(cls):76 cls.__unicode__ = cls.__str__77 cls.__str__ = lambda x: x.__unicode__().encode('utf-8')78 return cls7980 get_next = lambda x: x.next8182 def encode_filename(filename):83 if isinstance(filename, unicode):84 return filename.encode('utf-8')85 return filename868788def with_metaclass(meta, *bases):89 # This requires a bit of explanation: the basic idea is to make a90 # dummy metaclass for one level of class instantiation that replaces91 # itself with the actual metaclass. Because of internal type checks92 # we also need to make sure that we downgrade the custom metaclass93 # for one level to something closer to type (that's why __call__ and94 # __init__ comes back from type etc.).95 #96 # This has the advantage over six.with_metaclass in that it does not97 # introduce dummy classes into the final MRO.98 class metaclass(meta):99 __call__ = type.__call__100 __init__ = type.__init__101 def __new__(cls, name, this_bases, d):102 if this_bases is None:103 return type.__new__(cls, name, (), d)104 return meta(name, bases, d)105 return metaclass('temporary_class', None, {})106107108try:109 from urllib.parse import quote_from_bytes as url_quote110except ImportError:111 from urllib import quote as url_quote
modified:flask/app.py+39 added-35 removed
7 unmodified lines
8 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112from __future__ import with_statement1312import os13import sys14from threading import Lock15from datetime import timedelta
17 unmodified lines
33from .templating import DispatchingJinjaLoader, Environment, \34 _default_template_ctx_processor35from .signals import request_started, request_finished, got_request_exception, \36 request_tearing_down, appcontext_tearing_down37from ._compat import reraise, string_types, integer_types3839# a lock used for logger initialization40_logger_lock = Lock()41
134 unmodified lines
176 del _get_request_globals_class, _set_request_globals_class177178 #: The debug flag. Set this to `True` to enable debugging of the179 #: application. In debug mode the debugger will kick in when an unhandled181 #: exception ocurrs and the integrated server will automatically reload180 #: exception occurs and the integrated server will automatically reload181 #: the application if changes in the code are detected.182 #:183 #: This attribute can also be configured from the config with the `DEBUG`184 #: configuration key. Defaults to `False`.
336 unmodified lines
521 def name(self):522 """The name of the application. This is usually the import name523 with the difference that it's guessed from the run file if the524 import name is main. This name is used as a display name when526 Flask needs the name of the application. It can be set and overriden525 Flask needs the name of the application. It can be set and overridden526 to change the value.527528 .. versionadded:: 0.8529 """
53 unmodified lines
583584 @locked_cached_property585 def jinja_env(self):586 """The Jinja2 environment used to load templates."""588 rv = self.create_jinja_environment()587 return self.create_jinja_environment()588590 # Hack to support the init_jinja_globals method which is supported591 # until 1.0 but has an API deficiency.592 if getattr(self.init_jinja_globals, 'im_func', None) is not \593 Flask.init_jinja_globals.im_func:594 from warnings import warn595 warn(DeprecationWarning('This flask class uses a customized '596 'init_jinja_globals() method which is deprecated. '597 'Move the code from that method into the '598 'create_jinja_environment() method instead.'))599 self.__dict__['jinja_env'] = rv600 self.init_jinja_globals()601602 return rv603589 @property590 def got_first_request(self):591 """This attribute is set to `True` if the application started592 handling the first request.
36 unmodified lines
629 writing.630631 :param resource: the name of the resource. To access resources within632 subfolders use forward slashes as separator.633 :param mode: resource file opening mode, default is 'rb'.634 """635 return open(os.path.join(self.instance_path, resource), mode)636637 def create_jinja_environment(self):
58 unmodified lines
696 """Update the template context with some commonly used variables.697 This injects request, session, config and g into the template698 context as well as everything template context processors want699 to inject. Note that the as of Flask 0.6, the original values714 in the context will not be overriden if a context processor700 in the context will not be overridden if a context processor701 decides to return a value with the same key.702703 :param context: the context as a dictionary that is updated in place704 to add extra variables.
339 unmodified lines
1044 return 'This page does not exist', 4041045 app.error_handler_spec[None][404] = page_not_found10461047 Setting error handlers via assignments to :attr:`error_handler_spec`1062 however is discouraged as it requires fidling with nested dictionaries1048 however is discouraged as it requires fiddling with nested dictionaries1049 and the special case for arbitrary exception types.10501051 The first `None` refers to the active blueprint. If the error1052 handler should be application wide `None` shall be used.
22 unmodified lines
1075 @setupmethod1076 def _register_error_handler(self, key, code_or_exception, f):1077 if isinstance(code_or_exception, HTTPException):1078 code_or_exception = code_or_exception.code1093 if isinstance(code_or_exception, (int, long)):1079 if isinstance(code_or_exception, integer_types):1080 assert code_or_exception != 500 or key is None, \1081 'It is currently not possible to register a 500 internal ' \1082 'server error on a per-blueprint level.'1083 self.error_handler_spec.setdefault(key, {})[code_or_exception] = f
38 unmodified lines
1122 @app.template_test()1123 def is_prime(n):1124 if n == 2:1125 return True1140 for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1):1126 for i in range(2, int(math.ceil(math.sqrt(n))) + 1):1127 if n % i == 0:1128 return False1129 return True1130
237 unmodified lines
1368 for typecheck, handler in chain(blueprint_handlers, app_handlers):1369 if isinstance(e, typecheck):1370 return handler(e)13711386 raise exc_type, exc_value, tb1372 reraise(exc_type, exc_value, tb)13731374 def handle_exception(self, e):1375 """Default exception handling that kicks in when an exception1376 occurs that is not caught. In debug mode the exception will
13 unmodified lines
1390 # raise it with the whole traceback in case we can do that1391 # (the function was actually called from the except part)1392 # otherwise, we just raise the error again1393 if exc_value is e:1408 raise exc_type, exc_value, tb1394 reraise(exc_type, exc_value, tb)1395 else:1396 raise e13971398 self.log_exception((exc_type, exc_value, tb))
64 unmodified lines
1463 request_started.send(self)1464 rv = self.preprocess_request()1465 if rv is None:1466 rv = self.dispatch_request()1481 except Exception, e:1467 except Exception as e:1468 rv = self.handle_user_exception(e)1469 response = self.make_response(rv)1470 response = self.process_response(response)1471 request_finished.send(self, response=response)
29 unmodified lines
1501 # fallback for Werkzeug < 0.71502 methods = []1503 try:1504 adapter.match(method='--')1519 except MethodNotAllowed, e:1505 except MethodNotAllowed as e:1506 methods = e.valid_methods1521 except HTTPException, e:1507 except HTTPException as e:1508 pass1509 rv = self.response_class()1510 rv.allow.update(methods)1511 return rv15121513 def should_ignore_error(self, error):1514 """This is called to figure out if an error should be ignored1515 or not as far as the teardown system is concerned. If this1516 function returns `True` then the teardown handlers will not be1517 passed the error.15181519 .. versionadded:: 0.101520 """1521 return False15221523 def make_response(self, rv):1524 """Converts the return value from a view function to a real1525 response object that is an instance of :attr:`response_class`.1526
32 unmodified lines
1559 if not isinstance(rv, self.response_class):1560 # When we create a response object directly, we let the constructor1561 # set the headers and status. We do this because there can be1562 # some extra logic involved when creating these objects with1567 # specific values (like defualt content type selection).1568 if isinstance(rv, basestring):1563 # specific values (like default content type selection).1564 if isinstance(rv, string_types + (bytes, )):1565 rv = self.response_class(rv, headers=headers, status=status)1566 headers = status = None1567 else:1568 rv = self.response_class.force_type(rv, request.environ)15691570 if status is not None:1575 if isinstance(status, basestring):1571 if isinstance(status, string_types):1572 rv.status = status1573 else:1574 rv.status_code = status1575 if headers:
45 unmodified lines
1621 try:1622 rv = handler(error, endpoint, values)1623 if rv is not None:1624 return rv1629 except BuildError, error:1625 except BuildError as error:1626 pass16271628 # At this point we want to reraise the exception. If the error is1629 # still the same one we can reraise it with the original traceback,1630 # otherwise we raise it from here.1631 if error is exc_value:1636 raise exc_type, exc_value, tb1632 reraise(exc_type, exc_value, tb)1633 raise error16341635 def preprocess_request(self):1636 """Called before the actual request dispatching and will
162 unmodified lines
1799 :param start_response: a callable accepting a status code,1800 a list of headers and an optional1801 exception context to start the response1802 """1807 with self.request_context(environ):1803 ctx = self.request_context(environ)1804 ctx.push()1805 error = None1806 try:1807 try:1808 response = self.full_dispatch_request()1810 except Exception, e:1809 except Exception as e:1810 error = e1811 response = self.make_response(self.handle_exception(e))1812 return response(environ, start_response)1813 finally:1814 if self.should_ignore_error(error):1815 error = None1816 ctx.auto_pop(error)18171818 @property1819 def modules(self):1820 from warnings import warn
13 unmodified lines
modified:flask/config.py+5 added-5 removed
7 unmodified lines
8 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112from __future__ import with_statement1312import imp13import os14import errno1516from werkzeug.utils import import_string17from ._compat import string_types181920class ConfigAttribute(object):21 """Makes an attribute forward to the config"""
102 unmodified lines
124 filename = os.path.join(self.root_path, filename)125 d = imp.new_module('config')126 d.__file__ = filename127 try:128 with open(filename) as config_file:129 execfile(filename, d.__dict__)130 except IOError, e:129 exec(compile(config_file.read(), filename, 'exec'), d.__dict__)130 except IOError as e:131 if silent and e.errno in (errno.ENOENT, errno.EISDIR):132 return False133 e.strerror = 'Unable to load configuration file (%s)' % e.strerror134 raise
22 unmodified lines
157 package because the package might be installed system wide.158159 :param obj: an import name or object160 """161 if isinstance(obj, basestring):161 if isinstance(obj, string_types):162 obj = import_string(obj)163 for key in dir(obj):164 if key.isupper():165 self[key] = getattr(obj, key)
3 unmodified lines
modified:flask/ctx.py+13 added-7 removed
279 unmodified lines
280 try:281 url_rule, self.request.view_args = \282 self.url_adapter.match(return_rule=True)283 self.request.url_rule = url_rule284 except HTTPException, e:284 except HTTPException as e:285 self.request.routing_exception = e286287 def push(self):288 """Binds the request context to the current context."""289 # If an exception ocurrs in debug mode or if context preservation is289 # If an exception occurs in debug mode or if context preservation is290 # activated under exception situations exactly one context stays291 # on the stack. The rationale is that you want to access that292 # information under debug situations. However if someone forgets to293 # pop that context again we want to make sure that on the next push
39 unmodified lines
333 self.preserved = False334 if exc is None:335 exc = sys.exc_info()[1]336 self.app.do_teardown_request(exc)337 request_close = getattr(self.request, 'close', None)338 if request_close is not None:339 request_close()340 clear_request = True341342 rv = _request_ctx_stack.pop()343 assert rv is self, 'Popped wrong request context. (%r instead of %r)' \
7 unmodified lines
351 # Get rid of the app as well if necessary.352 if app_ctx is not None:353 app_ctx.pop(exc)354355 def auto_pop(self, exc):356 if self.request.environ.get('flask._preserve_context') or \357 (exc is not None and self.app.preserve_context_on_exception):358 self.preserved = True359 else:360 self.pop(exc)361362 def __enter__(self):363 self.push()364 return self365
2 unmodified lines
368 # exception happened. This will allow the debugger to still369 # access the request object in the interactive shell. Furthermore370 # the context can be force kept alive for the test client.371 # See flask.testing for how this works.362 if self.request.environ.get('flask._preserve_context') or \363 (tb is not None and self.app.preserve_context_on_exception):364 self.preserved = True365 else:366 self.pop(exc_value)372 self.auto_pop(exc_value)373374 def __repr__(self):375 return '<%s \'%s\' [%s] of %s>' % (376 self.__class__.__name__,
4 unmodified lines
modified:flask/debughelpers.py+4 added-2 removed
6 unmodified lines
78 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from ._compat import implements_to_string121314class UnexpectedUnicodeError(AssertionError, UnicodeError):15 """Raised in places where we want some better error reporting for16 unexpected unicode or binary data.17 """181920@implements_to_string21class DebugFilesKeyError(KeyError, AssertionError):22 """Raised from request.files during debugging. The idea is that it can23 provide a better error message than just a generic KeyError/BadRequest.24 """
9 unmodified lines
34 if form_matches:35 buf.append('\n\nThe browser instead transmitted some file names. '36 'This was submitted: %s' % ', '.join('"%s"' % x37 for x in form_matches))36 self.msg = ''.join(buf).encode('utf-8')38 self.msg = ''.join(buf)3940 def __str__(self):41 return self.msg42
34 unmodified lines
77 class newcls(oldcls):78 def __getitem__(self, key):79 try:80 return oldcls.__getitem__(self, key)79 except KeyError, e:81 except KeyError as e:82 if key not in request.form:83 raise84 raise DebugFilesKeyError(request, key)85 newcls.__name__ = oldcls.__name__
2 unmodified lines
modified:flask/exthook.py+2 added-1 removed
19 unmodified lines
20 :license: BSD, see LICENSE for more details.21"""22import sys23import os24from ._compat import reraise252627class ExtensionImporter(object):28 """This importer redirects imports from this submodule to other locations.
48 unmodified lines
77 # If it's an important traceback we reraise it, otherwise78 # we swallow it and try the next choice. The skipped frame79 # is the one from __import__ above which we don't care about80 if self.is_important_traceback(realname, tb):80 raise exc_type, exc_value, tb.tb_next81 reraise(exc_type, exc_value, tb.tb_next)82 continue83 module = sys.modules[fullname] = sys.modules[realname]84 if '.' not in modname:85 setattr(sys.modules[self.wrapper_module], modname, module)
35 unmodified lines
modified:flask/helpers.py+10 added-9 removed
7 unmodified lines
8 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112from __future__ import with_statement1312import os13import sys14import pkgutil15import posixpath
19 unmodified lines
3536from .signals import message_flashed37from .globals import session, _request_ctx_stack, _app_ctx_stack, \38 current_app, request39from ._compat import string_types, text_type404142# sentinel43_missing = object()
82 unmodified lines
126 # the first dummy None is yielded at which point the context was already127 # pushed. This item is discarded. Then when the iteration continues the128 # real generator is executed.129 wrapped_g = generator()131 wrapped_g.next()130 next(wrapped_g)131 return wrapped_g132133134def make_response(*args):
164 unmodified lines
299300 try:301 rv = url_adapter.build(endpoint, values, method=method,302 force_external=external)304 except BuildError, error:303 except BuildError as error:304 # We need to inject the values again so that the app callback can305 # deal with that sort of stuff.306 values['_external'] = external307 values['_anchor'] = anchor
21 unmodified lines
329330 .. versionadded:: 0.2331332 :param template_name: the name of the template334 :param attribute: the name of the variable of macro to acccess333 :param attribute: the name of the variable of macro to access334 """335 return getattr(current_app.jinja_env.get_template(template_name).module,336 attribute)337
59 unmodified lines
397 if flashes is None:398 _request_ctx_stack.top.flashes = flashes = session.pop('_flashes') \399 if '_flashes' in session else []400 if category_filter:402 flashes = filter(lambda f: f[0] in category_filter, flashes)401 flashes = list(filter(lambda f: f[0] in category_filter, flashes))402 if not with_categories:403 return [x[1] for x in flashes]404 return flashes405
58 unmodified lines
464 :meth:`~Flask.get_send_file_max_age` of465 :data:`~flask.current_app`.466 """467 mtime = None469 if isinstance(filename_or_fp, basestring):468 if isinstance(filename_or_fp, string_types):469 filename = filename_or_fp470 file = None471 else:472 from warnings import warn
2 unmodified lines
475476 # XXX: this behavior is now deprecated because it was unreliable.477 # removed in Flask 1.0478 if not attachment_filename and not mimetype \480 and isinstance(filename, basestring):479 and isinstance(filename, string_types):480 warn(DeprecationWarning('The filename support for file objects '481 'passed to send_file is now deprecated. Pass an '482 'attach_filename if you want mimetypes to be guessed.'),483 stacklevel=2)
31 unmodified lines
515 else:516 if file is None:517 file = open(filename, 'rb')518 mtime = os.path.getmtime(filename)519 headers['Content-Length'] = os.path.getsize(filename)520 data = wrap_file(request.environ, file)521522 rv = current_app.response_class(data, mimetype=mimetype, headers=headers,523 direct_passthrough=True)
14 unmodified lines
538 rv.set_etag('flask-%s-%s-%s' % (539 os.path.getmtime(filename),540 os.path.getsize(filename),541 adler32(542 filename.encode('utf-8') if isinstance(filename, unicode)542 filename.encode('utf-8') if isinstance(filename, text_type)543 else filename544 ) & 0xffffffff545 ))546 if conditional:
291 unmodified lines
838 do_something_with(contents)839840 :param resource: the name of the resource. To access resources within841 subfolders use forward slashes as separator.842 :param mode: resource file opening mode, default is 'rb'.843 """844 if mode not in ('r', 'rb'):845 raise ValueError('Resources can only be opened for reading')846 return open(os.path.join(self.root_path, resource), mode)
modified:flask/json.py+33 added-7 removed
6 unmodified lines
78 :copyright: (c) 2012 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import io12import uuid13from datetime import datetime14from .globals import current_app, request15from ._compat import text_type, PY21617from werkzeug.http import http_date1819# Use the same json implementation as itsdangerous on which we18# depend anyways. This name changed at one point so support both.20# depend anyways.21try:22 from itsdangerous import simplejson as _json23except ImportError:24 from itsdangerous import json as _json
8 unmodified lines
33 'htmlsafe_dumps', 'JSONDecoder', 'JSONEncoder',34 'jsonify']353637def _wrap_reader_for_text(fp, encoding):38 if isinstance(fp.read(0), bytes):39 fp = io.TextIOWrapper(io.BufferedReader(fp), encoding)40 return fp414243def _wrap_writer_for_text(fp, encoding):44 try:45 fp.write('')46 except TypeError:47 fp = io.TextIOWrapper(fp, encoding)48 return fp495051class JSONEncoder(_json.JSONEncoder):52 """The default Flask JSON encoder. This one extends the default simplejson53 encoder by also supporting ``datetime`` objects, ``UUID`` as well as54 ``Markup`` objects which are serialized as RFC 822 datetime strings (same
22 unmodified lines
77 return http_date(o)78 if isinstance(o, uuid.UUID):79 return str(o)80 if hasattr(o, '__html__'):65 return unicode(o.__html__())81 return text_type(o.__html__())82 return _json.JSONEncoder.default(self, o)838485class JSONDecoder(_json.JSONDecoder):
28 unmodified lines
114 default is controlled by the ``JSON_AS_ASCII`` configuration variable115 and can be overriden by the simplejson ``ensure_ascii`` parameter.116 """117 _dump_arg_defaults(kwargs)118 encoding = kwargs.pop('encoding', None)102 return _json.dumps(obj, **kwargs)119 rv = _json.dumps(obj, **kwargs)120 if encoding is not None and isinstance(rv, text_type):121 rv = rv.encode(encoding)122 return rv123124125def dump(obj, fp, **kwargs):126 """Like :func:`dumps` but writes into a file object."""127 _dump_arg_defaults(kwargs)128 encoding = kwargs.pop('encoding', None)129 if encoding is not None:130 fp = _wrap_writer_for_text(fp, encoding)108 return _json.dump(obj, fp, **kwargs)131 _json.dump(obj, fp, **kwargs)132133134def loads(s, **kwargs):135 """Unserialize a JSON object from a string ``s`` by using the application's136 configured decoder (:attr:`~flask.Flask.json_decoder`) if there is an137 application on the stack.138 """139 _load_arg_defaults(kwargs)140 if isinstance(s, bytes):141 s = s.decode(kwargs.pop('encoding', None) or 'utf-8')142 return _json.loads(s, **kwargs)143144145def load(fp, **kwargs):146 """Like :func:`loads` but reads from a file object.147 """148 _load_arg_defaults(kwargs)149 if not PY2:150 fp = _wrap_reader_for_text(fp, kwargs.pop('encoding', None) or 'utf-8')151 return _json.load(fp, **kwargs)152153154def htmlsafe_dumps(obj, **kwargs):
18 unmodified lines
173 the given arguments with an `application/json` mimetype. The arguments174 to this function are the same as to the :class:`dict` constructor.175176 Example usage::150 177178 from flask import jsonify179180 @app.route('/_get_current_user')181 def get_current_user():
8 unmodified lines
190 "email": "admin@localhost",191 "id": 42192 }193167 This requires Python 2.6 or an installed version of simplejson. For168 security reasons only objects are supported toplevel. For more194 For security reasons only objects are supported toplevel. For more195 information about this, have a look at :ref:`json-security`.196197 .. versionadded:: 0.2198 """
3 unmodified lines
modified:flask/sessions.py+5 added-4 removed
13 unmodified lines
14from datetime import datetime15from werkzeug.http import http_date, parse_date16from werkzeug.datastructures import CallbackDict17from . import Markup, json18from ._compat import iteritems, text_type1920from itsdangerous import URLSafeTimedSerializer, BadSignature2122
39 unmodified lines
62 return {' t': [_tag(x) for x in value]}63 elif isinstance(value, uuid.UUID):64 return {' u': value.hex}65 elif callable(getattr(value, '__html__', None)):65 return {' m': unicode(value.__html__())}66 return {' m': text_type(value.__html__())}67 elif isinstance(value, list):68 return [_tag(x) for x in value]69 elif isinstance(value, datetime):70 return {' d': http_date(value)}71 elif isinstance(value, dict):71 return dict((k, _tag(v)) for k, v in value.iteritems())72 return dict((k, _tag(v)) for k, v in iteritems(value))73 elif isinstance(value, str):74 try:74 return unicode(value)75 return text_type(value)76 except UnicodeError:77 raise UnexpectedUnicodeError(u'A byte string with '78 u'non-ASCII data was passed to the session system '79 u'which can only store unicode strings. Consider '
4 unmodified lines
84 def loads(self, value):85 def object_hook(obj):86 if len(obj) != 1:87 return obj87 the_key, the_value = obj.iteritems().next()88 the_key, the_value = next(iteritems(obj))89 if the_key == ' t':90 return tuple(the_value)91 elif the_key == ' u':92 return uuid.UUID(the_value)
235 unmodified lines
modified:flask/templating.py+3 added-2 removed
13 unmodified lines
1415from .globals import _request_ctx_stack, _app_ctx_stack16from .signals import template_rendered17from .module import blueprint_is_module18from ._compat import itervalues, iteritems192021def _default_template_ctx_processor():22 """Default template context processor. Injects `request`,
56 unmodified lines
79 yield loader, local_name80 except (ValueError, KeyError):81 pass8282 for blueprint in self.app.blueprints.itervalues():83 for blueprint in itervalues(self.app.blueprints):84 if blueprint_is_module(blueprint):85 continue86 loader = blueprint.jinja_loader87 if loader is not None:
4 unmodified lines
92 loader = self.app.jinja_loader93 if loader is not None:94 result.update(loader.list_templates())9595 for name, blueprint in self.app.blueprints.iteritems():96 for name, blueprint in iteritems(self.app.blueprints):97 loader = blueprint.jinja_loader98 if loader is not None:99 for template in loader.list_templates():100 prefix = ''
43 unmodified lines
modified:flask/testing.py+6 added-4 removed
8 unmodified lines
9 :copyright: (c) 2011 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213from __future__ import with_statement1413from contextlib import contextmanager14from werkzeug.test import Client, EnvironBuilder15from flask import _request_ctx_stack18from urlparse import urlparse1617try:18 from werkzeug.urls import url_parse19except ImportError:20 from urlparse import urlsplit as url_parse212223def make_test_environ_builder(app, path='/', base_url=None, *args, **kwargs):24 """Creates a new test builder with some application defaults thrown in."""25 http_host = app.config.get('SERVER_NAME')26 app_root = app.config.get('APPLICATION_ROOT')27 if base_url is None:26 url = urlparse(path)28 url = url_parse(path)29 base_url = 'http://%s/' % (url.netloc or http_host or 'localhost')30 if app_root:31 base_url += app_root.lstrip('/')32 if url.netloc:
92 unmodified lines
modified:flask/views.py+2 added-3 removed
7 unmodified lines
8 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from .globals import request12from ._compat import with_metaclass131415http_method_funcs = frozenset(['get', 'post', 'head', 'options',16 'delete', 'put', 'trace', 'patch'])
102 unmodified lines
119 rv.methods = sorted(methods)120 return rv121122122class MethodView(View):123class MethodView(with_metaclass(MethodViewType, View)):124 """Like a regular class-based view but that dispatches requests to125 particular methods. For instance if you implement a method called126 :meth:`get` it means you will response to ``'GET'`` requests and127 the :meth:`dispatch_request` implementation will automatically
10 unmodified lines
138 return 'OK'139140 app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))141 """141 __metaclass__ = MethodViewType142142 def dispatch_request(self, *args, **kwargs):143 meth = getattr(self, request.method.lower(), None)144 # if the request method is HEAD and we don't have a handler for it145 # retry with GET
4 unmodified lines
modified:flask/wrappers.py+1 added-3 removed
90 unmodified lines
91 @cached_property92 def json(self):93 """If the mimetype is `application/json` this will contain the94 parsed JSON data. Otherwise this will be `None`.9596 This requires Python 2.6 or an installed version of simplejson.95 """96 if self.mimetype == 'application/json':97 request_charset = self.mimetype_params.get('charset')98 try:99 if request_charset is not None:100 return json.loads(self.data, encoding=request_charset)101 return json.loads(self.data)104 except ValueError, e:102 except ValueError as e:103 return self.on_json_loading_failed(e)104105 def on_json_loading_failed(self, e):106 """Called if decoding of the JSON data failed. The return value of
33 unmodified lines
modified:scripts/flask-07-upgrade.py+1 added-3 removed
285 unmodified lines
286 if not args:287 args = ['.']288289 if ast is None:290 parser.error('Python 2.6 or later is required to run the upgrade script.\n'291 'The runtime requirements for Flask 0.7 however are still '292 'Python 2.5.')290 parser.error('Python 2.6 or later is required to run the upgrade script.')291292 for path in args:293 scan_path(path, teardown=not options.no_teardown)294
3 unmodified lines
modified:scripts/flaskext_test.py-2 removed
7 unmodified lines
8 :copyright: (c) 2010 by Ali Afshar.9 :license: BSD, see LICENSE for more details.10"""1112from __future__ import with_statement1312import os13import sys14import shutil15import urllib2
294 unmodified lines
modified:.travis.yml+1 added-6 removed
2 unmodified lines
3python:4 - 2.65 - 2.76 - pypy7 - 3.389install: pip install --editable .1011script: make test
6 unmodified lines
18 # Disable travis notifications until they figured out how to hide19 # their own builder failure from us. Travis currently fails way20 # too many times by itself.21 email: false2122 irc:23 channels:24 - "irc.freenode.org#pocoo"25 use_notice: true26 skip_join: true
modified:CHANGES+5 added
55 unmodified lines
56 greenlets.57- Removed custom JSON HTTP exception subclasses. If you were relying on them58 you can reintroduce them again yourself trivially. Using them however is59 strongly discouraged as the interface was flawed.60- Python requirements changed: requiring Python 2.6 or 2.7 now to prepare61 for Python 3.3 port.62- Changed how the teardown system is informed about exceptions. This is now63 more reliable in case something handles an exception halfway through64 the error handling process.6566Version 0.967-----------68
365 unmodified lines
modified:Makefile+4 added-1 removed
1.PHONY: clean-pyc ext-test test test-with-mem upload-docs docs audit1.PHONY: clean-pyc ext-test test tox-test test-with-mem upload-docs docs audit23all: clean-pyc test45test:6 python run-tests.py78tox-test:9 tox1011test-with-mem:12 RUN_FLASK_MEMORY_TESTS=1 python run-tests.py1314audit:
32 unmodified lines
modified:setup.py+5 added-5 removed
36 unmodified lines
37* `development version38 <http://github.com/mitsuhiko/flask/zipball/master#egg=Flask-dev>`_3940"""41from __future__ import print_function42from setuptools import Command, setup4344class run_audit(Command):45 """Audits source code using PyFlakes for following issues:
13 unmodified lines
59 import os, sys60 try:61 import pyflakes.scripts.pyflakes as flakes62 except ImportError:62 print "Audit requires PyFlakes installed in your system."63 print("Audit requires PyFlakes installed in your system.")64 sys.exit(-1)6566 warns = 067 # Define top-level directories
3 unmodified lines
71 for file in files:72 if file != '__init__.py' and file.endswith('.py') :73 warns += flakes.checkPath(os.path.join(root, file))74 if warns > 0:74 print "Audit finished with total %d warnings." % warns75 print("Audit finished with total %d warnings." % warns)76 else:76 print "No problems found in sourcecode."77 print("No problems found in sourcecode.")7879setup(80 name='Flask',81 version='0.10-dev',
10 unmodified lines
92 platforms='any',93 install_requires=[94 'Werkzeug>=0.7',95 'Jinja2>=2.4',95 'itsdangerous>=0.17'96 'itsdangerous>=0.21'97 ],98 classifiers=[99 'Development Status :: 4 - Beta',100 'Environment :: Web Environment',101 'Intended Audience :: Developers',102 'License :: OSI Approved :: BSD License',103 'Operating System :: OS Independent',104 'Programming Language :: Python',104 'Programming Language :: Python :: 2.5',105 'Programming Language :: Python :: 2.6',106 'Programming Language :: Python :: 2.7',107 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',108 'Topic :: Software Development :: Libraries :: Python Modules'
4 unmodified lines
added:tox.ini+6 added
1[tox]2envlist = py26, py27, pypy, py3334[testenv]5deps = -egit+git://github.com/mitsuhiko/werkzeug.git@sprint-branch#egg=werkzeug6commands = python run-tests.py []