From 6caaa8a527134dc9aff6d5c442969e96f9c00f21 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Sat, 18 May 2013 16:24:40 +0200 Subject: [PATCH 01/58] automated change using python-modernize: use 'as' in except --- flask/app.py | 10 +++++----- flask/config.py | 2 +- flask/ctx.py | 2 +- flask/debughelpers.py | 2 +- flask/helpers.py | 2 +- flask/testsuite/__init__.py | 2 +- flask/testsuite/basic.py | 20 ++++++++++---------- flask/testsuite/blueprints.py | 4 ++-- flask/testsuite/config.py | 8 ++++---- flask/testsuite/reqctx.py | 6 +++--- flask/testsuite/testing.py | 4 ++-- flask/wrappers.py | 2 +- 12 files changed, 32 insertions(+), 32 deletions(-) diff --git a/flask/app.py b/flask/app.py index cc9a2f90..3204e13f 100644 --- a/flask/app.py +++ b/flask/app.py @@ -1478,7 +1478,7 @@ class Flask(_PackageBoundObject): rv = self.preprocess_request() if rv is None: rv = self.dispatch_request() - except Exception, e: + except Exception as e: rv = self.handle_user_exception(e) response = self.make_response(rv) response = self.process_response(response) @@ -1516,9 +1516,9 @@ class Flask(_PackageBoundObject): methods = [] try: adapter.match(method='--') - except MethodNotAllowed, e: + except MethodNotAllowed as e: methods = e.valid_methods - except HTTPException, e: + except HTTPException as e: pass rv = self.response_class() rv.allow.update(methods) @@ -1626,7 +1626,7 @@ class Flask(_PackageBoundObject): rv = handler(error, endpoint, values) if rv is not None: return rv - except BuildError, error: + except BuildError as error: pass # At this point we want to reraise the exception. If the error is @@ -1807,7 +1807,7 @@ class Flask(_PackageBoundObject): with self.request_context(environ): try: response = self.full_dispatch_request() - except Exception, e: + except Exception as e: response = self.make_response(self.handle_exception(e)) return response(environ, start_response) diff --git a/flask/config.py b/flask/config.py index 759fd488..80e9983e 100644 --- a/flask/config.py +++ b/flask/config.py @@ -127,7 +127,7 @@ class Config(dict): d.__file__ = filename try: execfile(filename, d.__dict__) - except IOError, e: + except IOError as e: if silent and e.errno in (errno.ENOENT, errno.EISDIR): return False e.strerror = 'Unable to load configuration file (%s)' % e.strerror diff --git a/flask/ctx.py b/flask/ctx.py index 6b271687..a02c9a86 100644 --- a/flask/ctx.py +++ b/flask/ctx.py @@ -279,7 +279,7 @@ class RequestContext(object): url_rule, self.request.view_args = \ self.url_adapter.match(return_rule=True) self.request.url_rule = url_rule - except HTTPException, e: + except HTTPException as e: self.request.routing_exception = e def push(self): diff --git a/flask/debughelpers.py b/flask/debughelpers.py index 3ebd2f3e..504fab93 100644 --- a/flask/debughelpers.py +++ b/flask/debughelpers.py @@ -76,7 +76,7 @@ def attach_enctype_error_multidict(request): def __getitem__(self, key): try: return oldcls.__getitem__(self, key) - except KeyError, e: + except KeyError as e: if key not in request.form: raise raise DebugFilesKeyError(request, key) diff --git a/flask/helpers.py b/flask/helpers.py index d24dde6b..d68cb04b 100644 --- a/flask/helpers.py +++ b/flask/helpers.py @@ -301,7 +301,7 @@ def url_for(endpoint, **values): try: rv = url_adapter.build(endpoint, values, method=method, force_external=external) - except BuildError, error: + except BuildError as error: # We need to inject the values again so that the app callback can # deal with that sort of stuff. values['_external'] = external diff --git a/flask/testsuite/__init__.py b/flask/testsuite/__init__.py index 5d86fa3d..084b3726 100644 --- a/flask/testsuite/__init__.py +++ b/flask/testsuite/__init__.py @@ -220,5 +220,5 @@ def main(): """Runs the testsuite as command line application.""" try: unittest.main(testLoader=BetterLoader(), defaultTest='suite') - except Exception, e: + except Exception as e: print 'Error: %s' % e diff --git a/flask/testsuite/basic.py b/flask/testsuite/basic.py index 5f6dbe4b..2836a1b6 100644 --- a/flask/testsuite/basic.py +++ b/flask/testsuite/basic.py @@ -256,7 +256,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): def expect_exception(f, *args, **kwargs): try: f(*args, **kwargs) - except RuntimeError, e: + except RuntimeError as e: self.assert_(e.args and 'session is unavailable' in e.args[0]) else: self.assert_(False, 'expected exception') @@ -629,7 +629,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): c = app.test_client() try: c.get('/fail') - except KeyError, e: + except KeyError as e: self.assert_(isinstance(e, BadRequest)) else: self.fail('Expected exception') @@ -645,7 +645,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): c = app.test_client() try: c.get('/fail') - except NotFound, e: + except NotFound as e: pass else: self.fail('Expected exception') @@ -664,7 +664,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): with app.test_client() as c: try: c.post('/fail', data={'foo': 'index.txt'}) - except DebugFilesKeyError, e: + except DebugFilesKeyError as e: self.assert_('no file contents were transmitted' in str(e)) self.assert_('This was submitted: "index.txt"' in str(e)) else: @@ -755,7 +755,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): try: with app.test_request_context(): flask.url_for('spam') - except BuildError, error: + except BuildError as error: pass try: raise RuntimeError('Test case where BuildError is not current.') @@ -802,7 +802,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): return None try: app.test_client().get('/') - except ValueError, e: + except ValueError as e: self.assert_equal(str(e), 'View function did not return a response') pass else: @@ -843,7 +843,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): rv = app.test_client().get('/', 'https://localhost.localdomain') # Werkzeug 0.8 self.assert_equal(rv.status_code, 404) - except ValueError, e: + except ValueError as e: # Werkzeug 0.7 self.assert_equal(str(e), "the server name provided " + "('localhost.localdomain:443') does not match the " + \ @@ -854,7 +854,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): rv = app.test_client().get('/', 'http://foo.localhost') # Werkzeug 0.8 self.assert_equal(rv.status_code, 404) - except ValueError, e: + except ValueError as e: # Werkzeug 0.7 self.assert_equal(str(e), "the server name provided " + \ "('localhost.localdomain') does not match the " + \ @@ -975,7 +975,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): @app.route('/foo') def broken(): return 'Meh' - except AssertionError, e: + except AssertionError as e: self.assert_('A setup function was called' in str(e)) else: self.fail('Expected exception') @@ -1009,7 +1009,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): with app.test_client() as c: try: c.post('/foo', data={}) - except AssertionError, e: + except AssertionError as e: self.assert_('http://localhost/foo/' in str(e)) self.assert_('Make sure to directly send your POST-request ' 'to this URL' in str(e)) diff --git a/flask/testsuite/blueprints.py b/flask/testsuite/blueprints.py index ea047918..0399d48e 100644 --- a/flask/testsuite/blueprints.py +++ b/flask/testsuite/blueprints.py @@ -183,7 +183,7 @@ class ModuleTestCase(FlaskTestCase): with app.test_request_context(): try: flask.render_template('missing.html') - except TemplateNotFound, e: + except TemplateNotFound as e: self.assert_equal(e.name, 'missing.html') else: self.assert_(0, 'expected exception') @@ -378,7 +378,7 @@ class BlueprintTestCase(FlaskTestCase): with app.test_request_context(): try: flask.render_template('missing.html') - except TemplateNotFound, e: + except TemplateNotFound as e: self.assert_equal(e.name, 'missing.html') else: self.assert_(0, 'expected exception') diff --git a/flask/testsuite/config.py b/flask/testsuite/config.py index bf72925b..0b2c65bd 100644 --- a/flask/testsuite/config.py +++ b/flask/testsuite/config.py @@ -57,7 +57,7 @@ class ConfigTestCase(FlaskTestCase): app = flask.Flask(__name__) try: app.config.from_envvar('FOO_SETTINGS') - except RuntimeError, e: + except RuntimeError as e: self.assert_("'FOO_SETTINGS' is not set" in str(e)) else: self.assert_(0, 'expected exception') @@ -76,7 +76,7 @@ class ConfigTestCase(FlaskTestCase): try: app = flask.Flask(__name__) app.config.from_envvar('FOO_SETTINGS') - except IOError, e: + except IOError as e: msg = str(e) self.assert_(msg.startswith('[Errno 2] Unable to load configuration ' 'file (No such file or directory):')) @@ -91,7 +91,7 @@ class ConfigTestCase(FlaskTestCase): app = flask.Flask(__name__) try: app.config.from_pyfile('missing.cfg') - except IOError, e: + except IOError as e: msg = str(e) self.assert_(msg.startswith('[Errno 2] Unable to load configuration ' 'file (No such file or directory):')) @@ -141,7 +141,7 @@ class InstanceTestCase(FlaskTestCase): here = os.path.abspath(os.path.dirname(__file__)) try: flask.Flask(__name__, instance_path='instance') - except ValueError, e: + except ValueError as e: self.assert_('must be absolute' in str(e)) else: self.fail('Expected value error') diff --git a/flask/testsuite/reqctx.py b/flask/testsuite/reqctx.py index a93523e7..89a47728 100644 --- a/flask/testsuite/reqctx.py +++ b/flask/testsuite/reqctx.py @@ -58,7 +58,7 @@ class RequestContextTestCase(FlaskTestCase): try: with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}): pass - except Exception, e: + except Exception as e: self.assert_(isinstance(e, ValueError)) self.assert_equal(str(e), "the server name provided " + "('localhost.localdomain:5000') does not match the " + \ @@ -68,7 +68,7 @@ class RequestContextTestCase(FlaskTestCase): app.config.update(SERVER_NAME='localhost') with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}): pass - except ValueError, e: + except ValueError as e: raise ValueError( "No ValueError exception should have been raised \"%s\"" % e ) @@ -77,7 +77,7 @@ class RequestContextTestCase(FlaskTestCase): app.config.update(SERVER_NAME='localhost:80') with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}): pass - except ValueError, e: + except ValueError as e: raise ValueError( "No ValueError exception should have been raised \"%s\"" % e ) diff --git a/flask/testsuite/testing.py b/flask/testsuite/testing.py index 92e3f267..605078a7 100644 --- a/flask/testsuite/testing.py +++ b/flask/testsuite/testing.py @@ -106,7 +106,7 @@ class TestToolsTestCase(FlaskTestCase): try: with c.session_transaction() as sess: pass - except RuntimeError, e: + except RuntimeError as e: self.assert_('Session backend did not open a session' in str(e)) else: self.fail('Expected runtime error') @@ -130,7 +130,7 @@ class TestToolsTestCase(FlaskTestCase): try: with c.session_transaction() as s: pass - except RuntimeError, e: + except RuntimeError as e: self.assert_('cookies' in str(e)) else: self.fail('Expected runtime error') diff --git a/flask/wrappers.py b/flask/wrappers.py index a56fe5d7..717d8ce5 100644 --- a/flask/wrappers.py +++ b/flask/wrappers.py @@ -101,7 +101,7 @@ class Request(RequestBase): if request_charset is not None: return json.loads(self.data, encoding=request_charset) return json.loads(self.data) - except ValueError, e: + except ValueError as e: return self.on_json_loading_failed(e) def on_json_loading_failed(self, e): From b52b7b1f9322e7ab3e69a387dbfe9fe14de4c401 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Sat, 18 May 2013 16:31:40 +0200 Subject: [PATCH 02/58] automated change using python-modernize: replace execfile --- flask/config.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flask/config.py b/flask/config.py index 759fd488..55aef029 100644 --- a/flask/config.py +++ b/flask/config.py @@ -126,7 +126,7 @@ class Config(dict): d = imp.new_module('config') d.__file__ = filename try: - execfile(filename, d.__dict__) + exec(compile(open(filename).read(), filename, 'exec'), d.__dict__) except IOError, e: if silent and e.errno in (errno.ENOENT, errno.EISDIR): return False From b8b769ad41edeb2320774d88502dd998df272397 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Sat, 18 May 2013 16:39:39 +0200 Subject: [PATCH 03/58] automated change using python-modernize: fix methodattrs --- flask/app.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flask/app.py b/flask/app.py index cc9a2f90..b7826420 100644 --- a/flask/app.py +++ b/flask/app.py @@ -590,7 +590,7 @@ class Flask(_PackageBoundObject): # Hack to support the init_jinja_globals method which is supported # until 1.0 but has an API deficiency. if getattr(self.init_jinja_globals, 'im_func', None) is not \ - Flask.init_jinja_globals.im_func: + Flask.init_jinja_globals.__func__: from warnings import warn warn(DeprecationWarning('This flask class uses a customized ' 'init_jinja_globals() method which is deprecated. ' From 40fad2ece80e8bf6784e137028645fa66a3cd9c2 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Sat, 18 May 2013 17:06:25 +0200 Subject: [PATCH 04/58] document python 2.6 minimum requirement, remove all stuff that refers to 2.5 --- .travis.yml | 1 - CHANGES | 2 ++ docs/extensiondev.rst | 2 +- docs/installation.rst | 2 +- docs/patterns/jquery.rst | 4 ---- docs/tutorial/dbinit.rst | 7 ++----- flask/json.py | 3 +-- flask/wrappers.py | 2 -- scripts/flask-07-upgrade.py | 4 +--- setup.py | 1 - 10 files changed, 8 insertions(+), 20 deletions(-) diff --git a/.travis.yml b/.travis.yml index fd590bea..307945bf 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,6 @@ language: python python: - - 2.5 - 2.6 - 2.7 - pypy diff --git a/CHANGES b/CHANGES index e383b56f..af3c4752 100644 --- a/CHANGES +++ b/CHANGES @@ -54,6 +54,8 @@ Release date to be decided. - Added `message_flashed` signal that simplifies flashing testing. - Added support for copying of request contexts for better working with greenlets. +- Python requirements changed: requiring Python 2.6 or 2.7 now to prepare + for Python 3.3 port. Version 0.9 ----------- diff --git a/docs/extensiondev.rst b/docs/extensiondev.rst index 0615e4db..09bf2d2c 100644 --- a/docs/extensiondev.rst +++ b/docs/extensiondev.rst @@ -390,7 +390,7 @@ extension to be approved you have to follow these guidelines: (``PackageName==dev``). 9. The ``zip_safe`` flag in the setup script must be set to ``False``, even if the extension would be safe for zipping. -10. An extension currently has to support Python 2.5, 2.6 as well as +10. An extension currently has to support Python 2.6 as well as Python 2.7 diff --git a/docs/installation.rst b/docs/installation.rst index 5e4673dd..16475383 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -13,7 +13,7 @@ So how do you get all that on your computer quickly? There are many ways you could do that, but the most kick-ass method is virtualenv, so let's have a look at that first. -You will need Python 2.5 or higher to get started, so be sure to have an +You will need Python 2.6 or higher to get started, so be sure to have an up-to-date Python 2.x installation. Python 3.x is not supported. .. _virtualenv: diff --git a/docs/patterns/jquery.rst b/docs/patterns/jquery.rst index 1bd49533..7aaa2803 100644 --- a/docs/patterns/jquery.rst +++ b/docs/patterns/jquery.rst @@ -11,11 +11,7 @@ Python primitives (numbers, strings, dicts and lists) look like which is widely supported and very easy to parse. It became popular a few years ago and quickly replaced XML as transport format in web applications. -If you have Python 2.6 JSON will work out of the box, in Python 2.5 you -will have to install the `simplejson`_ library from PyPI. - .. _jQuery: http://jquery.com/ -.. _simplejson: http://pypi.python.org/pypi/simplejson Loading jQuery -------------- diff --git a/docs/tutorial/dbinit.rst b/docs/tutorial/dbinit.rst index 6415cdaa..b32a8eda 100644 --- a/docs/tutorial/dbinit.rst +++ b/docs/tutorial/dbinit.rst @@ -21,12 +21,9 @@ errors. It's a good idea to add a function that initializes the database for you to the application. If you want to do that, you first have to import the -:func:`contextlib.closing` function from the contextlib package. If you -want to use Python 2.5 it's also necessary to enable the `with` statement -first (`__future__` imports must be the very first import). Accordingly, -add the following lines to your existing imports in `flaskr.py`:: +:func:`contextlib.closing` function from the contextlib package. +Accordingly, add the following lines to your existing imports in `flaskr.py`:: - from __future__ import with_statement from contextlib import closing Next we can create a function called `init_db` that initializes the diff --git a/flask/json.py b/flask/json.py index 717eb2ab..52e5680e 100644 --- a/flask/json.py +++ b/flask/json.py @@ -161,8 +161,7 @@ def jsonify(*args, **kwargs): "id": 42 } - This requires Python 2.6 or an installed version of simplejson. For - security reasons only objects are supported toplevel. For more + For security reasons only objects are supported toplevel. For more information about this, have a look at :ref:`json-security`. .. versionadded:: 0.2 diff --git a/flask/wrappers.py b/flask/wrappers.py index a56fe5d7..d348ee0a 100644 --- a/flask/wrappers.py +++ b/flask/wrappers.py @@ -92,8 +92,6 @@ class Request(RequestBase): def json(self): """If the mimetype is `application/json` this will contain the parsed JSON data. Otherwise this will be `None`. - - This requires Python 2.6 or an installed version of simplejson. """ if self.mimetype == 'application/json': request_charset = self.mimetype_params.get('charset') diff --git a/scripts/flask-07-upgrade.py b/scripts/flask-07-upgrade.py index 4027d8ce..e1017e69 100644 --- a/scripts/flask-07-upgrade.py +++ b/scripts/flask-07-upgrade.py @@ -287,9 +287,7 @@ def main(): args = ['.'] if ast is None: - parser.error('Python 2.6 or later is required to run the upgrade script.\n' - 'The runtime requirements for Flask 0.7 however are still ' - 'Python 2.5.') + parser.error('Python 2.6 or later is required to run the upgrade script.') for path in args: scan_path(path, teardown=not options.no_teardown) diff --git a/setup.py b/setup.py index 2f9c95ca..ba5f4a67 100644 --- a/setup.py +++ b/setup.py @@ -101,7 +101,6 @@ setup( 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', - 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', From 1b753cb1b1764de5bf3afe1f96032362208febc6 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Sat, 18 May 2013 17:47:40 +0200 Subject: [PATCH 05/58] require 'six' in setup.py, add flask._compat for stuff not yet in 'six' --- flask/_compat.py | 13 +++++++++++++ setup.py | 1 + 2 files changed, 14 insertions(+) create mode 100644 flask/_compat.py diff --git a/flask/_compat.py b/flask/_compat.py new file mode 100644 index 00000000..3743a54c --- /dev/null +++ b/flask/_compat.py @@ -0,0 +1,13 @@ +# -*- coding: utf-8 -*- +""" + flask._compat + ~~~~~~~~~~~~~ + + Some py2/py3 compatibility support that is not yet available in + "six" 1.3.0. + There are bugs open for "six" for all this stuff, so we can remove it + again from here as soon as we require a new enough "six" release. + + :copyright: (c) 2013 by Armin Ronacher. + :license: BSD, see LICENSE for more details. +""" diff --git a/setup.py b/setup.py index 2f9c95ca..e25d435f 100644 --- a/setup.py +++ b/setup.py @@ -90,6 +90,7 @@ setup( zip_safe=False, platforms='any', install_requires=[ + 'six>=1.3.0', 'Werkzeug>=0.7', 'Jinja2>=2.4', 'itsdangerous>=0.17' From cfbfff2d2692a94bdb29133c2e7bb6b792cb337d Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Sat, 18 May 2013 17:57:43 +0200 Subject: [PATCH 06/58] python-modernize automated changes: misc. minor stuff --- flask/testsuite/__init__.py | 3 ++- flask/testsuite/config.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/flask/testsuite/__init__.py b/flask/testsuite/__init__.py index 5d86fa3d..7938a784 100644 --- a/flask/testsuite/__init__.py +++ b/flask/testsuite/__init__.py @@ -10,6 +10,7 @@ :license: BSD, see LICENSE for more details. """ +from __future__ import print_function from __future__ import with_statement import os @@ -221,4 +222,4 @@ def main(): try: unittest.main(testLoader=BetterLoader(), defaultTest='suite') except Exception, e: - print 'Error: %s' % e + print('Error: %s' % e) diff --git a/flask/testsuite/config.py b/flask/testsuite/config.py index bf72925b..2027f578 100644 --- a/flask/testsuite/config.py +++ b/flask/testsuite/config.py @@ -113,7 +113,7 @@ class LimitedLoaderMockWrapper(object): def __getattr__(self, name): if name in ('archive', 'get_filename'): msg = 'Mocking a loader which does not have `%s.`' % name - raise AttributeError, msg + raise AttributeError(msg) return getattr(self.loader, name) From 0f8c47c988fbecc30785959065a53e00861c8558 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Sat, 18 May 2013 18:00:15 +0200 Subject: [PATCH 07/58] python-modernize automated changes: fix_dict --- flask/sessions.py | 3 ++- flask/templating.py | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/flask/sessions.py b/flask/sessions.py index 31b5900b..3746da7f 100644 --- a/flask/sessions.py +++ b/flask/sessions.py @@ -17,6 +17,7 @@ from werkzeug.datastructures import CallbackDict from . import Markup, json from itsdangerous import URLSafeTimedSerializer, BadSignature +import six def total_seconds(td): @@ -68,7 +69,7 @@ class TaggedJSONSerializer(object): elif isinstance(value, datetime): return {' d': http_date(value)} elif isinstance(value, dict): - return dict((k, _tag(v)) for k, v in value.iteritems()) + return dict((k, _tag(v)) for k, v in six.iteritems(value)) elif isinstance(value, str): try: return unicode(value) diff --git a/flask/templating.py b/flask/templating.py index 2cc09c4d..754c6893 100644 --- a/flask/templating.py +++ b/flask/templating.py @@ -15,6 +15,7 @@ from jinja2 import BaseLoader, Environment as BaseEnvironment, \ from .globals import _request_ctx_stack, _app_ctx_stack from .signals import template_rendered from .module import blueprint_is_module +import six def _default_template_ctx_processor(): @@ -79,7 +80,7 @@ class DispatchingJinjaLoader(BaseLoader): except (ValueError, KeyError): pass - for blueprint in self.app.blueprints.itervalues(): + for blueprint in six.itervalues(self.app.blueprints): if blueprint_is_module(blueprint): continue loader = blueprint.jinja_loader @@ -92,7 +93,7 @@ class DispatchingJinjaLoader(BaseLoader): if loader is not None: result.update(loader.list_templates()) - for name, blueprint in self.app.blueprints.iteritems(): + for name, blueprint in six.iteritems(self.app.blueprints): loader = blueprint.jinja_loader if loader is not None: for template in loader.list_templates(): From dcd052366b43df7bfe730c2e991ff37c617ba52b Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Sat, 18 May 2013 18:03:37 +0200 Subject: [PATCH 08/58] python-modernize automated changes: fix_next --- flask/helpers.py | 3 ++- flask/sessions.py | 2 +- flask/testsuite/helpers.py | 3 ++- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/flask/helpers.py b/flask/helpers.py index d24dde6b..a302995c 100644 --- a/flask/helpers.py +++ b/flask/helpers.py @@ -26,6 +26,7 @@ from functools import update_wrapper from werkzeug.datastructures import Headers from werkzeug.exceptions import NotFound +import six # this was moved in 0.7 try: @@ -128,7 +129,7 @@ def stream_with_context(generator_or_function): # pushed. This item is discarded. Then when the iteration continues the # real generator is executed. wrapped_g = generator() - wrapped_g.next() + six.advance_iterator(wrapped_g) return wrapped_g diff --git a/flask/sessions.py b/flask/sessions.py index 3746da7f..b8e37014 100644 --- a/flask/sessions.py +++ b/flask/sessions.py @@ -85,7 +85,7 @@ class TaggedJSONSerializer(object): def object_hook(obj): if len(obj) != 1: return obj - the_key, the_value = obj.iteritems().next() + the_key, the_value = six.advance_iterator(obj.iteritems()) if the_key == ' t': return tuple(the_value) elif the_key == ' u': diff --git a/flask/testsuite/helpers.py b/flask/testsuite/helpers.py index fdf2d89f..5604f85f 100644 --- a/flask/testsuite/helpers.py +++ b/flask/testsuite/helpers.py @@ -18,6 +18,7 @@ from logging import StreamHandler from StringIO import StringIO from flask.testsuite import FlaskTestCase, catch_warnings, catch_stderr from werkzeug.http import parse_cache_control_header, parse_options_header +import six def has_encoding(name): @@ -507,7 +508,7 @@ class StreamingTestCase(FlaskTestCase): def close(self): called.append(42) def next(self): - return self._gen.next() + return six.advance_iterator(self._gen) @app.route('/') def index(): def generate(): From 522cd0009367d1f775b0e978681426773f51ce14 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Sat, 18 May 2013 18:12:30 +0200 Subject: [PATCH 09/58] python-modernize automated changes: fix_unicode (but without six.u()) --- flask/json.py | 3 ++- flask/sessions.py | 4 ++-- flask/testsuite/basic.py | 3 ++- flask/testsuite/blueprints.py | 3 ++- flask/testsuite/helpers.py | 6 +++--- flask/testsuite/testing.py | 3 ++- 6 files changed, 13 insertions(+), 9 deletions(-) diff --git a/flask/json.py b/flask/json.py index 717eb2ab..dee2e189 100644 --- a/flask/json.py +++ b/flask/json.py @@ -17,6 +17,7 @@ from werkzeug.http import http_date # Use the same json implementation as itsdangerous on which we # depend anyways. from itsdangerous import simplejson as _json +import six # figure out if simplejson escapes slashes. This behavior was changed @@ -59,7 +60,7 @@ class JSONEncoder(_json.JSONEncoder): if isinstance(o, uuid.UUID): return str(o) if hasattr(o, '__html__'): - return unicode(o.__html__()) + return six.text_type(o.__html__()) return _json.JSONEncoder.default(self, o) diff --git a/flask/sessions.py b/flask/sessions.py index b8e37014..04b7f8af 100644 --- a/flask/sessions.py +++ b/flask/sessions.py @@ -63,7 +63,7 @@ class TaggedJSONSerializer(object): elif isinstance(value, uuid.UUID): return {' u': value.hex} elif callable(getattr(value, '__html__', None)): - return {' m': unicode(value.__html__())} + return {' m': six.text_type(value.__html__())} elif isinstance(value, list): return [_tag(x) for x in value] elif isinstance(value, datetime): @@ -72,7 +72,7 @@ class TaggedJSONSerializer(object): return dict((k, _tag(v)) for k, v in six.iteritems(value)) elif isinstance(value, str): try: - return unicode(value) + return six.text_type(value) except UnicodeError: raise UnexpectedUnicodeError(u'A byte string with ' u'non-ASCII data was passed to the session system ' diff --git a/flask/testsuite/basic.py b/flask/testsuite/basic.py index 5f6dbe4b..7cdf2211 100644 --- a/flask/testsuite/basic.py +++ b/flask/testsuite/basic.py @@ -22,6 +22,7 @@ from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning from werkzeug.exceptions import BadRequest, NotFound from werkzeug.http import parse_date from werkzeug.routing import BuildError +import six class BasicFunctionalityTestCase(FlaskTestCase): @@ -277,7 +278,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): @app.route('/test') def test(): - return unicode(flask.session.permanent) + return six.text_type(flask.session.permanent) client = app.test_client() rv = client.get('/') diff --git a/flask/testsuite/blueprints.py b/flask/testsuite/blueprints.py index ea047918..97426c8e 100644 --- a/flask/testsuite/blueprints.py +++ b/flask/testsuite/blueprints.py @@ -18,6 +18,7 @@ from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning from werkzeug.exceptions import NotFound from werkzeug.http import parse_cache_control_header from jinja2 import TemplateNotFound +import six # import moduleapp here because it uses deprecated features and we don't @@ -304,7 +305,7 @@ class BlueprintTestCase(FlaskTestCase): @bp.route('/bar') def bar(bar): - return unicode(bar) + return six.text_type(bar) app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23}) diff --git a/flask/testsuite/helpers.py b/flask/testsuite/helpers.py index 5604f85f..ac618538 100644 --- a/flask/testsuite/helpers.py +++ b/flask/testsuite/helpers.py @@ -36,7 +36,7 @@ class JSONTestCase(FlaskTestCase): app = flask.Flask(__name__) @app.route('/json', methods=['POST']) def return_json(): - return unicode(flask.request.json) + return six.text_type(flask.request.json) c = app.test_client() rv = c.post('/json', data='malformed', content_type='application/json') self.assert_equal(rv.status_code, 400) @@ -45,7 +45,7 @@ class JSONTestCase(FlaskTestCase): app = flask.Flask(__name__) @app.route('/json', methods=['POST']) def return_json(): - return unicode(flask.request.json) + return six.text_type(flask.request.json) c = app.test_client() rv = c.post('/json', data='malformed', content_type='application/json') self.assert_equal(rv.status_code, 400) @@ -97,7 +97,7 @@ class JSONTestCase(FlaskTestCase): app = flask.Flask(__name__) @app.route('/add', methods=['POST']) def add(): - return unicode(flask.request.json['a'] + flask.request.json['b']) + return six.text_type(flask.request.json['a'] + flask.request.json['b']) c = app.test_client() rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}), content_type='application/json') diff --git a/flask/testsuite/testing.py b/flask/testsuite/testing.py index 92e3f267..92be9d33 100644 --- a/flask/testsuite/testing.py +++ b/flask/testsuite/testing.py @@ -14,6 +14,7 @@ from __future__ import with_statement import flask import unittest from flask.testsuite import FlaskTestCase +import six class TestToolsTestCase(FlaskTestCase): @@ -85,7 +86,7 @@ class TestToolsTestCase(FlaskTestCase): @app.route('/') def index(): - return unicode(flask.session['foo']) + return six.text_type(flask.session['foo']) with app.test_client() as c: with c.session_transaction() as sess: From 323a840c5ab39e1df889d93ad0da28c5bd553c57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Sat, 18 May 2013 18:27:49 +0200 Subject: [PATCH 10/58] Add tox.ini --- tox.ini | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 tox.ini diff --git a/tox.ini b/tox.ini new file mode 100644 index 00000000..56c8f393 --- /dev/null +++ b/tox.ini @@ -0,0 +1,5 @@ +[tox] +envlist = py26, py27, pypy, py33 + +[testenv] +commands = python run-tests.py [] From aba1d3a5074953702f1ddc9fe623d2a724dd6570 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Sat, 18 May 2013 18:28:59 +0200 Subject: [PATCH 11/58] Test on 3.3 on travis --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 307945bf..f17e99b8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,6 +4,7 @@ python: - 2.6 - 2.7 - pypy + - 3.3 before_install: pip install simplejson From 287905e67c2f22df3c3055a0cca025931726cd02 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Sat, 18 May 2013 18:39:10 +0200 Subject: [PATCH 12/58] py3 compat: use six.reload_module --- flask/testsuite/ext.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/flask/testsuite/ext.py b/flask/testsuite/ext.py index 034ab5be..096a70f8 100644 --- a/flask/testsuite/ext.py +++ b/flask/testsuite/ext.py @@ -13,7 +13,7 @@ from __future__ import with_statement import sys import unittest from flask.testsuite import FlaskTestCase - +from six import reload_module class ExtImportHookTestCase(FlaskTestCase): @@ -29,7 +29,7 @@ class ExtImportHookTestCase(FlaskTestCase): entry == 'flaskext') and value is not None: sys.modules.pop(entry, None) from flask import ext - reload(ext) + reload_module(ext) # reloading must not add more hooks import_hooks = 0 From c618db92d6059ab1262ea2450b0f81a94cdad901 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Sat, 18 May 2013 18:55:36 +0200 Subject: [PATCH 13/58] reload_module is in six.moves --- flask/testsuite/ext.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flask/testsuite/ext.py b/flask/testsuite/ext.py index 096a70f8..6f6a34f4 100644 --- a/flask/testsuite/ext.py +++ b/flask/testsuite/ext.py @@ -13,7 +13,7 @@ from __future__ import with_statement import sys import unittest from flask.testsuite import FlaskTestCase -from six import reload_module +from six.moves import reload_module class ExtImportHookTestCase(FlaskTestCase): From 506db0eab2bf9e514177d8b46e2708f10601cf36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Sat, 18 May 2013 19:00:06 +0200 Subject: [PATCH 14/58] Use print_function --- setup.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/setup.py b/setup.py index 4ad0b546..1d3e36ad 100644 --- a/setup.py +++ b/setup.py @@ -38,6 +38,7 @@ Links `_ """ +from __future__ import print_function from setuptools import Command, setup class run_audit(Command): @@ -59,7 +60,7 @@ class run_audit(Command): try: import pyflakes.scripts.pyflakes as flakes except ImportError: - print "Audit requires PyFlakes installed in your system." + print("Audit requires PyFlakes installed in your system.") sys.exit(-1) warns = 0 @@ -71,9 +72,9 @@ class run_audit(Command): if file != '__init__.py' and file.endswith('.py') : warns += flakes.checkPath(os.path.join(root, file)) if warns > 0: - print "Audit finished with total %d warnings." % warns + print("Audit finished with total %d warnings." % warns) else: - print "No problems found in sourcecode." + print("No problems found in sourcecode.") setup( name='Flask', From ceb7c7f7717c13cdb9c6d2eccb135a9edc71eef7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Sat, 18 May 2013 19:05:10 +0200 Subject: [PATCH 15/58] Don't notify IRC for this branch --- .travis.yml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/.travis.yml b/.travis.yml index f17e99b8..33027fef 100644 --- a/.travis.yml +++ b/.travis.yml @@ -19,9 +19,3 @@ notifications: # their own builder failure from us. Travis currently fails way # too many times by itself. email: false - - irc: - channels: - - "irc.freenode.org#pocoo" - use_notice: true - skip_join: true From a503520ac51d16558ce91f7d7fc9d30a910d928c Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Tue, 21 May 2013 23:34:25 +0200 Subject: [PATCH 16/58] copy _compat.py from flask in here (and adapt docstring) --- flask/_compat.py | 104 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 100 insertions(+), 4 deletions(-) diff --git a/flask/_compat.py b/flask/_compat.py index 3743a54c..776a2dd7 100644 --- a/flask/_compat.py +++ b/flask/_compat.py @@ -3,11 +3,107 @@ flask._compat ~~~~~~~~~~~~~ - Some py2/py3 compatibility support that is not yet available in - "six" 1.3.0. - There are bugs open for "six" for all this stuff, so we can remove it - again from here as soon as we require a new enough "six" release. + Some py2/py3 compatibility support based on a stripped down + version of six so we don't have to depend on a specific version + of it. :copyright: (c) 2013 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ +import sys + +PY2 = sys.version_info[0] == 2 +PYPY = hasattr(sys, 'pypy_translation_info') +_identity = lambda x: x + + +if not PY2: + unichr = chr + range_type = range + text_type = str + string_types = (str,) + + iterkeys = lambda d: iter(d.keys()) + itervalues = lambda d: iter(d.values()) + iteritems = lambda d: iter(d.items()) + + import pickle + from io import BytesIO, StringIO + NativeStringIO = StringIO + + def reraise(tp, value, tb=None): + if value.__traceback__ is not tb: + raise value.with_traceback(tb) + raise value + + ifilter = filter + imap = map + izip = zip + intern = sys.intern + + implements_iterator = _identity + implements_to_string = _identity + encode_filename = _identity + get_next = lambda x: x.__next__ + +else: + unichr = unichr + text_type = unicode + range_type = xrange + string_types = (str, unicode) + + iterkeys = lambda d: d.iterkeys() + itervalues = lambda d: d.itervalues() + iteritems = lambda d: d.iteritems() + + import cPickle as pickle + from cStringIO import StringIO as BytesIO, StringIO + NativeStringIO = BytesIO + + exec('def reraise(tp, value, tb=None):\n raise tp, value, tb') + + from itertools import imap, izip, ifilter + intern = intern + + def implements_iterator(cls): + cls.next = cls.__next__ + del cls.__next__ + return cls + + def implements_to_string(cls): + cls.__unicode__ = cls.__str__ + cls.__str__ = lambda x: x.__unicode__().encode('utf-8') + return cls + + get_next = lambda x: x.next + + def encode_filename(filename): + if isinstance(filename, unicode): + return filename.encode('utf-8') + return filename + + +def with_metaclass(meta, *bases): + # This requires a bit of explanation: the basic idea is to make a + # dummy metaclass for one level of class instanciation that replaces + # itself with the actual metaclass. Because of internal type checks + # we also need to make sure that we downgrade the custom metaclass + # for one level to something closer to type (that's why __call__ and + # __init__ comes back from type etc.). + # + # This has the advantage over six.with_metaclass in that it does not + # introduce dummy classes into the final MRO. + class metaclass(meta): + __call__ = type.__call__ + __init__ = type.__init__ + def __new__(cls, name, this_bases, d): + if this_bases is None: + return type.__new__(cls, name, (), d) + return meta(name, bases, d) + return metaclass('temporary_class', None, {}) + + +try: + from urllib.parse import quote_from_bytes as url_quote +except ImportError: + from urllib import quote as url_quote From e1d356fb713f3272db2a23f9f898c34c5dc79dc0 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Wed, 22 May 2013 01:33:04 +0200 Subject: [PATCH 17/58] ported some more stuff to py 3.3 removed init_jinja_globals hack from app.py after consulting mitsuhiko (didn't work on py 3.3 "as is") removed with_statement future imports, not needed any more needs more work on 2.7 as well as on 3.3 --- examples/flaskr/flaskr.py | 2 +- examples/minitwit/minitwit.py | 2 +- flask/_compat.py | 6 ++++++ flask/app.py | 33 +++++++++------------------------ flask/config.py | 5 ++--- flask/exthook.py | 3 ++- flask/helpers.py | 9 ++++----- flask/testing.py | 4 +--- flask/testsuite/__init__.py | 5 ++--- flask/testsuite/appctx.py | 2 -- flask/testsuite/basic.py | 4 +--- flask/testsuite/blueprints.py | 2 -- flask/testsuite/config.py | 1 - flask/testsuite/deprecations.py | 19 +------------------ flask/testsuite/ext.py | 5 ++--- flask/testsuite/helpers.py | 4 +--- flask/testsuite/regression.py | 4 +--- flask/testsuite/reqctx.py | 2 -- flask/testsuite/signals.py | 1 - flask/testsuite/subclassing.py | 2 +- flask/testsuite/templating.py | 2 -- flask/testsuite/testing.py | 2 -- flask/testsuite/views.py | 2 +- scripts/flaskext_test.py | 2 -- 24 files changed, 36 insertions(+), 87 deletions(-) diff --git a/examples/flaskr/flaskr.py b/examples/flaskr/flaskr.py index 0647fc7b..20254660 100644 --- a/examples/flaskr/flaskr.py +++ b/examples/flaskr/flaskr.py @@ -9,7 +9,7 @@ :copyright: (c) 2010 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ -from __future__ import with_statement + from sqlite3 import dbapi2 as sqlite3 from flask import Flask, request, session, g, redirect, url_for, abort, \ render_template, flash, _app_ctx_stack diff --git a/examples/minitwit/minitwit.py b/examples/minitwit/minitwit.py index a92da6af..2863de50 100644 --- a/examples/minitwit/minitwit.py +++ b/examples/minitwit/minitwit.py @@ -8,7 +8,7 @@ :copyright: (c) 2010 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ -from __future__ import with_statement + import time from sqlite3 import dbapi2 as sqlite3 from hashlib import md5 diff --git a/flask/_compat.py b/flask/_compat.py index 776a2dd7..27f61137 100644 --- a/flask/_compat.py +++ b/flask/_compat.py @@ -22,6 +22,7 @@ if not PY2: range_type = range text_type = str string_types = (str,) + integer_types = (int, ) iterkeys = lambda d: iter(d.keys()) itervalues = lambda d: iter(d.values()) @@ -46,11 +47,14 @@ if not PY2: encode_filename = _identity get_next = lambda x: x.__next__ + from urllib.parse import urlparse + else: unichr = unichr text_type = unicode range_type = xrange string_types = (str, unicode) + integer_types = (int, long) iterkeys = lambda d: d.iterkeys() itervalues = lambda d: d.itervalues() @@ -82,6 +86,8 @@ else: return filename.encode('utf-8') return filename + from urlparse import urlparse + def with_metaclass(meta, *bases): # This requires a bit of explanation: the basic idea is to make a diff --git a/flask/app.py b/flask/app.py index 0337c608..dc684489 100644 --- a/flask/app.py +++ b/flask/app.py @@ -9,8 +9,6 @@ :license: BSD, see LICENSE for more details. """ -from __future__ import with_statement - import os import sys from threading import Lock @@ -36,6 +34,7 @@ from .templating import DispatchingJinjaLoader, Environment, \ _default_template_ctx_processor from .signals import request_started, request_finished, got_request_exception, \ request_tearing_down, appcontext_tearing_down +from flask._compat import reraise, string_types, integer_types # a lock used for logger initialization _logger_lock = Lock() @@ -585,21 +584,7 @@ class Flask(_PackageBoundObject): @locked_cached_property def jinja_env(self): """The Jinja2 environment used to load templates.""" - rv = self.create_jinja_environment() - - # Hack to support the init_jinja_globals method which is supported - # until 1.0 but has an API deficiency. - if getattr(self.init_jinja_globals, 'im_func', None) is not \ - Flask.init_jinja_globals.__func__: - from warnings import warn - warn(DeprecationWarning('This flask class uses a customized ' - 'init_jinja_globals() method which is deprecated. ' - 'Move the code from that method into the ' - 'create_jinja_environment() method instead.')) - self.__dict__['jinja_env'] = rv - self.init_jinja_globals() - - return rv + return self.create_jinja_environment() @property def got_first_request(self): @@ -1090,7 +1075,7 @@ class Flask(_PackageBoundObject): def _register_error_handler(self, key, code_or_exception, f): if isinstance(code_or_exception, HTTPException): code_or_exception = code_or_exception.code - if isinstance(code_or_exception, (int, long)): + if isinstance(code_or_exception, integer_types): assert code_or_exception != 500 or key is None, \ 'It is currently not possible to register a 500 internal ' \ 'server error on a per-blueprint level.' @@ -1137,7 +1122,7 @@ class Flask(_PackageBoundObject): def is_prime(n): if n == 2: return True - for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1): + for i in range(2, int(math.ceil(math.sqrt(n))) + 1): if n % i == 0: return False return True @@ -1383,7 +1368,7 @@ class Flask(_PackageBoundObject): if isinstance(e, typecheck): return handler(e) - raise exc_type, exc_value, tb + reraise(exc_type, exc_value, tb) def handle_exception(self, e): """Default exception handling that kicks in when an exception @@ -1405,7 +1390,7 @@ class Flask(_PackageBoundObject): # (the function was actually called from the except part) # otherwise, we just raise the error again if exc_value is e: - raise exc_type, exc_value, tb + reraise(exc_type, exc_value, tb) else: raise e @@ -1565,14 +1550,14 @@ class Flask(_PackageBoundObject): # set the headers and status. We do this because there can be # some extra logic involved when creating these objects with # specific values (like defualt content type selection). - if isinstance(rv, basestring): + if isinstance(rv, string_types): rv = self.response_class(rv, headers=headers, status=status) headers = status = None else: rv = self.response_class.force_type(rv, request.environ) if status is not None: - if isinstance(status, basestring): + if isinstance(status, string_types): rv.status = status else: rv.status_code = status @@ -1633,7 +1618,7 @@ class Flask(_PackageBoundObject): # still the same one we can reraise it with the original traceback, # otherwise we raise it from here. if error is exc_value: - raise exc_type, exc_value, tb + reraise(exc_type, exc_value, tb) raise error def preprocess_request(self): diff --git a/flask/config.py b/flask/config.py index 3afe623a..ddb113a5 100644 --- a/flask/config.py +++ b/flask/config.py @@ -9,13 +9,12 @@ :license: BSD, see LICENSE for more details. """ -from __future__ import with_statement - import imp import os import errno from werkzeug.utils import import_string +from flask._compat import string_types class ConfigAttribute(object): @@ -158,7 +157,7 @@ class Config(dict): :param obj: an import name or object """ - if isinstance(obj, basestring): + if isinstance(obj, string_types): obj = import_string(obj) for key in dir(obj): if key.isupper(): diff --git a/flask/exthook.py b/flask/exthook.py index 26578f0f..89dac47b 100644 --- a/flask/exthook.py +++ b/flask/exthook.py @@ -21,6 +21,7 @@ """ import sys import os +from flask._compat import reraise class ExtensionImporter(object): @@ -77,7 +78,7 @@ class ExtensionImporter(object): # we swallow it and try the next choice. The skipped frame # is the one from __import__ above which we don't care about if self.is_important_traceback(realname, tb): - raise exc_type, exc_value, tb.tb_next + reraise(exc_type, exc_value, tb.tb_next) continue module = sys.modules[fullname] = sys.modules[realname] if '.' not in modname: diff --git a/flask/helpers.py b/flask/helpers.py index 68ebc74e..1359bba6 100644 --- a/flask/helpers.py +++ b/flask/helpers.py @@ -9,8 +9,6 @@ :license: BSD, see LICENSE for more details. """ -from __future__ import with_statement - import os import sys import pkgutil @@ -27,6 +25,7 @@ from functools import update_wrapper from werkzeug.datastructures import Headers from werkzeug.exceptions import NotFound import six +from flask._compat import string_types, text_type # this was moved in 0.7 try: @@ -467,7 +466,7 @@ def send_file(filename_or_fp, mimetype=None, as_attachment=False, :data:`~flask.current_app`. """ mtime = None - if isinstance(filename_or_fp, basestring): + if isinstance(filename_or_fp, string_types): filename = filename_or_fp file = None else: @@ -478,7 +477,7 @@ def send_file(filename_or_fp, mimetype=None, as_attachment=False, # XXX: this behavior is now deprecated because it was unreliable. # removed in Flask 1.0 if not attachment_filename and not mimetype \ - and isinstance(filename, basestring): + and isinstance(filename, string_types): warn(DeprecationWarning('The filename support for file objects ' 'passed to send_file is now deprecated. Pass an ' 'attach_filename if you want mimetypes to be guessed.'), @@ -540,7 +539,7 @@ def send_file(filename_or_fp, mimetype=None, as_attachment=False, os.path.getmtime(filename), os.path.getsize(filename), adler32( - filename.encode('utf-8') if isinstance(filename, unicode) + filename.encode('utf-8') if isinstance(filename, text_type) else filename ) & 0xffffffff )) diff --git a/flask/testing.py b/flask/testing.py index bdd3860f..ef116cf3 100644 --- a/flask/testing.py +++ b/flask/testing.py @@ -10,12 +10,10 @@ :license: BSD, see LICENSE for more details. """ -from __future__ import with_statement - from contextlib import contextmanager from werkzeug.test import Client, EnvironBuilder from flask import _request_ctx_stack -from urlparse import urlparse +from flask._compat import urlparse def make_test_environ_builder(app, path='/', base_url=None, *args, **kwargs): diff --git a/flask/testsuite/__init__.py b/flask/testsuite/__init__.py index 9027369c..82fa3232 100644 --- a/flask/testsuite/__init__.py +++ b/flask/testsuite/__init__.py @@ -11,17 +11,16 @@ """ from __future__ import print_function -from __future__ import with_statement import os import sys import flask import warnings import unittest -from StringIO import StringIO from functools import update_wrapper from contextlib import contextmanager from werkzeug.utils import import_string, find_modules +from flask._compat import reraise, StringIO def add_to_path(path): @@ -159,7 +158,7 @@ class _ExceptionCatcher(object): self.test_case.fail('Expected exception of type %r' % exception_name) elif not issubclass(exc_type, self.exc_type): - raise exc_type, exc_value, tb + reraise(exc_type, exc_value, tb) return True diff --git a/flask/testsuite/appctx.py b/flask/testsuite/appctx.py index aa71e11e..afed923a 100644 --- a/flask/testsuite/appctx.py +++ b/flask/testsuite/appctx.py @@ -9,8 +9,6 @@ :license: BSD, see LICENSE for more details. """ -from __future__ import with_statement - import flask import unittest from flask.testsuite import FlaskTestCase diff --git a/flask/testsuite/basic.py b/flask/testsuite/basic.py index 89159a16..974b4ebc 100644 --- a/flask/testsuite/basic.py +++ b/flask/testsuite/basic.py @@ -9,8 +9,6 @@ :license: BSD, see LICENSE for more details. """ -from __future__ import with_statement - import re import uuid import flask @@ -1060,7 +1058,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): 1/0 c = app.test_client() - for x in xrange(3): + for x in range(3): with self.assert_raises(ZeroDivisionError): c.get('/fail') diff --git a/flask/testsuite/blueprints.py b/flask/testsuite/blueprints.py index eba43e63..331854a6 100644 --- a/flask/testsuite/blueprints.py +++ b/flask/testsuite/blueprints.py @@ -9,8 +9,6 @@ :license: BSD, see LICENSE for more details. """ -from __future__ import with_statement - import flask import unittest import warnings diff --git a/flask/testsuite/config.py b/flask/testsuite/config.py index ca142cff..415d8aca 100644 --- a/flask/testsuite/config.py +++ b/flask/testsuite/config.py @@ -8,7 +8,6 @@ :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ -from __future__ import with_statement import os import sys diff --git a/flask/testsuite/deprecations.py b/flask/testsuite/deprecations.py index 795a5d3d..56371822 100644 --- a/flask/testsuite/deprecations.py +++ b/flask/testsuite/deprecations.py @@ -9,30 +9,13 @@ :license: BSD, see LICENSE for more details. """ -from __future__ import with_statement - import flask import unittest from flask.testsuite import FlaskTestCase, catch_warnings class DeprecationsTestCase(FlaskTestCase): - - def test_init_jinja_globals(self): - class MyFlask(flask.Flask): - def init_jinja_globals(self): - self.jinja_env.globals['foo'] = '42' - - with catch_warnings() as log: - app = MyFlask(__name__) - @app.route('/') - def foo(): - return app.jinja_env.globals['foo'] - - c = app.test_client() - self.assert_equal(c.get('/').data, '42') - self.assert_equal(len(log), 1) - self.assert_('init_jinja_globals' in str(log[0]['message'])) + """not used currently""" def suite(): diff --git a/flask/testsuite/ext.py b/flask/testsuite/ext.py index 6f6a34f4..147e23b0 100644 --- a/flask/testsuite/ext.py +++ b/flask/testsuite/ext.py @@ -8,7 +8,6 @@ :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ -from __future__ import with_statement import sys import unittest @@ -22,7 +21,7 @@ class ExtImportHookTestCase(FlaskTestCase): # that a real flaskext could be in there which would disable our # fake package. Secondly we want to make sure that the flaskext # import hook does not break on reloading. - for entry, value in sys.modules.items(): + for entry, value in list(sys.modules.items()): if (entry.startswith('flask.ext.') or entry.startswith('flask_') or entry.startswith('flaskext.') or @@ -100,7 +99,7 @@ class ExtImportHookTestCase(FlaskTestCase): self.assert_equal(test_function(), 42) def test_flaskext_broken_package_no_module_caching(self): - for x in xrange(2): + for x in range(2): with self.assert_raises(ImportError): import flask.ext.broken diff --git a/flask/testsuite/helpers.py b/flask/testsuite/helpers.py index ac618538..2808a409 100644 --- a/flask/testsuite/helpers.py +++ b/flask/testsuite/helpers.py @@ -9,16 +9,14 @@ :license: BSD, see LICENSE for more details. """ -from __future__ import with_statement - import os import flask import unittest from logging import StreamHandler -from StringIO import StringIO from flask.testsuite import FlaskTestCase, catch_warnings, catch_stderr from werkzeug.http import parse_cache_control_header, parse_options_header import six +from flask._compat import StringIO def has_encoding(name): diff --git a/flask/testsuite/regression.py b/flask/testsuite/regression.py index 00219856..b8140d6f 100644 --- a/flask/testsuite/regression.py +++ b/flask/testsuite/regression.py @@ -9,8 +9,6 @@ :license: BSD, see LICENSE for more details. """ -from __future__ import with_statement - import os import gc import sys @@ -77,7 +75,7 @@ class MemoryTestCase(FlaskTestCase): if sys.version_info >= (2, 7) and \ not hasattr(sys, 'pypy_translation_info'): with self.assert_no_leak(): - for x in xrange(10): + for x in range(10): fire() def test_safe_join_toplevel_pardir(self): diff --git a/flask/testsuite/reqctx.py b/flask/testsuite/reqctx.py index 89a47728..0f0282e5 100644 --- a/flask/testsuite/reqctx.py +++ b/flask/testsuite/reqctx.py @@ -9,8 +9,6 @@ :license: BSD, see LICENSE for more details. """ -from __future__ import with_statement - import flask import unittest try: diff --git a/flask/testsuite/signals.py b/flask/testsuite/signals.py index 0e5d0cea..637c2c66 100644 --- a/flask/testsuite/signals.py +++ b/flask/testsuite/signals.py @@ -8,7 +8,6 @@ :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ -from __future__ import with_statement import flask import unittest diff --git a/flask/testsuite/subclassing.py b/flask/testsuite/subclassing.py index 89aa9150..3e8d75c1 100644 --- a/flask/testsuite/subclassing.py +++ b/flask/testsuite/subclassing.py @@ -11,9 +11,9 @@ """ import flask import unittest -from StringIO import StringIO from logging import StreamHandler from flask.testsuite import FlaskTestCase +from flask._compat import StringIO class FlaskSubclassingTestCase(FlaskTestCase): diff --git a/flask/testsuite/templating.py b/flask/testsuite/templating.py index 635210f7..c8d1dd22 100644 --- a/flask/testsuite/templating.py +++ b/flask/testsuite/templating.py @@ -9,8 +9,6 @@ :license: BSD, see LICENSE for more details. """ -from __future__ import with_statement - import flask import unittest from flask.testsuite import FlaskTestCase diff --git a/flask/testsuite/testing.py b/flask/testsuite/testing.py index 2872ecdc..a37f6e6c 100644 --- a/flask/testsuite/testing.py +++ b/flask/testsuite/testing.py @@ -9,8 +9,6 @@ :license: BSD, see LICENSE for more details. """ -from __future__ import with_statement - import flask import unittest from flask.testsuite import FlaskTestCase diff --git a/flask/testsuite/views.py b/flask/testsuite/views.py index f09c1266..6c3ae816 100644 --- a/flask/testsuite/views.py +++ b/flask/testsuite/views.py @@ -8,7 +8,7 @@ :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ -from __future__ import with_statement + import flask import flask.views import unittest diff --git a/scripts/flaskext_test.py b/scripts/flaskext_test.py index d1d5d991..5b0d9d22 100644 --- a/scripts/flaskext_test.py +++ b/scripts/flaskext_test.py @@ -9,8 +9,6 @@ :license: BSD, see LICENSE for more details. """ -from __future__ import with_statement - import os import sys import shutil From da5edad23a13336d218ee08f9b8843f611aded07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Wed, 22 May 2013 16:19:57 +0200 Subject: [PATCH 18/58] Use werkzeug@sprint-branch in tox --- tox.ini | 1 + 1 file changed, 1 insertion(+) diff --git a/tox.ini b/tox.ini index 56c8f393..161e86fb 100644 --- a/tox.ini +++ b/tox.ini @@ -2,4 +2,5 @@ envlist = py26, py27, pypy, py33 [testenv] +deps = -egit+git://github.com/mitsuhiko/werkzeug.git@sprint-branch#egg=werkzeug commands = python run-tests.py [] From 884aad8ecebe309d3b17502ecaa64008d2b461e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Wed, 22 May 2013 16:33:05 +0200 Subject: [PATCH 19/58] Test using itsdangerous with 3.x support --- tox.ini | 1 + 1 file changed, 1 insertion(+) diff --git a/tox.ini b/tox.ini index 161e86fb..c699ac48 100644 --- a/tox.ini +++ b/tox.ini @@ -3,4 +3,5 @@ envlist = py26, py27, pypy, py33 [testenv] deps = -egit+git://github.com/mitsuhiko/werkzeug.git@sprint-branch#egg=werkzeug + -egit+git://github.com/mitsuhiko/itsdangerous.git#egg=itsdangerous commands = python run-tests.py [] From 3f51a09db4673c45f19cf1dcdbe04212ac7de890 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Wed, 22 May 2013 16:33:50 +0200 Subject: [PATCH 20/58] itsdangerous uses json instead of simplejson now --- flask/json.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flask/json.py b/flask/json.py index d5da4f91..6b95fde0 100644 --- a/flask/json.py +++ b/flask/json.py @@ -16,7 +16,7 @@ from werkzeug.http import http_date # Use the same json implementation as itsdangerous on which we # depend anyways. -from itsdangerous import simplejson as _json +from itsdangerous import json as _json import six From 05f66ad73543db207791ea5d6a2de2e8eaaf1640 Mon Sep 17 00:00:00 2001 From: Markus Unterwaditzer Date: Wed, 22 May 2013 17:05:48 +0200 Subject: [PATCH 21/58] Fix some literals --- flask/testsuite/basic.py | 111 +++++++++++++++++----------------- flask/testsuite/blueprints.py | 74 +++++++++++------------ flask/testsuite/helpers.py | 16 ++--- flask/testsuite/regression.py | 4 +- flask/testsuite/reqctx.py | 4 +- flask/testsuite/signals.py | 4 +- flask/testsuite/templating.py | 16 ++--- flask/testsuite/testing.py | 8 +-- flask/testsuite/views.py | 14 ++--- 9 files changed, 125 insertions(+), 126 deletions(-) diff --git a/flask/testsuite/basic.py b/flask/testsuite/basic.py index 974b4ebc..1636bee7 100644 --- a/flask/testsuite/basic.py +++ b/flask/testsuite/basic.py @@ -32,7 +32,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): return 'Hello World' rv = app.test_client().open('/', method='OPTIONS') self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST']) - self.assert_equal(rv.data, '') + self.assert_equal(rv.data, b'') def test_options_on_multiple_rules(self): app = flask.Flask(__name__) @@ -72,15 +72,15 @@ class BasicFunctionalityTestCase(FlaskTestCase): return flask.request.method c = app.test_client() - self.assert_equal(c.get('/').data, 'GET') + self.assert_equal(c.get('/').data, b'GET') rv = c.post('/') self.assert_equal(rv.status_code, 405) self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS']) rv = c.head('/') self.assert_equal(rv.status_code, 200) self.assert_(not rv.data) # head truncates - self.assert_equal(c.post('/more').data, 'POST') - self.assert_equal(c.get('/more').data, 'GET') + self.assert_equal(c.post('/more').data, b'POST') + self.assert_equal(c.get('/more').data, b'GET') rv = c.delete('/more') self.assert_equal(rv.status_code, 405) self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST']) @@ -96,15 +96,15 @@ class BasicFunctionalityTestCase(FlaskTestCase): app.add_url_rule('/more', 'more', more, methods=['GET', 'POST']) c = app.test_client() - self.assert_equal(c.get('/').data, 'GET') + self.assert_equal(c.get('/').data, b'GET') rv = c.post('/') self.assert_equal(rv.status_code, 405) self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS']) rv = c.head('/') self.assert_equal(rv.status_code, 200) self.assert_(not rv.data) # head truncates - self.assert_equal(c.post('/more').data, 'POST') - self.assert_equal(c.get('/more').data, 'GET') + self.assert_equal(c.post('/more').data, b'POST') + self.assert_equal(c.get('/more').data, b'GET') rv = c.delete('/more') self.assert_equal(rv.status_code, 405) self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST']) @@ -124,8 +124,8 @@ class BasicFunctionalityTestCase(FlaskTestCase): app.view_functions['index'] = index c = app.test_client() - self.assert_equal(c.get('/foo/').data, 'index') - self.assert_equal(c.get('/foo/bar').data, 'bar') + self.assert_equal(c.get('/foo/').data, b'index') + self.assert_equal(c.get('/foo/bar').data, b'bar') def test_endpoint_decorator(self): from werkzeug.routing import Submount, Rule @@ -144,8 +144,8 @@ class BasicFunctionalityTestCase(FlaskTestCase): return 'index' c = app.test_client() - self.assert_equal(c.get('/foo/').data, 'index') - self.assert_equal(c.get('/foo/bar').data, 'bar') + self.assert_equal(c.get('/foo/').data, b'index') + self.assert_equal(c.get('/foo/bar').data, b'bar') def test_session(self): app = flask.Flask(__name__) @@ -159,8 +159,8 @@ class BasicFunctionalityTestCase(FlaskTestCase): return flask.session['value'] c = app.test_client() - self.assert_equal(c.post('/set', data={'value': '42'}).data, 'value set') - self.assert_equal(c.get('/get').data, '42') + self.assert_equal(c.post('/set', data={'value': '42'}).data, b'value set') + self.assert_equal(c.get('/get').data, b'42') def test_session_using_server_name(self): app = flask.Flask(__name__) @@ -289,7 +289,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): self.assert_equal(expires.day, expected.day) rv = client.get('/test') - self.assert_equal(rv.data, 'True') + self.assert_equal(rv.data, b'True') permanent = False rv = app.test_client().get('/') @@ -311,8 +311,8 @@ class BasicFunctionalityTestCase(FlaskTestCase): return repr(flask.session.get('foo')) c = app.test_client() - self.assert_equal(c.get('/').data, 'None') - self.assert_equal(c.get('/').data, '42') + self.assert_equal(c.get('/').data, b'None') + self.assert_equal(c.get('/').data, b'42') def test_session_special_types(self): app = flask.Flask(__name__) @@ -454,7 +454,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): self.assert_('after' not in evts) rv = app.test_client().get('/').data self.assert_('after' in evts) - self.assert_equal(rv, 'request|after') + self.assert_equal(rv, b'request|after') def test_after_request_processing(self): app = flask.Flask(__name__) @@ -483,7 +483,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): return "Response" rv = app.test_client().get('/') self.assert_equal(rv.status_code, 200) - self.assert_('Response' in rv.data) + self.assert_(b'Response' in rv.data) self.assert_equal(len(called), 1) def test_teardown_request_handler_debug_mode(self): @@ -499,7 +499,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): return "Response" rv = app.test_client().get('/') self.assert_equal(rv.status_code, 200) - self.assert_('Response' in rv.data) + self.assert_(b'Response' in rv.data) self.assert_equal(len(called), 1) def test_teardown_request_handler_error(self): @@ -532,7 +532,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): 1/0 rv = app.test_client().get('/') self.assert_equal(rv.status_code, 500) - self.assert_('Internal Server Error' in rv.data) + self.assert_(b'Internal Server Error' in rv.data) self.assert_equal(len(called), 2) def test_before_after_request_order(self): @@ -562,7 +562,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): def index(): return '42' rv = app.test_client().get('/') - self.assert_equal(rv.data, '42') + self.assert_equal(rv.data, b'42') self.assert_equal(called, [1, 2, 3, 4, 5, 6]) def test_error_handling(self): @@ -582,10 +582,10 @@ class BasicFunctionalityTestCase(FlaskTestCase): c = app.test_client() rv = c.get('/') self.assert_equal(rv.status_code, 404) - self.assert_equal(rv.data, 'not found') + self.assert_equal(rv.data, b'not found') rv = c.get('/error') self.assert_equal(rv.status_code, 500) - self.assert_equal('internal server error', rv.data) + self.assert_equal(b'internal server error', rv.data) def test_before_request_and_routing_errors(self): app = flask.Flask(__name__) @@ -597,7 +597,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): return flask.g.something, 404 rv = app.test_client().get('/') self.assert_equal(rv.status_code, 404) - self.assert_equal(rv.data, 'value') + self.assert_equal(rv.data, b'value') def test_user_error_handling(self): class MyException(Exception): @@ -613,7 +613,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): raise MyException() c = app.test_client() - self.assert_equal(c.get('/').data, '42') + self.assert_equal(c.get('/').data, b'42') def test_trapping_of_bad_request_key_errors(self): app = flask.Flask(__name__) @@ -687,7 +687,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): self.assert_equal(c.get('/unicode').data, u'Hällo Wörld'.encode('utf-8')) self.assert_equal(c.get('/string').data, u'Hällo Wörld'.encode('utf-8')) rv = c.get('/args') - self.assert_equal(rv.data, 'Meh') + self.assert_equal(rv.data, b'Meh') self.assert_equal(rv.headers['X-Foo'], 'Testing') self.assert_equal(rv.status_code, 400) self.assert_equal(rv.mimetype, 'text/plain') @@ -697,17 +697,17 @@ class BasicFunctionalityTestCase(FlaskTestCase): with app.test_request_context(): rv = flask.make_response() self.assert_equal(rv.status_code, 200) - self.assert_equal(rv.data, '') + self.assert_equal(rv.data, b'') self.assert_equal(rv.mimetype, 'text/html') rv = flask.make_response('Awesome') self.assert_equal(rv.status_code, 200) - self.assert_equal(rv.data, 'Awesome') + self.assert_equal(rv.data, b'Awesome') self.assert_equal(rv.mimetype, 'text/html') rv = flask.make_response('W00t', 404) self.assert_equal(rv.status_code, 404) - self.assert_equal(rv.data, 'W00t') + self.assert_equal(rv.data, b'W00t') self.assert_equal(rv.mimetype, 'text/html') def test_make_response_with_response_instance(self): @@ -716,14 +716,13 @@ class BasicFunctionalityTestCase(FlaskTestCase): rv = flask.make_response( flask.jsonify({'msg': 'W00t'}), 400) self.assertEqual(rv.status_code, 400) - self.assertEqual(rv.data, - '{\n "msg": "W00t"\n}') + self.assertEqual(rv.data, b'{\n "msg": "W00t"\n}') self.assertEqual(rv.mimetype, 'application/json') rv = flask.make_response( flask.Response(''), 400) self.assertEqual(rv.status_code, 400) - self.assertEqual(rv.data, '') + self.assertEqual(rv.data, b'') self.assertEqual(rv.mimetype, 'text/html') rv = flask.make_response( @@ -783,13 +782,13 @@ class BasicFunctionalityTestCase(FlaskTestCase): def index(args): return '|'.join(args) c = app.test_client() - self.assert_equal(c.get('/1,2,3').data, '1|2|3') + self.assert_equal(c.get('/1,2,3').data, b'1|2|3') def test_static_files(self): app = flask.Flask(__name__) rv = app.test_client().get('/static/index.html') self.assert_equal(rv.status_code, 200) - self.assert_equal(rv.data.strip(), '

Hello World!

') + self.assert_equal(rv.data.strip(), b'

Hello World!

') with app.test_request_context(): self.assert_equal(flask.url_for('static', filename='index.html'), '/static/index.html') @@ -825,17 +824,17 @@ class BasicFunctionalityTestCase(FlaskTestCase): return 'Foo SubDomain' rv = app.test_client().get('/') - self.assert_equal(rv.data, 'Foo') + self.assert_equal(rv.data, b'Foo') rv = app.test_client().get('/', 'http://localhost.localdomain:5000') - self.assert_equal(rv.data, 'Foo') + self.assert_equal(rv.data, b'Foo') rv = app.test_client().get('/', 'https://localhost.localdomain:5000') - self.assert_equal(rv.data, 'Foo') + self.assert_equal(rv.data, b'Foo') app.config.update(SERVER_NAME='localhost.localdomain') rv = app.test_client().get('/', 'https://localhost.localdomain') - self.assert_equal(rv.data, 'Foo') + self.assert_equal(rv.data, b'Foo') try: app.config.update(SERVER_NAME='localhost.localdomain:443') @@ -860,7 +859,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): "server name from the WSGI environment ('foo.localhost')") rv = app.test_client().get('/', 'http://foo.localhost.localdomain') - self.assert_equal(rv.data, 'Foo SubDomain') + self.assert_equal(rv.data, b'Foo SubDomain') def test_exception_propagation(self): def apprunner(configkey): @@ -906,7 +905,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): c = app.test_client() rv = c.post('/accept', data={'myfile': 'foo' * 100}) - self.assert_equal(rv.data, '42') + self.assert_equal(rv.data, b'42') def test_url_processors(self): app = flask.Flask(__name__) @@ -935,9 +934,9 @@ class BasicFunctionalityTestCase(FlaskTestCase): c = app.test_client() - self.assert_equal(c.get('/de/').data, '/de/about') - self.assert_equal(c.get('/de/about').data, '/foo') - self.assert_equal(c.get('/foo').data, '/en/about') + self.assert_equal(c.get('/de/').data, b'/de/about') + self.assert_equal(c.get('/de/about').data, b'/foo') + self.assert_equal(c.get('/foo').data, b'/en/about') def test_inject_blueprint_url_defaults(self): app = flask.Flask(__name__) @@ -969,7 +968,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): def index(): return 'Awesome' self.assert_(not app.got_first_request) - self.assert_equal(app.test_client().get('/').data, 'Awesome') + self.assert_equal(app.test_client().get('/').data, b'Awesome') try: @app.route('/foo') def broken(): @@ -983,7 +982,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): @app.route('/foo') def working(): return 'Meh' - self.assert_equal(app.test_client().get('/foo').data, 'Meh') + self.assert_equal(app.test_client().get('/foo').data, b'Meh') self.assert_(app.got_first_request) def test_before_first_request_functions(self): @@ -1016,12 +1015,12 @@ class BasicFunctionalityTestCase(FlaskTestCase): self.fail('Expected exception') rv = c.get('/foo', data={}, follow_redirects=True) - self.assert_equal(rv.data, 'success') + self.assert_equal(rv.data, b'success') app.debug = False with app.test_client() as c: rv = c.post('/foo', data={}, follow_redirects=True) - self.assert_equal(rv.data, 'success') + self.assert_equal(rv.data, b'success') def test_route_decorator_custom_endpoint(self): app = flask.Flask(__name__) @@ -1045,9 +1044,9 @@ class BasicFunctionalityTestCase(FlaskTestCase): assert flask.url_for('123') == '/bar/123' c = app.test_client() - self.assertEqual(c.get('/foo/').data, 'foo') - self.assertEqual(c.get('/bar/').data, 'bar') - self.assertEqual(c.get('/bar/123').data, '123') + self.assertEqual(c.get('/foo/').data, b'foo') + self.assertEqual(c.get('/bar/').data, b'bar') + self.assertEqual(c.get('/bar/123').data, b'123') def test_preserve_only_once(self): app = flask.Flask(__name__) @@ -1084,10 +1083,10 @@ class SubdomainTestCase(FlaskTestCase): c = app.test_client() rv = c.get('/', 'http://localhost/') - self.assert_equal(rv.data, 'normal index') + self.assert_equal(rv.data, b'normal index') rv = c.get('/', 'http://test.localhost/') - self.assert_equal(rv.data, 'test index') + self.assert_equal(rv.data, b'test index') @emits_module_deprecation_warning def test_module_static_path_subdomain(self): @@ -1108,7 +1107,7 @@ class SubdomainTestCase(FlaskTestCase): c = app.test_client() rv = c.get('/', 'http://mitsuhiko.localhost/') - self.assert_equal(rv.data, 'index for mitsuhiko') + self.assert_equal(rv.data, b'index for mitsuhiko') def test_subdomain_matching_with_ports(self): app = flask.Flask(__name__) @@ -1119,7 +1118,7 @@ class SubdomainTestCase(FlaskTestCase): c = app.test_client() rv = c.get('/', 'http://mitsuhiko.localhost:3000/') - self.assert_equal(rv.data, 'index for mitsuhiko') + self.assert_equal(rv.data, b'index for mitsuhiko') @emits_module_deprecation_warning def test_module_subdomain_support(self): @@ -1139,9 +1138,9 @@ class SubdomainTestCase(FlaskTestCase): c = app.test_client() rv = c.get('/test', 'http://testing.localhost/') - self.assert_equal(rv.data, 'Test') + self.assert_equal(rv.data, b'Test') rv = c.get('/outside', 'http://xtesting.localhost/') - self.assert_equal(rv.data, 'Outside') + self.assert_equal(rv.data, b'Outside') def suite(): diff --git a/flask/testsuite/blueprints.py b/flask/testsuite/blueprints.py index 331854a6..28256b63 100644 --- a/flask/testsuite/blueprints.py +++ b/flask/testsuite/blueprints.py @@ -46,10 +46,10 @@ class ModuleTestCase(FlaskTestCase): return 'the index' app.register_module(admin) c = app.test_client() - self.assert_equal(c.get('/').data, 'the index') - self.assert_equal(c.get('/admin/').data, 'admin index') - self.assert_equal(c.get('/admin/login').data, 'admin login') - self.assert_equal(c.get('/admin/logout').data, 'admin logout') + self.assert_equal(c.get('/').data, b'the index') + self.assert_equal(c.get('/admin/').data, b'admin index') + self.assert_equal(c.get('/admin/login').data, b'admin login') + self.assert_equal(c.get('/admin/logout').data, b'admin logout') @emits_module_deprecation_warning def test_default_endpoint_name(self): @@ -60,7 +60,7 @@ class ModuleTestCase(FlaskTestCase): mod.add_url_rule('/', view_func=index) app.register_module(mod) rv = app.test_client().get('/') - self.assert_equal(rv.data, 'Awesome') + self.assert_equal(rv.data, b'Awesome') with app.test_request_context(): self.assert_equal(flask.url_for('frontend.index'), '/') @@ -92,11 +92,11 @@ class ModuleTestCase(FlaskTestCase): app.register_module(admin) c = app.test_client() - self.assert_equal(c.get('/').data, 'the index') + self.assert_equal(c.get('/').data, b'the index') self.assert_equal(catched, ['before-app', 'after-app']) del catched[:] - self.assert_equal(c.get('/admin/').data, 'the admin') + self.assert_equal(c.get('/admin/').data, b'the admin') self.assert_equal(catched, ['before-app', 'before-admin', 'after-admin', 'after-app']) @@ -121,8 +121,8 @@ class ModuleTestCase(FlaskTestCase): return flask.render_template_string('{{ a }}{{ b }}{{ c }}') app.register_module(admin) c = app.test_client() - self.assert_equal(c.get('/').data, '13') - self.assert_equal(c.get('/admin/').data, '123') + self.assert_equal(c.get('/').data, b'13') + self.assert_equal(c.get('/admin/').data, b'123') @emits_module_deprecation_warning def test_late_binding(self): @@ -132,7 +132,7 @@ class ModuleTestCase(FlaskTestCase): def index(): return '42' app.register_module(admin, url_prefix='/admin') - self.assert_equal(app.test_client().get('/admin/').data, '42') + self.assert_equal(app.test_client().get('/admin/').data, b'42') @emits_module_deprecation_warning def test_error_handling(self): @@ -154,7 +154,7 @@ class ModuleTestCase(FlaskTestCase): c = app.test_client() rv = c.get('/') self.assert_equal(rv.status_code, 404) - self.assert_equal(rv.data, 'not found') + self.assert_equal(rv.data, b'not found') rv = c.get('/error') self.assert_equal(rv.status_code, 500) self.assert_equal('internal server error', rv.data) @@ -165,11 +165,11 @@ class ModuleTestCase(FlaskTestCase): c = app.test_client() rv = c.get('/') - self.assert_equal(rv.data, 'Hello from the Frontend') + self.assert_equal(rv.data, b'Hello from the Frontend') rv = c.get('/admin/') - self.assert_equal(rv.data, 'Hello from the Admin') + self.assert_equal(rv.data, b'Hello from the Admin') rv = c.get('/admin/index2') - self.assert_equal(rv.data, 'Hello from the Admin') + self.assert_equal(rv.data, b'Hello from the Admin') rv = c.get('/admin/static/test.txt') self.assert_equal(rv.data.strip(), 'Admin File') rv = c.get('/admin/static/css/test.css') @@ -248,8 +248,8 @@ class ModuleTestCase(FlaskTestCase): app.register_module(module) c = app.test_client() - self.assert_equal(c.get('/foo/').data, 'index') - self.assert_equal(c.get('/foo/bar').data, 'bar') + self.assert_equal(c.get('/foo/').data, b'index') + self.assert_equal(c.get('/foo/bar').data, b'bar') class BlueprintTestCase(FlaskTestCase): @@ -290,9 +290,9 @@ class BlueprintTestCase(FlaskTestCase): c = app.test_client() - self.assert_equal(c.get('/frontend-no').data, 'frontend says no') - self.assert_equal(c.get('/backend-no').data, 'backend says no') - self.assert_equal(c.get('/what-is-a-sideend').data, 'application itself says no') + self.assert_equal(c.get('/frontend-no').data, b'frontend says no') + self.assert_equal(c.get('/backend-no').data, b'backend says no') + self.assert_equal(c.get('/what-is-a-sideend').data, b'application itself says no') def test_blueprint_url_definitions(self): bp = flask.Blueprint('test', __name__) @@ -339,19 +339,19 @@ class BlueprintTestCase(FlaskTestCase): c = app.test_client() - self.assert_equal(c.get('/de/').data, '/de/about') - self.assert_equal(c.get('/de/about').data, '/de/') + self.assert_equal(c.get('/de/').data, b'/de/about') + self.assert_equal(c.get('/de/about').data, b'/de/') def test_templates_and_static(self): from blueprintapp import app c = app.test_client() rv = c.get('/') - self.assert_equal(rv.data, 'Hello from the Frontend') + self.assert_equal(rv.data, b'Hello from the Frontend') rv = c.get('/admin/') - self.assert_equal(rv.data, 'Hello from the Admin') + self.assert_equal(rv.data, b'Hello from the Admin') rv = c.get('/admin/index2') - self.assert_equal(rv.data, 'Hello from the Admin') + self.assert_equal(rv.data, b'Hello from the Admin') rv = c.get('/admin/static/test.txt') self.assert_equal(rv.data.strip(), 'Admin File') rv = c.get('/admin/static/css/test.css') @@ -451,8 +451,8 @@ class BlueprintTestCase(FlaskTestCase): app.register_blueprint(bp) c = app.test_client() - self.assert_equal(c.get('/').data, '1') - self.assert_equal(c.get('/page/2').data, '2') + self.assert_equal(c.get('/').data, b'1') + self.assert_equal(c.get('/page/2').data, b'2') def test_route_decorator_custom_endpoint(self): @@ -482,11 +482,11 @@ class BlueprintTestCase(FlaskTestCase): return flask.request.endpoint c = app.test_client() - self.assertEqual(c.get('/').data, 'index') - self.assertEqual(c.get('/py/foo').data, 'bp.foo') - self.assertEqual(c.get('/py/bar').data, 'bp.bar') - self.assertEqual(c.get('/py/bar/123').data, 'bp.123') - self.assertEqual(c.get('/py/bar/foo').data, 'bp.bar_foo') + self.assertEqual(c.get('/').data, b'index') + self.assertEqual(c.get('/py/foo').data, b'bp.foo') + self.assertEqual(c.get('/py/bar').data, b'bp.bar') + self.assertEqual(c.get('/py/bar/123').data, b'bp.123') + self.assertEqual(c.get('/py/bar/foo').data, b'bp.bar_foo') def test_route_decorator_custom_endpoint_with_dots(self): bp = flask.Blueprint('bp', __name__) @@ -533,7 +533,7 @@ class BlueprintTestCase(FlaskTestCase): app.register_blueprint(bp, url_prefix='/py') c = app.test_client() - self.assertEqual(c.get('/py/foo').data, 'bp.foo') + self.assertEqual(c.get('/py/foo').data, b'bp.foo') # The rule's din't actually made it through rv = c.get('/py/bar') assert rv.status_code == 404 @@ -595,7 +595,7 @@ class BlueprintTestCase(FlaskTestCase): def index(): return flask.render_template('template_filter.html', value='abcd') rv = app.test_client().get('/') - self.assert_equal(rv.data, 'dcba') + self.assert_equal(rv.data, b'dcba') def test_template_filter_after_route_with_template(self): app = flask.Flask(__name__) @@ -608,7 +608,7 @@ class BlueprintTestCase(FlaskTestCase): return s[::-1] app.register_blueprint(bp, url_prefix='/py') rv = app.test_client().get('/') - self.assert_equal(rv.data, 'dcba') + self.assert_equal(rv.data, b'dcba') def test_add_template_filter_with_template(self): bp = flask.Blueprint('bp', __name__) @@ -621,7 +621,7 @@ class BlueprintTestCase(FlaskTestCase): def index(): return flask.render_template('template_filter.html', value='abcd') rv = app.test_client().get('/') - self.assert_equal(rv.data, 'dcba') + self.assert_equal(rv.data, b'dcba') def test_template_filter_with_name_and_template(self): bp = flask.Blueprint('bp', __name__) @@ -634,7 +634,7 @@ class BlueprintTestCase(FlaskTestCase): def index(): return flask.render_template('template_filter.html', value='abcd') rv = app.test_client().get('/') - self.assert_equal(rv.data, 'dcba') + self.assert_equal(rv.data, b'dcba') def test_add_template_filter_with_name_and_template(self): bp = flask.Blueprint('bp', __name__) @@ -647,7 +647,7 @@ class BlueprintTestCase(FlaskTestCase): def index(): return flask.render_template('template_filter.html', value='abcd') rv = app.test_client().get('/') - self.assert_equal(rv.data, 'dcba') + self.assert_equal(rv.data, b'dcba') def test_template_test(self): bp = flask.Blueprint('bp', __name__) diff --git a/flask/testsuite/helpers.py b/flask/testsuite/helpers.py index 2808a409..fbdcbff4 100644 --- a/flask/testsuite/helpers.py +++ b/flask/testsuite/helpers.py @@ -99,7 +99,7 @@ class JSONTestCase(FlaskTestCase): c = app.test_client() rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}), content_type='application/json') - self.assert_equal(rv.data, '3') + self.assert_equal(rv.data, b'3') def test_template_escaping(self): app = flask.Flask(__name__) @@ -140,7 +140,7 @@ class JSONTestCase(FlaskTestCase): rv = c.post('/', data=flask.json.dumps({ 'x': {'_foo': 42} }), content_type='application/json') - self.assertEqual(rv.data, '"<42>"') + self.assertEqual(rv.data, b'"<42>"') def test_modified_url_encoding(self): class ModifiedRequest(flask.Request): @@ -212,14 +212,14 @@ class SendfileTestCase(FlaskTestCase): with catch_warnings() as captured: f = StringIO('Test') rv = flask.send_file(f) - self.assert_equal(rv.data, 'Test') + self.assert_equal(rv.data, b'Test') self.assert_equal(rv.mimetype, 'application/octet-stream') # etags self.assert_equal(len(captured), 1) with catch_warnings() as captured: f = StringIO('Test') rv = flask.send_file(f, mimetype='text/plain') - self.assert_equal(rv.data, 'Test') + self.assert_equal(rv.data, b'Test') self.assert_equal(rv.mimetype, 'text/plain') # etags self.assert_equal(len(captured), 1) @@ -385,7 +385,7 @@ class LoggingTestCase(FlaskTestCase): for trigger in 'before', 'after': rv = app.test_client().get('/') self.assert_equal(rv.status_code, 500) - self.assert_equal(rv.data, 'Hello Server Error') + self.assert_equal(rv.data, b'Hello Server Error') def test_url_for_with_anchor(self): app = flask.Flask(__name__) @@ -477,7 +477,7 @@ class StreamingTestCase(FlaskTestCase): return flask.Response(flask.stream_with_context(generate())) c = app.test_client() rv = c.get('/?name=World') - self.assertEqual(rv.data, 'Hello World!') + self.assertEqual(rv.data, b'Hello World!') def test_streaming_with_context_as_decorator(self): app = flask.Flask(__name__) @@ -492,7 +492,7 @@ class StreamingTestCase(FlaskTestCase): return flask.Response(generate()) c = app.test_client() rv = c.get('/?name=World') - self.assertEqual(rv.data, 'Hello World!') + self.assertEqual(rv.data, b'Hello World!') def test_streaming_with_context_and_custom_close(self): app = flask.Flask(__name__) @@ -517,7 +517,7 @@ class StreamingTestCase(FlaskTestCase): Wrapper(generate()))) c = app.test_client() rv = c.get('/?name=World') - self.assertEqual(rv.data, 'Hello World!') + self.assertEqual(rv.data, b'Hello World!') self.assertEqual(called, [42]) diff --git a/flask/testsuite/regression.py b/flask/testsuite/regression.py index b8140d6f..e516dc0f 100644 --- a/flask/testsuite/regression.py +++ b/flask/testsuite/regression.py @@ -66,7 +66,7 @@ class MemoryTestCase(FlaskTestCase): with app.test_client() as c: rv = c.get('/') self.assert_equal(rv.status_code, 200) - self.assert_equal(rv.data, '

42

') + self.assert_equal(rv.data, b'

42

') # Trigger caches fire() @@ -105,7 +105,7 @@ class ExceptionTestCase(FlaskTestCase): rv = c.get('/') self.assertEqual(rv.headers['Location'], 'http://localhost/test') rv = c.get('/test') - self.assertEqual(rv.data, '42') + self.assertEqual(rv.data, b'42') def suite(): diff --git a/flask/testsuite/reqctx.py b/flask/testsuite/reqctx.py index 0f0282e5..6e379448 100644 --- a/flask/testsuite/reqctx.py +++ b/flask/testsuite/reqctx.py @@ -145,7 +145,7 @@ class RequestContextTestCase(FlaskTestCase): return 'Hello World!' rv = app.test_client().get('/?foo=bar') - self.assert_equal(rv.data, 'Hello World!') + self.assert_equal(rv.data, b'Hello World!') result = greenlets[0].run() self.assert_equal(result, 42) @@ -168,7 +168,7 @@ class RequestContextTestCase(FlaskTestCase): return 'Hello World!' rv = app.test_client().get('/?foo=bar') - self.assert_equal(rv.data, 'Hello World!') + self.assert_equal(rv.data, b'Hello World!') result = greenlets[0].run() self.assert_equal(result, 42) diff --git a/flask/testsuite/signals.py b/flask/testsuite/signals.py index 637c2c66..843c2f83 100644 --- a/flask/testsuite/signals.py +++ b/flask/testsuite/signals.py @@ -45,7 +45,7 @@ class SignalsTestCase(FlaskTestCase): calls.append('before-signal') def after_request_signal(sender, response): - self.assert_equal(response.data, 'stuff') + self.assert_equal(response.data, b'stuff') calls.append('after-signal') @app.before_request @@ -68,7 +68,7 @@ class SignalsTestCase(FlaskTestCase): try: rv = app.test_client().get('/') - self.assert_equal(rv.data, 'stuff') + self.assert_equal(rv.data, b'stuff') self.assert_equal(calls, ['before-signal', 'before-handler', 'handler', 'after-handler', diff --git a/flask/testsuite/templating.py b/flask/testsuite/templating.py index c8d1dd22..c36a282e 100644 --- a/flask/testsuite/templating.py +++ b/flask/testsuite/templating.py @@ -25,7 +25,7 @@ class TemplatingTestCase(FlaskTestCase): def index(): return flask.render_template('context_template.html', value=23) rv = app.test_client().get('/') - self.assert_equal(rv.data, '

23|42') + self.assert_equal(rv.data, b'

23|42') def test_original_win(self): app = flask.Flask(__name__) @@ -33,7 +33,7 @@ class TemplatingTestCase(FlaskTestCase): def index(): return flask.render_template_string('{{ config }}', config=42) rv = app.test_client().get('/') - self.assert_equal(rv.data, '42') + self.assert_equal(rv.data, b'42') def test_request_less_rendering(self): app = flask.Flask(__name__) @@ -139,7 +139,7 @@ class TemplatingTestCase(FlaskTestCase): def index(): return flask.render_template('template_filter.html', value='abcd') rv = app.test_client().get('/') - self.assert_equal(rv.data, 'dcba') + self.assert_equal(rv.data, b'dcba') def test_add_template_filter_with_template(self): app = flask.Flask(__name__) @@ -150,7 +150,7 @@ class TemplatingTestCase(FlaskTestCase): def index(): return flask.render_template('template_filter.html', value='abcd') rv = app.test_client().get('/') - self.assert_equal(rv.data, 'dcba') + self.assert_equal(rv.data, b'dcba') def test_template_filter_with_name_and_template(self): app = flask.Flask(__name__) @@ -161,7 +161,7 @@ class TemplatingTestCase(FlaskTestCase): def index(): return flask.render_template('template_filter.html', value='abcd') rv = app.test_client().get('/') - self.assert_equal(rv.data, 'dcba') + self.assert_equal(rv.data, b'dcba') def test_add_template_filter_with_name_and_template(self): app = flask.Flask(__name__) @@ -172,7 +172,7 @@ class TemplatingTestCase(FlaskTestCase): def index(): return flask.render_template('template_filter.html', value='abcd') rv = app.test_client().get('/') - self.assert_equal(rv.data, 'dcba') + self.assert_equal(rv.data, b'dcba') def test_template_test(self): app = flask.Flask(__name__) @@ -277,7 +277,7 @@ class TemplatingTestCase(FlaskTestCase): return flask.render_template('index.html') c = app.test_client() rv = c.get('/') - self.assert_equal(rv.data, 'Hello Custom World!') + self.assert_equal(rv.data, b'Hello Custom World!') def test_iterable_loader(self): app = flask.Flask(__name__) @@ -293,7 +293,7 @@ class TemplatingTestCase(FlaskTestCase): value=23) rv = app.test_client().get('/') - self.assert_equal(rv.data, '

Jameson

') + self.assert_equal(rv.data, b'

Jameson

') def suite(): diff --git a/flask/testsuite/testing.py b/flask/testsuite/testing.py index a37f6e6c..8b1b7d62 100644 --- a/flask/testsuite/testing.py +++ b/flask/testsuite/testing.py @@ -30,7 +30,7 @@ class TestToolsTestCase(FlaskTestCase): self.assert_equal(ctx.request.url, 'http://example.com:1234/foo/') with app.test_client() as c: rv = c.get('/') - self.assert_equal(rv.data, 'http://example.com:1234/foo/') + self.assert_equal(rv.data, b'http://example.com:1234/foo/') def test_environ_defaults(self): app = flask.Flask(__name__) @@ -43,7 +43,7 @@ class TestToolsTestCase(FlaskTestCase): self.assert_equal(ctx.request.url, 'http://localhost/') with app.test_client() as c: rv = c.get('/') - self.assert_equal(rv.data, 'http://localhost/') + self.assert_equal(rv.data, b'http://localhost/') def test_redirect_keep_session(self): app = flask.Flask(__name__) @@ -92,7 +92,7 @@ class TestToolsTestCase(FlaskTestCase): sess['foo'] = [42] self.assert_equal(len(sess), 1) rv = c.get('/') - self.assert_equal(rv.data, '[42]') + self.assert_equal(rv.data, b'[42]') with c.session_transaction() as sess: self.assert_equal(len(sess), 1) self.assert_equal(sess['foo'], [42]) @@ -148,7 +148,7 @@ class TestToolsTestCase(FlaskTestCase): with app.test_client() as c: resp = c.get('/') self.assert_equal(flask.g.value, 42) - self.assert_equal(resp.data, 'Hello World!') + self.assert_equal(resp.data, b'Hello World!') self.assert_equal(resp.status_code, 200) resp = c.get('/other') diff --git a/flask/testsuite/views.py b/flask/testsuite/views.py index 6c3ae816..9dd463f2 100644 --- a/flask/testsuite/views.py +++ b/flask/testsuite/views.py @@ -20,8 +20,8 @@ class ViewTestCase(FlaskTestCase): def common_test(self, app): c = app.test_client() - self.assert_equal(c.get('/').data, 'GET') - self.assert_equal(c.post('/').data, 'POST') + self.assert_equal(c.get('/').data, b'GET') + self.assert_equal(c.post('/').data, b'POST') self.assert_equal(c.put('/').status_code, 405) meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow']) self.assert_equal(sorted(meths), ['GET', 'HEAD', 'OPTIONS', 'POST']) @@ -108,7 +108,7 @@ class ViewTestCase(FlaskTestCase): c = app.test_client() rv = c.get('/') self.assert_equal(rv.headers['X-Parachute'], 'awesome') - self.assert_equal(rv.data, 'Awesome') + self.assert_equal(rv.data, b'Awesome') def test_implicit_head(self): app = flask.Flask(__name__) @@ -122,10 +122,10 @@ class ViewTestCase(FlaskTestCase): app.add_url_rule('/', view_func=Index.as_view('index')) c = app.test_client() rv = c.get('/') - self.assert_equal(rv.data, 'Blub') + self.assert_equal(rv.data, b'Blub') self.assert_equal(rv.headers['X-Method'], 'GET') rv = c.head('/') - self.assert_equal(rv.data, '') + self.assert_equal(rv.data, b'') self.assert_equal(rv.headers['X-Method'], 'HEAD') def test_explicit_head(self): @@ -140,9 +140,9 @@ class ViewTestCase(FlaskTestCase): app.add_url_rule('/', view_func=Index.as_view('index')) c = app.test_client() rv = c.get('/') - self.assert_equal(rv.data, 'GET') + self.assert_equal(rv.data, b'GET') rv = c.head('/') - self.assert_equal(rv.data, '') + self.assert_equal(rv.data, b'') self.assert_equal(rv.headers['X-Method'], 'HEAD') def test_endpoint_override(self): From 5b89355b1c9771431fb8a011094591ad43461b0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Wed, 22 May 2013 17:14:07 +0200 Subject: [PATCH 22/58] Response data is bytes --- flask/testsuite/basic.py | 8 ++++---- flask/testsuite/blueprints.py | 34 +++++++++++++++++----------------- flask/testsuite/helpers.py | 2 +- flask/testsuite/subclassing.py | 2 +- flask/testsuite/templating.py | 22 +++++++++++----------- flask/testsuite/testing.py | 14 +++++++------- 6 files changed, 41 insertions(+), 41 deletions(-) diff --git a/flask/testsuite/basic.py b/flask/testsuite/basic.py index 1636bee7..c76204d7 100644 --- a/flask/testsuite/basic.py +++ b/flask/testsuite/basic.py @@ -453,7 +453,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): return 'request' self.assert_('after' not in evts) rv = app.test_client().get('/').data - self.assert_('after' in evts) + self.assert_(b'after' in evts) self.assert_equal(rv, b'request|after') def test_after_request_processing(self): @@ -937,10 +937,10 @@ class BasicFunctionalityTestCase(FlaskTestCase): self.assert_equal(c.get('/de/').data, b'/de/about') self.assert_equal(c.get('/de/about').data, b'/foo') self.assert_equal(c.get('/foo').data, b'/en/about') - + def test_inject_blueprint_url_defaults(self): app = flask.Flask(__name__) - bp = flask.Blueprint('foo.bar.baz', __name__, + bp = flask.Blueprint('foo.bar.baz', __name__, template_folder='template') @bp.url_defaults @@ -1096,7 +1096,7 @@ class SubdomainTestCase(FlaskTestCase): app.register_module(mod) c = app.test_client() rv = c.get('/static/hello.txt', 'http://foo.example.com/') - self.assert_equal(rv.data.strip(), 'Hello Subdomain') + self.assert_equal(rv.data.strip(), b'Hello Subdomain') def test_subdomain_matching(self): app = flask.Flask(__name__) diff --git a/flask/testsuite/blueprints.py b/flask/testsuite/blueprints.py index 28256b63..ed3ddbb2 100644 --- a/flask/testsuite/blueprints.py +++ b/flask/testsuite/blueprints.py @@ -157,7 +157,7 @@ class ModuleTestCase(FlaskTestCase): self.assert_equal(rv.data, b'not found') rv = c.get('/error') self.assert_equal(rv.status_code, 500) - self.assert_equal('internal server error', rv.data) + self.assert_equal(b'internal server error', rv.data) def test_templates_and_static(self): app = moduleapp @@ -171,9 +171,9 @@ class ModuleTestCase(FlaskTestCase): rv = c.get('/admin/index2') self.assert_equal(rv.data, b'Hello from the Admin') rv = c.get('/admin/static/test.txt') - self.assert_equal(rv.data.strip(), 'Admin File') + self.assert_equal(rv.data.strip(), b'Admin File') rv = c.get('/admin/static/css/test.css') - self.assert_equal(rv.data.strip(), '/* nested file */') + self.assert_equal(rv.data.strip(), b'/* nested file */') with app.test_request_context(): self.assert_equal(flask.url_for('admin.static', filename='test.txt'), @@ -310,10 +310,10 @@ class BlueprintTestCase(FlaskTestCase): app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19}) c = app.test_client() - self.assert_equal(c.get('/1/foo').data, u'23/42') - self.assert_equal(c.get('/2/foo').data, u'19/42') - self.assert_equal(c.get('/1/bar').data, u'23') - self.assert_equal(c.get('/2/bar').data, u'19') + self.assert_equal(c.get('/1/foo').data, b'23/42') + self.assert_equal(c.get('/2/foo').data, b'19/42') + self.assert_equal(c.get('/1/bar').data, b'23') + self.assert_equal(c.get('/2/bar').data, b'19') def test_blueprint_url_processors(self): bp = flask.Blueprint('frontend', __name__, url_prefix='/') @@ -353,9 +353,9 @@ class BlueprintTestCase(FlaskTestCase): rv = c.get('/admin/index2') self.assert_equal(rv.data, b'Hello from the Admin') rv = c.get('/admin/static/test.txt') - self.assert_equal(rv.data.strip(), 'Admin File') + self.assert_equal(rv.data.strip(), b'Admin File') rv = c.get('/admin/static/css/test.css') - self.assert_equal(rv.data.strip(), '/* nested file */') + self.assert_equal(rv.data.strip(), b'/* nested file */') # try/finally, in case other tests use this app for Blueprint tests. max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT'] @@ -435,9 +435,9 @@ class BlueprintTestCase(FlaskTestCase): app.register_blueprint(backend) c = app.test_client() - self.assert_equal(c.get('/fe').data.strip(), '/be') - self.assert_equal(c.get('/fe2').data.strip(), '/fe') - self.assert_equal(c.get('/be').data.strip(), '/fe') + self.assert_equal(c.get('/fe').data.strip(), b'/be') + self.assert_equal(c.get('/fe2').data.strip(), b'/fe') + self.assert_equal(c.get('/be').data.strip(), b'/fe') def test_empty_url_defaults(self): bp = flask.Blueprint('bp', __name__) @@ -704,7 +704,7 @@ class BlueprintTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_('Success!' in rv.data) + self.assert_(b'Success!' in rv.data) def test_template_test_after_route_with_template(self): app = flask.Flask(__name__) @@ -717,7 +717,7 @@ class BlueprintTestCase(FlaskTestCase): return isinstance(value, bool) app.register_blueprint(bp, url_prefix='/py') rv = app.test_client().get('/') - self.assert_('Success!' in rv.data) + self.assert_(b'Success!' in rv.data) def test_add_template_test_with_template(self): bp = flask.Blueprint('bp', __name__) @@ -730,7 +730,7 @@ class BlueprintTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_('Success!' in rv.data) + self.assert_(b'Success!' in rv.data) def test_template_test_with_name_and_template(self): bp = flask.Blueprint('bp', __name__) @@ -743,7 +743,7 @@ class BlueprintTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_('Success!' in rv.data) + self.assert_(b'Success!' in rv.data) def test_add_template_test_with_name_and_template(self): bp = flask.Blueprint('bp', __name__) @@ -756,7 +756,7 @@ class BlueprintTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_('Success!' in rv.data) + self.assert_(b'Success!' in rv.data) def suite(): suite = unittest.TestSuite() diff --git a/flask/testsuite/helpers.py b/flask/testsuite/helpers.py index fbdcbff4..9ca9eec3 100644 --- a/flask/testsuite/helpers.py +++ b/flask/testsuite/helpers.py @@ -357,7 +357,7 @@ class LoggingTestCase(FlaskTestCase): rv = app.test_client().get('/') self.assert_equal(rv.status_code, 500) - self.assert_('Internal Server Error' in rv.data) + self.assert_(b'Internal Server Error' in rv.data) err = out.getvalue() self.assert_('Exception on / [GET]' in err) diff --git a/flask/testsuite/subclassing.py b/flask/testsuite/subclassing.py index 3e8d75c1..e26b9085 100644 --- a/flask/testsuite/subclassing.py +++ b/flask/testsuite/subclassing.py @@ -34,7 +34,7 @@ class FlaskSubclassingTestCase(FlaskTestCase): rv = app.test_client().get('/') self.assert_equal(rv.status_code, 500) - self.assert_('Internal Server Error' in rv.data) + self.assert_(b'Internal Server Error' in rv.data) err = out.getvalue() self.assert_equal(err, '') diff --git a/flask/testsuite/templating.py b/flask/testsuite/templating.py index c36a282e..0d3a2a5c 100644 --- a/flask/testsuite/templating.py +++ b/flask/testsuite/templating.py @@ -61,7 +61,7 @@ class TemplatingTestCase(FlaskTestCase): {{ session.test }} ''') rv = app.test_client().get('/?foo=42') - self.assert_equal(rv.data.split(), ['42', '23', 'False', 'aha']) + self.assert_equal(rv.data.split(), [b'42', b'23', b'False', b'aha']) def test_escaping(self): text = '

Hello World!' @@ -72,12 +72,12 @@ class TemplatingTestCase(FlaskTestCase): html=flask.Markup(text)) lines = app.test_client().get('/').data.splitlines() self.assert_equal(lines, [ - '<p>Hello World!', - '

Hello World!', - '

Hello World!', - '

Hello World!', - '<p>Hello World!', - '

Hello World!' + b'<p>Hello World!', + b'

Hello World!', + b'

Hello World!', + b'

Hello World!', + b'<p>Hello World!', + b'

Hello World!' ]) def test_no_escaping(self): @@ -219,7 +219,7 @@ class TemplatingTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_('Success!' in rv.data) + self.assert_(b'Success!' in rv.data) def test_add_template_test_with_template(self): app = flask.Flask(__name__) @@ -230,7 +230,7 @@ class TemplatingTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_('Success!' in rv.data) + self.assert_(b'Success!' in rv.data) def test_template_test_with_name_and_template(self): app = flask.Flask(__name__) @@ -241,7 +241,7 @@ class TemplatingTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_('Success!' in rv.data) + self.assert_(b'Success!' in rv.data) def test_add_template_test_with_name_and_template(self): app = flask.Flask(__name__) @@ -252,7 +252,7 @@ class TemplatingTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_('Success!' in rv.data) + self.assert_(b'Success!' in rv.data) def test_add_template_global(self): app = flask.Flask(__name__) diff --git a/flask/testsuite/testing.py b/flask/testsuite/testing.py index 8b1b7d62..3379a463 100644 --- a/flask/testsuite/testing.py +++ b/flask/testsuite/testing.py @@ -62,20 +62,20 @@ class TestToolsTestCase(FlaskTestCase): with app.test_client() as c: rv = c.get('/getsession') - assert rv.data == '' + assert rv.data == b'' rv = c.get('/') - assert rv.data == 'index' + assert rv.data == b'index' assert flask.session.get('data') == 'foo' rv = c.post('/', data={}, follow_redirects=True) - assert rv.data == 'foo' + assert rv.data == b'foo' # This support requires a new Werkzeug version if not hasattr(c, 'redirect_client'): assert flask.session.get('data') == 'foo' rv = c.get('/getsession') - assert rv.data == 'foo' + assert rv.data == b'foo' def test_session_transactions(self): app = flask.Flask(__name__) @@ -153,7 +153,7 @@ class TestToolsTestCase(FlaskTestCase): resp = c.get('/other') self.assert_(not hasattr(flask.g, 'value')) - self.assert_('Internal Server Error' in resp.data) + self.assert_(b'Internal Server Error' in resp.data) self.assert_equal(resp.status_code, 500) flask.g.value = 23 @@ -220,7 +220,7 @@ class SubdomainTestCase(FlaskTestCase): response = self.client.get(url) self.assertEquals(200, response.status_code) - self.assertEquals('xxx', response.data) + self.assertEquals(b'xxx', response.data) def test_nosubdomain(self): @@ -232,7 +232,7 @@ class SubdomainTestCase(FlaskTestCase): response = self.client.get(url) self.assertEquals(200, response.status_code) - self.assertEquals('xxx', response.data) + self.assertEquals(b'xxx', response.data) def suite(): From 239780be289efd365c07be2f60bab9223388399e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Wed, 22 May 2013 17:23:38 +0200 Subject: [PATCH 23/58] Use assert_true instead of assert_ assert_ is deprecated which causes annoying warnings --- flask/testsuite/__init__.py | 7 ++- flask/testsuite/appctx.py | 2 +- flask/testsuite/basic.py | 92 +++++++++++++++++----------------- flask/testsuite/blueprints.py | 44 ++++++++-------- flask/testsuite/config.py | 24 ++++----- flask/testsuite/ext.py | 8 +-- flask/testsuite/helpers.py | 38 +++++++------- flask/testsuite/reqctx.py | 24 ++++----- flask/testsuite/signals.py | 2 +- flask/testsuite/subclassing.py | 2 +- flask/testsuite/templating.py | 36 ++++++------- flask/testsuite/testing.py | 12 ++--- 12 files changed, 147 insertions(+), 144 deletions(-) diff --git a/flask/testsuite/__init__.py b/flask/testsuite/__init__.py index 82fa3232..2a869173 100644 --- a/flask/testsuite/__init__.py +++ b/flask/testsuite/__init__.py @@ -101,9 +101,9 @@ def emits_module_deprecation_warning(f): def new_f(self, *args, **kwargs): with catch_warnings() as log: f(self, *args, **kwargs) - self.assert_(log, 'expected deprecation warning') + self.assert_true(log, 'expected deprecation warning') for entry in log: - self.assert_('Modules are deprecated' in str(entry['message'])) + self.assert_true('Modules are deprecated' in str(entry['message'])) return update_wrapper(new_f, f) @@ -142,6 +142,9 @@ class FlaskTestCase(unittest.TestCase): with catcher: callable(*args, **kwargs) + def assert_true(self, x): + self.assertTrue(x) + class _ExceptionCatcher(object): diff --git a/flask/testsuite/appctx.py b/flask/testsuite/appctx.py index afed923a..54b9014e 100644 --- a/flask/testsuite/appctx.py +++ b/flask/testsuite/appctx.py @@ -87,7 +87,7 @@ class AppContextTestCase(FlaskTestCase): with flask._app_ctx_stack.top: with flask._request_ctx_stack.top: pass - self.assert_(flask._request_ctx_stack.request.environ + self.assert_true(flask._request_ctx_stack.request.environ ['werkzeug.request'] is not None) c = app.test_client() c.get('/') diff --git a/flask/testsuite/basic.py b/flask/testsuite/basic.py index c76204d7..20c2f0cc 100644 --- a/flask/testsuite/basic.py +++ b/flask/testsuite/basic.py @@ -78,7 +78,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS']) rv = c.head('/') self.assert_equal(rv.status_code, 200) - self.assert_(not rv.data) # head truncates + self.assert_true(not rv.data) # head truncates self.assert_equal(c.post('/more').data, b'POST') self.assert_equal(c.get('/more').data, b'GET') rv = c.delete('/more') @@ -102,7 +102,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS']) rv = c.head('/') self.assert_equal(rv.status_code, 200) - self.assert_(not rv.data) # head truncates + self.assert_true(not rv.data) # head truncates self.assert_equal(c.post('/more').data, b'POST') self.assert_equal(c.get('/more').data, b'GET') rv = c.delete('/more') @@ -173,8 +173,8 @@ class BasicFunctionalityTestCase(FlaskTestCase): flask.session['testing'] = 42 return 'Hello World' rv = app.test_client().get('/', 'http://example.com/') - self.assert_('domain=.example.com' in rv.headers['set-cookie'].lower()) - self.assert_('httponly' in rv.headers['set-cookie'].lower()) + self.assert_true('domain=.example.com' in rv.headers['set-cookie'].lower()) + self.assert_true('httponly' in rv.headers['set-cookie'].lower()) def test_session_using_server_name_and_port(self): app = flask.Flask(__name__) @@ -187,8 +187,8 @@ class BasicFunctionalityTestCase(FlaskTestCase): flask.session['testing'] = 42 return 'Hello World' rv = app.test_client().get('/', 'http://example.com:8080/') - self.assert_('domain=.example.com' in rv.headers['set-cookie'].lower()) - self.assert_('httponly' in rv.headers['set-cookie'].lower()) + self.assert_true('domain=.example.com' in rv.headers['set-cookie'].lower()) + self.assert_true('httponly' in rv.headers['set-cookie'].lower()) def test_session_using_server_name_port_and_path(self): app = flask.Flask(__name__) @@ -202,9 +202,9 @@ class BasicFunctionalityTestCase(FlaskTestCase): flask.session['testing'] = 42 return 'Hello World' rv = app.test_client().get('/', 'http://example.com:8080/foo') - self.assert_('domain=example.com' in rv.headers['set-cookie'].lower()) - self.assert_('path=/foo' in rv.headers['set-cookie'].lower()) - self.assert_('httponly' in rv.headers['set-cookie'].lower()) + self.assert_true('domain=example.com' in rv.headers['set-cookie'].lower()) + self.assert_true('path=/foo' in rv.headers['set-cookie'].lower()) + self.assert_true('httponly' in rv.headers['set-cookie'].lower()) def test_session_using_application_root(self): class PrefixPathMiddleware(object): @@ -226,7 +226,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): flask.session['testing'] = 42 return 'Hello World' rv = app.test_client().get('/', 'http://example.com:8080/') - self.assert_('path=/bar' in rv.headers['set-cookie'].lower()) + self.assert_true('path=/bar' in rv.headers['set-cookie'].lower()) def test_session_using_session_settings(self): app = flask.Flask(__name__) @@ -245,10 +245,10 @@ class BasicFunctionalityTestCase(FlaskTestCase): return 'Hello World' rv = app.test_client().get('/', 'http://www.example.com:8080/test/') cookie = rv.headers['set-cookie'].lower() - self.assert_('domain=.example.com' in cookie) - self.assert_('path=/;' in cookie) - self.assert_('secure' in cookie) - self.assert_('httponly' not in cookie) + self.assert_true('domain=.example.com' in cookie) + self.assert_true('path=/;' in cookie) + self.assert_true('secure' in cookie) + self.assert_true('httponly' not in cookie) def test_missing_session(self): app = flask.Flask(__name__) @@ -256,11 +256,11 @@ class BasicFunctionalityTestCase(FlaskTestCase): try: f(*args, **kwargs) except RuntimeError as e: - self.assert_(e.args and 'session is unavailable' in e.args[0]) + self.assert_true(e.args and 'session is unavailable' in e.args[0]) else: - self.assert_(False, 'expected exception') + self.assert_true(False, 'expected exception') with app.test_request_context(): - self.assert_(flask.session.get('missing_key') is None) + self.assert_true(flask.session.get('missing_key') is None) expect_exception(flask.session.__setitem__, 'foo', 42) expect_exception(flask.session.pop, 'foo') @@ -280,7 +280,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): client = app.test_client() rv = client.get('/') - self.assert_('set-cookie' in rv.headers) + self.assert_true('set-cookie' in rv.headers) match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie']) expires = parse_date(match.group()) expected = datetime.utcnow() + app.permanent_session_lifetime @@ -293,9 +293,9 @@ class BasicFunctionalityTestCase(FlaskTestCase): permanent = False rv = app.test_client().get('/') - self.assert_('set-cookie' in rv.headers) + self.assert_true('set-cookie' in rv.headers) match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie']) - self.assert_(match is None) + self.assert_true(match is None) def test_session_stored_last(self): app = flask.Flask(__name__) @@ -347,11 +347,11 @@ class BasicFunctionalityTestCase(FlaskTestCase): app.secret_key = 'testkey' with app.test_request_context(): - self.assert_(not flask.session.modified) + self.assert_true(not flask.session.modified) flask.flash('Zap') flask.session.modified = False flask.flash('Zip') - self.assert_(flask.session.modified) + self.assert_true(flask.session.modified) self.assert_equal(list(flask.get_flashed_messages()), ['Zap', 'Zip']) def test_extended_flashing(self): @@ -448,12 +448,12 @@ class BasicFunctionalityTestCase(FlaskTestCase): return response @app.route('/') def index(): - self.assert_('before' in evts) - self.assert_('after' not in evts) + self.assert_true('before' in evts) + self.assert_true('after' not in evts) return 'request' - self.assert_('after' not in evts) + self.assert_true('after' not in evts) rv = app.test_client().get('/').data - self.assert_(b'after' in evts) + self.assert_true(b'after' in evts) self.assert_equal(rv, b'request|after') def test_after_request_processing(self): @@ -483,7 +483,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): return "Response" rv = app.test_client().get('/') self.assert_equal(rv.status_code, 200) - self.assert_(b'Response' in rv.data) + self.assert_true(b'Response' in rv.data) self.assert_equal(len(called), 1) def test_teardown_request_handler_debug_mode(self): @@ -499,7 +499,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): return "Response" rv = app.test_client().get('/') self.assert_equal(rv.status_code, 200) - self.assert_(b'Response' in rv.data) + self.assert_true(b'Response' in rv.data) self.assert_equal(len(called), 1) def test_teardown_request_handler_error(self): @@ -532,7 +532,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): 1/0 rv = app.test_client().get('/') self.assert_equal(rv.status_code, 500) - self.assert_(b'Internal Server Error' in rv.data) + self.assert_true(b'Internal Server Error' in rv.data) self.assert_equal(len(called), 2) def test_before_after_request_order(self): @@ -606,7 +606,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): app = flask.Flask(__name__) @app.errorhandler(MyException) def handle_my_exception(e): - self.assert_(isinstance(e, MyException)) + self.assert_true(isinstance(e, MyException)) return '42' @app.route('/') def index(): @@ -629,7 +629,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): try: c.get('/fail') except KeyError as e: - self.assert_(isinstance(e, BadRequest)) + self.assert_true(isinstance(e, BadRequest)) else: self.fail('Expected exception') @@ -664,8 +664,8 @@ class BasicFunctionalityTestCase(FlaskTestCase): try: c.post('/fail', data={'foo': 'index.txt'}) except DebugFilesKeyError as e: - self.assert_('no file contents were transmitted' in str(e)) - self.assert_('This was submitted: "index.txt"' in str(e)) + self.assert_true('no file contents were transmitted' in str(e)) + self.assert_true('This was submitted: "index.txt"' in str(e)) else: self.fail('Expected exception') @@ -804,7 +804,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): self.assert_equal(str(e), 'View function did not return a response') pass else: - self.assert_("Expected ValueError") + self.assert_true("Expected ValueError") def test_request_locals(self): self.assert_equal(repr(flask.g), '') @@ -894,11 +894,11 @@ class BasicFunctionalityTestCase(FlaskTestCase): @app.before_request def always_first(): flask.request.form['myfile'] - self.assert_(False) + self.assert_true(False) @app.route('/accept', methods=['POST']) def accept_file(): flask.request.form['myfile'] - self.assert_(False) + self.assert_true(False) @app.errorhandler(413) def catcher(error): return '42' @@ -967,14 +967,14 @@ class BasicFunctionalityTestCase(FlaskTestCase): @app.route('/') def index(): return 'Awesome' - self.assert_(not app.got_first_request) + self.assert_true(not app.got_first_request) self.assert_equal(app.test_client().get('/').data, b'Awesome') try: @app.route('/foo') def broken(): return 'Meh' except AssertionError as e: - self.assert_('A setup function was called' in str(e)) + self.assert_true('A setup function was called' in str(e)) else: self.fail('Expected exception') @@ -983,7 +983,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): def working(): return 'Meh' self.assert_equal(app.test_client().get('/foo').data, b'Meh') - self.assert_(app.got_first_request) + self.assert_true(app.got_first_request) def test_before_first_request_functions(self): got = [] @@ -996,7 +996,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): self.assert_equal(got, [42]) c.get('/') self.assert_equal(got, [42]) - self.assert_(app.got_first_request) + self.assert_true(app.got_first_request) def test_routing_redirect_debugging(self): app = flask.Flask(__name__) @@ -1008,8 +1008,8 @@ class BasicFunctionalityTestCase(FlaskTestCase): try: c.post('/foo', data={}) except AssertionError as e: - self.assert_('http://localhost/foo/' in str(e)) - self.assert_('Make sure to directly send your POST-request ' + self.assert_true('http://localhost/foo/' in str(e)) + self.assert_true('Make sure to directly send your POST-request ' 'to this URL' in str(e)) else: self.fail('Expected exception') @@ -1061,12 +1061,12 @@ class BasicFunctionalityTestCase(FlaskTestCase): with self.assert_raises(ZeroDivisionError): c.get('/fail') - self.assert_(flask._request_ctx_stack.top is not None) - self.assert_(flask._app_ctx_stack.top is not None) + self.assert_true(flask._request_ctx_stack.top is not None) + self.assert_true(flask._app_ctx_stack.top is not None) # implicit appctx disappears too flask._request_ctx_stack.top.pop() - self.assert_(flask._request_ctx_stack.top is None) - self.assert_(flask._app_ctx_stack.top is None) + self.assert_true(flask._request_ctx_stack.top is None) + self.assert_true(flask._app_ctx_stack.top is None) class SubdomainTestCase(FlaskTestCase): diff --git a/flask/testsuite/blueprints.py b/flask/testsuite/blueprints.py index ed3ddbb2..088c72d2 100644 --- a/flask/testsuite/blueprints.py +++ b/flask/testsuite/blueprints.py @@ -185,7 +185,7 @@ class ModuleTestCase(FlaskTestCase): except TemplateNotFound as e: self.assert_equal(e.name, 'missing.html') else: - self.assert_(0, 'expected exception') + self.assert_true(0, 'expected exception') with flask.Flask(__name__).test_request_context(): self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested') @@ -201,13 +201,13 @@ class ModuleTestCase(FlaskTestCase): except NotFound: pass else: - self.assert_(0, 'expected exception') + self.assert_true(0, 'expected exception') try: f('../__init__.py') except NotFound: pass else: - self.assert_(0, 'expected exception') + self.assert_true(0, 'expected exception') # testcase for a security issue that may exist on windows systems import os @@ -220,7 +220,7 @@ class ModuleTestCase(FlaskTestCase): except NotFound: pass else: - self.assert_(0, 'expected exception') + self.assert_true(0, 'expected exception') finally: os.path = old_path @@ -380,7 +380,7 @@ class BlueprintTestCase(FlaskTestCase): except TemplateNotFound as e: self.assert_equal(e.name, 'missing.html') else: - self.assert_(0, 'expected exception') + self.assert_true(0, 'expected exception') with flask.Flask(__name__).test_request_context(): self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested') @@ -547,7 +547,7 @@ class BlueprintTestCase(FlaskTestCase): return s[::-1] app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') - self.assert_('my_reverse' in app.jinja_env.filters.keys()) + self.assert_true('my_reverse' in app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse) self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba') @@ -558,7 +558,7 @@ class BlueprintTestCase(FlaskTestCase): bp.add_app_template_filter(my_reverse) app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') - self.assert_('my_reverse' in app.jinja_env.filters.keys()) + self.assert_true('my_reverse' in app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse) self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba') @@ -569,7 +569,7 @@ class BlueprintTestCase(FlaskTestCase): return s[::-1] app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') - self.assert_('strrev' in app.jinja_env.filters.keys()) + self.assert_true('strrev' in app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['strrev'], my_reverse) self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba') @@ -580,7 +580,7 @@ class BlueprintTestCase(FlaskTestCase): bp.add_app_template_filter(my_reverse, 'strrev') app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') - self.assert_('strrev' in app.jinja_env.filters.keys()) + self.assert_true('strrev' in app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['strrev'], my_reverse) self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba') @@ -656,9 +656,9 @@ class BlueprintTestCase(FlaskTestCase): return isinstance(value, bool) app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') - self.assert_('is_boolean' in app.jinja_env.tests.keys()) + self.assert_true('is_boolean' in app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['is_boolean'], is_boolean) - self.assert_(app.jinja_env.tests['is_boolean'](False)) + self.assert_true(app.jinja_env.tests['is_boolean'](False)) def test_add_template_test(self): bp = flask.Blueprint('bp', __name__) @@ -667,9 +667,9 @@ class BlueprintTestCase(FlaskTestCase): bp.add_app_template_test(is_boolean) app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') - self.assert_('is_boolean' in app.jinja_env.tests.keys()) + self.assert_true('is_boolean' in app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['is_boolean'], is_boolean) - self.assert_(app.jinja_env.tests['is_boolean'](False)) + self.assert_true(app.jinja_env.tests['is_boolean'](False)) def test_template_test_with_name(self): bp = flask.Blueprint('bp', __name__) @@ -678,9 +678,9 @@ class BlueprintTestCase(FlaskTestCase): return isinstance(value, bool) app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') - self.assert_('boolean' in app.jinja_env.tests.keys()) + self.assert_true('boolean' in app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['boolean'], is_boolean) - self.assert_(app.jinja_env.tests['boolean'](False)) + self.assert_true(app.jinja_env.tests['boolean'](False)) def test_add_template_test_with_name(self): bp = flask.Blueprint('bp', __name__) @@ -689,9 +689,9 @@ class BlueprintTestCase(FlaskTestCase): bp.add_app_template_test(is_boolean, 'boolean') app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') - self.assert_('boolean' in app.jinja_env.tests.keys()) + self.assert_true('boolean' in app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['boolean'], is_boolean) - self.assert_(app.jinja_env.tests['boolean'](False)) + self.assert_true(app.jinja_env.tests['boolean'](False)) def test_template_test_with_template(self): bp = flask.Blueprint('bp', __name__) @@ -704,7 +704,7 @@ class BlueprintTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_(b'Success!' in rv.data) + self.assert_true(b'Success!' in rv.data) def test_template_test_after_route_with_template(self): app = flask.Flask(__name__) @@ -717,7 +717,7 @@ class BlueprintTestCase(FlaskTestCase): return isinstance(value, bool) app.register_blueprint(bp, url_prefix='/py') rv = app.test_client().get('/') - self.assert_(b'Success!' in rv.data) + self.assert_true(b'Success!' in rv.data) def test_add_template_test_with_template(self): bp = flask.Blueprint('bp', __name__) @@ -730,7 +730,7 @@ class BlueprintTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_(b'Success!' in rv.data) + self.assert_true(b'Success!' in rv.data) def test_template_test_with_name_and_template(self): bp = flask.Blueprint('bp', __name__) @@ -743,7 +743,7 @@ class BlueprintTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_(b'Success!' in rv.data) + self.assert_true(b'Success!' in rv.data) def test_add_template_test_with_name_and_template(self): bp = flask.Blueprint('bp', __name__) @@ -756,7 +756,7 @@ class BlueprintTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_(b'Success!' in rv.data) + self.assert_true(b'Success!' in rv.data) def suite(): suite = unittest.TestSuite() diff --git a/flask/testsuite/config.py b/flask/testsuite/config.py index 415d8aca..6633c6ba 100644 --- a/flask/testsuite/config.py +++ b/flask/testsuite/config.py @@ -28,7 +28,7 @@ class ConfigTestCase(FlaskTestCase): def common_object_test(self, app): self.assert_equal(app.secret_key, 'devkey') self.assert_equal(app.config['TEST_KEY'], 'foo') - self.assert_('ConfigTestCase' not in app.config) + self.assert_true('ConfigTestCase' not in app.config) def test_config_from_file(self): app = flask.Flask(__name__) @@ -57,13 +57,13 @@ class ConfigTestCase(FlaskTestCase): try: app.config.from_envvar('FOO_SETTINGS') except RuntimeError as e: - self.assert_("'FOO_SETTINGS' is not set" in str(e)) + self.assert_true("'FOO_SETTINGS' is not set" in str(e)) else: - self.assert_(0, 'expected exception') - self.assert_(not app.config.from_envvar('FOO_SETTINGS', silent=True)) + self.assert_true(0, 'expected exception') + self.assert_true(not app.config.from_envvar('FOO_SETTINGS', silent=True)) os.environ = {'FOO_SETTINGS': __file__.rsplit('.', 1)[0] + '.py'} - self.assert_(app.config.from_envvar('FOO_SETTINGS')) + self.assert_true(app.config.from_envvar('FOO_SETTINGS')) self.common_object_test(app) finally: os.environ = env @@ -77,9 +77,9 @@ class ConfigTestCase(FlaskTestCase): app.config.from_envvar('FOO_SETTINGS') except IOError as e: msg = str(e) - self.assert_(msg.startswith('[Errno 2] Unable to load configuration ' + self.assert_true(msg.startswith('[Errno 2] Unable to load configuration ' 'file (No such file or directory):')) - self.assert_(msg.endswith("missing.cfg'")) + self.assert_true(msg.endswith("missing.cfg'")) else: self.fail('expected IOError') self.assertFalse(app.config.from_envvar('FOO_SETTINGS', silent=True)) @@ -92,12 +92,12 @@ class ConfigTestCase(FlaskTestCase): app.config.from_pyfile('missing.cfg') except IOError as e: msg = str(e) - self.assert_(msg.startswith('[Errno 2] Unable to load configuration ' + self.assert_true(msg.startswith('[Errno 2] Unable to load configuration ' 'file (No such file or directory):')) - self.assert_(msg.endswith("missing.cfg'")) + self.assert_true(msg.endswith("missing.cfg'")) else: - self.assert_(0, 'expected config') - self.assert_(not app.config.from_pyfile('missing.cfg', silent=True)) + self.assert_true(0, 'expected config') + self.assert_true(not app.config.from_pyfile('missing.cfg', silent=True)) def test_session_lifetime(self): app = flask.Flask(__name__) @@ -141,7 +141,7 @@ class InstanceTestCase(FlaskTestCase): try: flask.Flask(__name__, instance_path='instance') except ValueError as e: - self.assert_('must be absolute' in str(e)) + self.assert_true('must be absolute' in str(e)) else: self.fail('Expected value error') diff --git a/flask/testsuite/ext.py b/flask/testsuite/ext.py index 147e23b0..a6d1be9d 100644 --- a/flask/testsuite/ext.py +++ b/flask/testsuite/ext.py @@ -42,7 +42,7 @@ class ExtImportHookTestCase(FlaskTestCase): def teardown(self): from flask import ext for key in ext.__dict__: - self.assert_('.' not in key) + self.assert_true('.' not in key) def test_flaskext_new_simple_import_normal(self): from flask.ext.newext_simple import ext_id @@ -108,12 +108,12 @@ class ExtImportHookTestCase(FlaskTestCase): import flask.ext.broken except ImportError: exc_type, exc_value, tb = sys.exc_info() - self.assert_(exc_type is ImportError) + self.assert_true(exc_type is ImportError) self.assert_equal(str(exc_value), 'No module named missing_module') - self.assert_(tb.tb_frame.f_globals is globals()) + self.assert_true(tb.tb_frame.f_globals is globals()) next = tb.tb_next - self.assert_('flask_broken/__init__.py' in next.tb_frame.f_code.co_filename) + self.assert_true('flask_broken/__init__.py' in next.tb_frame.f_code.co_filename) def suite(): diff --git a/flask/testsuite/helpers.py b/flask/testsuite/helpers.py index 9ca9eec3..702ab517 100644 --- a/flask/testsuite/helpers.py +++ b/flask/testsuite/helpers.py @@ -48,8 +48,8 @@ class JSONTestCase(FlaskTestCase): rv = c.post('/json', data='malformed', content_type='application/json') self.assert_equal(rv.status_code, 400) self.assert_equal(rv.mimetype, 'application/json') - self.assert_('description' in flask.json.loads(rv.data)) - self.assert_('

' not in flask.json.loads(rv.data)['description']) + self.assert_true('description' in flask.json.loads(rv.data)) + self.assert_true('

' not in flask.json.loads(rv.data)['description']) def test_json_body_encoding(self): app = flask.Flask(__name__) @@ -167,7 +167,7 @@ class SendfileTestCase(FlaskTestCase): app = flask.Flask(__name__) with app.test_request_context(): rv = flask.send_file('static/index.html') - self.assert_(rv.direct_passthrough) + self.assert_true(rv.direct_passthrough) self.assert_equal(rv.mimetype, 'text/html') with app.open_resource('static/index.html') as f: self.assert_equal(rv.data, f.read()) @@ -177,8 +177,8 @@ class SendfileTestCase(FlaskTestCase): app.use_x_sendfile = True with app.test_request_context(): rv = flask.send_file('static/index.html') - self.assert_(rv.direct_passthrough) - self.assert_('x-sendfile' in rv.headers) + self.assert_true(rv.direct_passthrough) + self.assert_true('x-sendfile' in rv.headers) self.assert_equal(rv.headers['x-sendfile'], os.path.join(app.root_path, 'static/index.html')) self.assert_equal(rv.mimetype, 'text/html') @@ -201,7 +201,7 @@ class SendfileTestCase(FlaskTestCase): f = open(os.path.join(app.root_path, 'static/index.html')) rv = flask.send_file(f) self.assert_equal(rv.mimetype, 'text/html') - self.assert_('x-sendfile' in rv.headers) + self.assert_true('x-sendfile' in rv.headers) self.assert_equal(rv.headers['x-sendfile'], os.path.join(app.root_path, 'static/index.html')) # mimetypes + etag @@ -229,7 +229,7 @@ class SendfileTestCase(FlaskTestCase): with app.test_request_context(): f = StringIO('Test') rv = flask.send_file(f) - self.assert_('x-sendfile' not in rv.headers) + self.assert_true('x-sendfile' not in rv.headers) # etags self.assert_equal(len(captured), 1) @@ -302,10 +302,10 @@ class LoggingTestCase(FlaskTestCase): def test_logger_cache(self): app = flask.Flask(__name__) logger1 = app.logger - self.assert_(app.logger is logger1) + self.assert_true(app.logger is logger1) self.assert_equal(logger1.name, __name__) app.logger_name = __name__ + '/test_logger_cache' - self.assert_(app.logger is not logger1) + self.assert_true(app.logger is not logger1) def test_debug_log(self): app = flask.Flask(__name__) @@ -325,10 +325,10 @@ class LoggingTestCase(FlaskTestCase): with catch_stderr() as err: c.get('/') out = err.getvalue() - self.assert_('WARNING in helpers [' in out) - self.assert_(os.path.basename(__file__.rsplit('.', 1)[0] + '.py') in out) - self.assert_('the standard library is dead' in out) - self.assert_('this is a debug statement' in out) + self.assert_true('WARNING in helpers [' in out) + self.assert_true(os.path.basename(__file__.rsplit('.', 1)[0] + '.py') in out) + self.assert_true('the standard library is dead' in out) + self.assert_true('this is a debug statement' in out) with catch_stderr() as err: try: @@ -336,7 +336,7 @@ class LoggingTestCase(FlaskTestCase): except ZeroDivisionError: pass else: - self.assert_(False, 'debug log ate the exception') + self.assert_true(False, 'debug log ate the exception') def test_debug_log_override(self): app = flask.Flask(__name__) @@ -357,13 +357,13 @@ class LoggingTestCase(FlaskTestCase): rv = app.test_client().get('/') self.assert_equal(rv.status_code, 500) - self.assert_(b'Internal Server Error' in rv.data) + self.assert_true(b'Internal Server Error' in rv.data) err = out.getvalue() - self.assert_('Exception on / [GET]' in err) - self.assert_('Traceback (most recent call last):' in err) - self.assert_('1/0' in err) - self.assert_('ZeroDivisionError:' in err) + self.assert_true('Exception on / [GET]' in err) + self.assert_true('Traceback (most recent call last):' in err) + self.assert_true('1/0' in err) + self.assert_true('ZeroDivisionError:' in err) def test_processor_exceptions(self): app = flask.Flask(__name__) diff --git a/flask/testsuite/reqctx.py b/flask/testsuite/reqctx.py index 6e379448..69b43f84 100644 --- a/flask/testsuite/reqctx.py +++ b/flask/testsuite/reqctx.py @@ -57,7 +57,7 @@ class RequestContextTestCase(FlaskTestCase): with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}): pass except Exception as e: - self.assert_(isinstance(e, ValueError)) + self.assert_true(isinstance(e, ValueError)) self.assert_equal(str(e), "the server name provided " + "('localhost.localdomain:5000') does not match the " + \ "server name from the WSGI environment ('localhost')") @@ -93,17 +93,17 @@ class RequestContextTestCase(FlaskTestCase): self.assert_equal(index(), 'Hello World!') with app.test_request_context('/meh'): self.assert_equal(meh(), 'http://localhost/meh') - self.assert_(flask._request_ctx_stack.top is None) + self.assert_true(flask._request_ctx_stack.top is None) def test_context_test(self): app = flask.Flask(__name__) - self.assert_(not flask.request) - self.assert_(not flask.has_request_context()) + self.assert_true(not flask.request) + self.assert_true(not flask.has_request_context()) ctx = app.test_request_context() ctx.push() try: - self.assert_(flask.request) - self.assert_(flask.has_request_context()) + self.assert_true(flask.request) + self.assert_true(flask.has_request_context()) finally: ctx.pop() @@ -122,7 +122,7 @@ class RequestContextTestCase(FlaskTestCase): except RuntimeError: pass else: - self.assert_(0, 'expected runtime error') + self.assert_true(0, 'expected runtime error') def test_greenlet_context_copying(self): app = flask.Flask(__name__) @@ -132,14 +132,14 @@ class RequestContextTestCase(FlaskTestCase): def index(): reqctx = flask._request_ctx_stack.top.copy() def g(): - self.assert_(not flask.request) - self.assert_(not flask.current_app) + self.assert_true(not flask.request) + self.assert_true(not flask.current_app) with reqctx: - self.assert_(flask.request) + self.assert_true(flask.request) self.assert_equal(flask.current_app, app) self.assert_equal(flask.request.path, '/') self.assert_equal(flask.request.args['foo'], 'bar') - self.assert_(not flask.request) + self.assert_true(not flask.request) return 42 greenlets.append(greenlet(g)) return 'Hello World!' @@ -159,7 +159,7 @@ class RequestContextTestCase(FlaskTestCase): reqctx = flask._request_ctx_stack.top.copy() @flask.copy_current_request_context def g(): - self.assert_(flask.request) + self.assert_true(flask.request) self.assert_equal(flask.current_app, app) self.assert_equal(flask.request.path, '/') self.assert_equal(flask.request.args['foo'], 'bar') diff --git a/flask/testsuite/signals.py b/flask/testsuite/signals.py index 843c2f83..ffd575c1 100644 --- a/flask/testsuite/signals.py +++ b/flask/testsuite/signals.py @@ -92,7 +92,7 @@ class SignalsTestCase(FlaskTestCase): try: self.assert_equal(app.test_client().get('/').status_code, 500) self.assert_equal(len(recorded), 1) - self.assert_(isinstance(recorded[0], ZeroDivisionError)) + self.assert_true(isinstance(recorded[0], ZeroDivisionError)) finally: flask.got_request_exception.disconnect(record, app) diff --git a/flask/testsuite/subclassing.py b/flask/testsuite/subclassing.py index e26b9085..a3cf5d0e 100644 --- a/flask/testsuite/subclassing.py +++ b/flask/testsuite/subclassing.py @@ -34,7 +34,7 @@ class FlaskSubclassingTestCase(FlaskTestCase): rv = app.test_client().get('/') self.assert_equal(rv.status_code, 500) - self.assert_(b'Internal Server Error' in rv.data) + self.assert_true(b'Internal Server Error' in rv.data) err = out.getvalue() self.assert_equal(err, '') diff --git a/flask/testsuite/templating.py b/flask/testsuite/templating.py index 0d3a2a5c..08a54d06 100644 --- a/flask/testsuite/templating.py +++ b/flask/testsuite/templating.py @@ -99,7 +99,7 @@ class TemplatingTestCase(FlaskTestCase): @app.template_filter() def my_reverse(s): return s[::-1] - self.assert_('my_reverse' in app.jinja_env.filters.keys()) + self.assert_true('my_reverse' in app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse) self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba') @@ -108,7 +108,7 @@ class TemplatingTestCase(FlaskTestCase): def my_reverse(s): return s[::-1] app.add_template_filter(my_reverse) - self.assert_('my_reverse' in app.jinja_env.filters.keys()) + self.assert_true('my_reverse' in app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse) self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba') @@ -117,7 +117,7 @@ class TemplatingTestCase(FlaskTestCase): @app.template_filter('strrev') def my_reverse(s): return s[::-1] - self.assert_('strrev' in app.jinja_env.filters.keys()) + self.assert_true('strrev' in app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['strrev'], my_reverse) self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba') @@ -126,7 +126,7 @@ class TemplatingTestCase(FlaskTestCase): def my_reverse(s): return s[::-1] app.add_template_filter(my_reverse, 'strrev') - self.assert_('strrev' in app.jinja_env.filters.keys()) + self.assert_true('strrev' in app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['strrev'], my_reverse) self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba') @@ -179,36 +179,36 @@ class TemplatingTestCase(FlaskTestCase): @app.template_test() def boolean(value): return isinstance(value, bool) - self.assert_('boolean' in app.jinja_env.tests.keys()) + self.assert_true('boolean' in app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['boolean'], boolean) - self.assert_(app.jinja_env.tests['boolean'](False)) + self.assert_true(app.jinja_env.tests['boolean'](False)) def test_add_template_test(self): app = flask.Flask(__name__) def boolean(value): return isinstance(value, bool) app.add_template_test(boolean) - self.assert_('boolean' in app.jinja_env.tests.keys()) + self.assert_true('boolean' in app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['boolean'], boolean) - self.assert_(app.jinja_env.tests['boolean'](False)) + self.assert_true(app.jinja_env.tests['boolean'](False)) def test_template_test_with_name(self): app = flask.Flask(__name__) @app.template_test('boolean') def is_boolean(value): return isinstance(value, bool) - self.assert_('boolean' in app.jinja_env.tests.keys()) + self.assert_true('boolean' in app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['boolean'], is_boolean) - self.assert_(app.jinja_env.tests['boolean'](False)) + self.assert_true(app.jinja_env.tests['boolean'](False)) def test_add_template_test_with_name(self): app = flask.Flask(__name__) def is_boolean(value): return isinstance(value, bool) app.add_template_test(is_boolean, 'boolean') - self.assert_('boolean' in app.jinja_env.tests.keys()) + self.assert_true('boolean' in app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['boolean'], is_boolean) - self.assert_(app.jinja_env.tests['boolean'](False)) + self.assert_true(app.jinja_env.tests['boolean'](False)) def test_template_test_with_template(self): app = flask.Flask(__name__) @@ -219,7 +219,7 @@ class TemplatingTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_(b'Success!' in rv.data) + self.assert_true(b'Success!' in rv.data) def test_add_template_test_with_template(self): app = flask.Flask(__name__) @@ -230,7 +230,7 @@ class TemplatingTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_(b'Success!' in rv.data) + self.assert_true(b'Success!' in rv.data) def test_template_test_with_name_and_template(self): app = flask.Flask(__name__) @@ -241,7 +241,7 @@ class TemplatingTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_(b'Success!' in rv.data) + self.assert_true(b'Success!' in rv.data) def test_add_template_test_with_name_and_template(self): app = flask.Flask(__name__) @@ -252,16 +252,16 @@ class TemplatingTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_(b'Success!' in rv.data) + self.assert_true(b'Success!' in rv.data) def test_add_template_global(self): app = flask.Flask(__name__) @app.template_global() def get_stuff(): return 42 - self.assert_('get_stuff' in app.jinja_env.globals.keys()) + self.assert_true('get_stuff' in app.jinja_env.globals.keys()) self.assert_equal(app.jinja_env.globals['get_stuff'], get_stuff) - self.assert_(app.jinja_env.globals['get_stuff'](), 42) + self.assert_true(app.jinja_env.globals['get_stuff'](), 42) with app.app_context(): rv = flask.render_template_string('{{ get_stuff() }}') self.assert_equal(rv, '42') diff --git a/flask/testsuite/testing.py b/flask/testsuite/testing.py index 3379a463..a18db673 100644 --- a/flask/testsuite/testing.py +++ b/flask/testsuite/testing.py @@ -106,7 +106,7 @@ class TestToolsTestCase(FlaskTestCase): with c.session_transaction() as sess: pass except RuntimeError as e: - self.assert_('Session backend did not open a session' in str(e)) + self.assert_true('Session backend did not open a session' in str(e)) else: self.fail('Expected runtime error') @@ -118,9 +118,9 @@ class TestToolsTestCase(FlaskTestCase): with app.test_client() as c: rv = c.get('/') req = flask.request._get_current_object() - self.assert_(req is not None) + self.assert_true(req is not None) with c.session_transaction(): - self.assert_(req is flask.request._get_current_object()) + self.assert_true(req is flask.request._get_current_object()) def test_session_transaction_needs_cookies(self): app = flask.Flask(__name__) @@ -130,7 +130,7 @@ class TestToolsTestCase(FlaskTestCase): with c.session_transaction() as s: pass except RuntimeError as e: - self.assert_('cookies' in str(e)) + self.assert_true('cookies' in str(e)) else: self.fail('Expected runtime error') @@ -152,8 +152,8 @@ class TestToolsTestCase(FlaskTestCase): self.assert_equal(resp.status_code, 200) resp = c.get('/other') - self.assert_(not hasattr(flask.g, 'value')) - self.assert_(b'Internal Server Error' in resp.data) + self.assert_true(not hasattr(flask.g, 'value')) + self.assert_true(b'Internal Server Error' in resp.data) self.assert_equal(resp.status_code, 500) flask.g.value = 23 From 8e9f0bdedca3edd5ba2e8902f05406acff8b8b44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Wed, 22 May 2013 17:30:37 +0200 Subject: [PATCH 24/58] Use assert_equal instead of assertEquals assertEquals is deprecated and its use inconsistent --- flask/testsuite/testing.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/flask/testsuite/testing.py b/flask/testsuite/testing.py index a18db673..2e735c47 100644 --- a/flask/testsuite/testing.py +++ b/flask/testsuite/testing.py @@ -219,8 +219,8 @@ class SubdomainTestCase(FlaskTestCase): url = flask.url_for('view', company_id='xxx') response = self.client.get(url) - self.assertEquals(200, response.status_code) - self.assertEquals(b'xxx', response.data) + self.assert_equal(200, response.status_code) + self.assert_equal(b'xxx', response.data) def test_nosubdomain(self): @@ -231,8 +231,8 @@ class SubdomainTestCase(FlaskTestCase): url = flask.url_for('view', company_id='xxx') response = self.client.get(url) - self.assertEquals(200, response.status_code) - self.assertEquals(b'xxx', response.data) + self.assert_equal(200, response.status_code) + self.assert_equal(b'xxx', response.data) def suite(): From 4d73ef1a194a4280d437db5cbc9ceb8850e99e1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Wed, 22 May 2013 19:19:46 +0200 Subject: [PATCH 25/58] Add missing msg argument to assert_true() --- flask/testsuite/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/flask/testsuite/__init__.py b/flask/testsuite/__init__.py index 2a869173..9088fc52 100644 --- a/flask/testsuite/__init__.py +++ b/flask/testsuite/__init__.py @@ -142,8 +142,8 @@ class FlaskTestCase(unittest.TestCase): with catcher: callable(*args, **kwargs) - def assert_true(self, x): - self.assertTrue(x) + def assert_true(self, x, msg=None): + self.assertTrue(x, msg) class _ExceptionCatcher(object): From 9f8a2075c79fec1b5481f5a5a95bb23b40bf68f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Wed, 22 May 2013 20:12:50 +0200 Subject: [PATCH 26/58] Use assert_in where appropriate --- flask/testsuite/__init__.py | 8 ++++- flask/testsuite/basic.py | 54 +++++++++++++++++----------------- flask/testsuite/blueprints.py | 26 ++++++++-------- flask/testsuite/config.py | 4 +-- flask/testsuite/ext.py | 4 +-- flask/testsuite/helpers.py | 28 +++++++++--------- flask/testsuite/subclassing.py | 2 +- flask/testsuite/templating.py | 26 ++++++++-------- flask/testsuite/testing.py | 6 ++-- 9 files changed, 82 insertions(+), 76 deletions(-) diff --git a/flask/testsuite/__init__.py b/flask/testsuite/__init__.py index 9088fc52..72de1963 100644 --- a/flask/testsuite/__init__.py +++ b/flask/testsuite/__init__.py @@ -103,7 +103,7 @@ def emits_module_deprecation_warning(f): f(self, *args, **kwargs) self.assert_true(log, 'expected deprecation warning') for entry in log: - self.assert_true('Modules are deprecated' in str(entry['message'])) + self.assert_in('Modules are deprecated', str(entry['message'])) return update_wrapper(new_f, f) @@ -145,6 +145,12 @@ class FlaskTestCase(unittest.TestCase): def assert_true(self, x, msg=None): self.assertTrue(x, msg) + def assert_in(self, x, y): + self.assertIn(x, y) + + def assert_not_in(self, x, y): + self.assertNotIn(x, y) + class _ExceptionCatcher(object): diff --git a/flask/testsuite/basic.py b/flask/testsuite/basic.py index 20c2f0cc..0abcac10 100644 --- a/flask/testsuite/basic.py +++ b/flask/testsuite/basic.py @@ -173,8 +173,8 @@ class BasicFunctionalityTestCase(FlaskTestCase): flask.session['testing'] = 42 return 'Hello World' rv = app.test_client().get('/', 'http://example.com/') - self.assert_true('domain=.example.com' in rv.headers['set-cookie'].lower()) - self.assert_true('httponly' in rv.headers['set-cookie'].lower()) + self.assert_in('domain=.example.com', rv.headers['set-cookie'].lower()) + self.assert_in('httponly', rv.headers['set-cookie'].lower()) def test_session_using_server_name_and_port(self): app = flask.Flask(__name__) @@ -187,8 +187,8 @@ class BasicFunctionalityTestCase(FlaskTestCase): flask.session['testing'] = 42 return 'Hello World' rv = app.test_client().get('/', 'http://example.com:8080/') - self.assert_true('domain=.example.com' in rv.headers['set-cookie'].lower()) - self.assert_true('httponly' in rv.headers['set-cookie'].lower()) + self.assert_in('domain=.example.com', rv.headers['set-cookie'].lower()) + self.assert_in('httponly', rv.headers['set-cookie'].lower()) def test_session_using_server_name_port_and_path(self): app = flask.Flask(__name__) @@ -202,9 +202,9 @@ class BasicFunctionalityTestCase(FlaskTestCase): flask.session['testing'] = 42 return 'Hello World' rv = app.test_client().get('/', 'http://example.com:8080/foo') - self.assert_true('domain=example.com' in rv.headers['set-cookie'].lower()) - self.assert_true('path=/foo' in rv.headers['set-cookie'].lower()) - self.assert_true('httponly' in rv.headers['set-cookie'].lower()) + self.assert_in('domain=example.com', rv.headers['set-cookie'].lower()) + self.assert_in('path=/foo', rv.headers['set-cookie'].lower()) + self.assert_in('httponly', rv.headers['set-cookie'].lower()) def test_session_using_application_root(self): class PrefixPathMiddleware(object): @@ -226,7 +226,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): flask.session['testing'] = 42 return 'Hello World' rv = app.test_client().get('/', 'http://example.com:8080/') - self.assert_true('path=/bar' in rv.headers['set-cookie'].lower()) + self.assert_in('path=/bar', rv.headers['set-cookie'].lower()) def test_session_using_session_settings(self): app = flask.Flask(__name__) @@ -245,10 +245,10 @@ class BasicFunctionalityTestCase(FlaskTestCase): return 'Hello World' rv = app.test_client().get('/', 'http://www.example.com:8080/test/') cookie = rv.headers['set-cookie'].lower() - self.assert_true('domain=.example.com' in cookie) - self.assert_true('path=/;' in cookie) - self.assert_true('secure' in cookie) - self.assert_true('httponly' not in cookie) + self.assert_in('domain=.example.com', cookie) + self.assert_in('path=/;', cookie) + self.assert_in('secure', cookie) + self.assert_not_in('httponly', cookie) def test_missing_session(self): app = flask.Flask(__name__) @@ -280,7 +280,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): client = app.test_client() rv = client.get('/') - self.assert_true('set-cookie' in rv.headers) + self.assert_in('set-cookie', rv.headers) match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie']) expires = parse_date(match.group()) expected = datetime.utcnow() + app.permanent_session_lifetime @@ -293,7 +293,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): permanent = False rv = app.test_client().get('/') - self.assert_true('set-cookie' in rv.headers) + self.assert_in('set-cookie', rv.headers) match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie']) self.assert_true(match is None) @@ -448,12 +448,12 @@ class BasicFunctionalityTestCase(FlaskTestCase): return response @app.route('/') def index(): - self.assert_true('before' in evts) - self.assert_true('after' not in evts) + self.assert_in('before', evts) + self.assert_not_in('after', evts) return 'request' - self.assert_true('after' not in evts) + self.assert_not_in('after', evts) rv = app.test_client().get('/').data - self.assert_true(b'after' in evts) + self.assert_in(b'after', evts) self.assert_equal(rv, b'request|after') def test_after_request_processing(self): @@ -483,7 +483,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): return "Response" rv = app.test_client().get('/') self.assert_equal(rv.status_code, 200) - self.assert_true(b'Response' in rv.data) + self.assert_in(b'Response', rv.data) self.assert_equal(len(called), 1) def test_teardown_request_handler_debug_mode(self): @@ -499,7 +499,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): return "Response" rv = app.test_client().get('/') self.assert_equal(rv.status_code, 200) - self.assert_true(b'Response' in rv.data) + self.assert_in(b'Response', rv.data) self.assert_equal(len(called), 1) def test_teardown_request_handler_error(self): @@ -532,7 +532,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): 1/0 rv = app.test_client().get('/') self.assert_equal(rv.status_code, 500) - self.assert_true(b'Internal Server Error' in rv.data) + self.assert_in(b'Internal Server Error', rv.data) self.assert_equal(len(called), 2) def test_before_after_request_order(self): @@ -664,8 +664,8 @@ class BasicFunctionalityTestCase(FlaskTestCase): try: c.post('/fail', data={'foo': 'index.txt'}) except DebugFilesKeyError as e: - self.assert_true('no file contents were transmitted' in str(e)) - self.assert_true('This was submitted: "index.txt"' in str(e)) + self.assert_in('no file contents were transmitted', str(e)) + self.assert_in('This was submitted: "index.txt"', str(e)) else: self.fail('Expected exception') @@ -974,7 +974,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): def broken(): return 'Meh' except AssertionError as e: - self.assert_true('A setup function was called' in str(e)) + self.assert_in('A setup function was called', str(e)) else: self.fail('Expected exception') @@ -1008,9 +1008,9 @@ class BasicFunctionalityTestCase(FlaskTestCase): try: c.post('/foo', data={}) except AssertionError as e: - self.assert_true('http://localhost/foo/' in str(e)) - self.assert_true('Make sure to directly send your POST-request ' - 'to this URL' in str(e)) + self.assert_in('http://localhost/foo/', str(e)) + self.assert_in('Make sure to directly send your POST-request ' + 'to this URL', str(e)) else: self.fail('Expected exception') diff --git a/flask/testsuite/blueprints.py b/flask/testsuite/blueprints.py index 088c72d2..89a8f2d7 100644 --- a/flask/testsuite/blueprints.py +++ b/flask/testsuite/blueprints.py @@ -547,7 +547,7 @@ class BlueprintTestCase(FlaskTestCase): return s[::-1] app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') - self.assert_true('my_reverse' in app.jinja_env.filters.keys()) + self.assert_in('my_reverse', app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse) self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba') @@ -558,7 +558,7 @@ class BlueprintTestCase(FlaskTestCase): bp.add_app_template_filter(my_reverse) app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') - self.assert_true('my_reverse' in app.jinja_env.filters.keys()) + self.assert_in('my_reverse', app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse) self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba') @@ -569,7 +569,7 @@ class BlueprintTestCase(FlaskTestCase): return s[::-1] app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') - self.assert_true('strrev' in app.jinja_env.filters.keys()) + self.assert_in('strrev', app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['strrev'], my_reverse) self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba') @@ -580,7 +580,7 @@ class BlueprintTestCase(FlaskTestCase): bp.add_app_template_filter(my_reverse, 'strrev') app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') - self.assert_true('strrev' in app.jinja_env.filters.keys()) + self.assert_in('strrev', app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['strrev'], my_reverse) self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba') @@ -656,7 +656,7 @@ class BlueprintTestCase(FlaskTestCase): return isinstance(value, bool) app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') - self.assert_true('is_boolean' in app.jinja_env.tests.keys()) + self.assert_in('is_boolean', app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['is_boolean'], is_boolean) self.assert_true(app.jinja_env.tests['is_boolean'](False)) @@ -667,7 +667,7 @@ class BlueprintTestCase(FlaskTestCase): bp.add_app_template_test(is_boolean) app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') - self.assert_true('is_boolean' in app.jinja_env.tests.keys()) + self.assert_in('is_boolean', app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['is_boolean'], is_boolean) self.assert_true(app.jinja_env.tests['is_boolean'](False)) @@ -678,7 +678,7 @@ class BlueprintTestCase(FlaskTestCase): return isinstance(value, bool) app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') - self.assert_true('boolean' in app.jinja_env.tests.keys()) + self.assert_in('boolean', app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['boolean'], is_boolean) self.assert_true(app.jinja_env.tests['boolean'](False)) @@ -689,7 +689,7 @@ class BlueprintTestCase(FlaskTestCase): bp.add_app_template_test(is_boolean, 'boolean') app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') - self.assert_true('boolean' in app.jinja_env.tests.keys()) + self.assert_in('boolean', app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['boolean'], is_boolean) self.assert_true(app.jinja_env.tests['boolean'](False)) @@ -704,7 +704,7 @@ class BlueprintTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_true(b'Success!' in rv.data) + self.assert_in(b'Success!', rv.data) def test_template_test_after_route_with_template(self): app = flask.Flask(__name__) @@ -717,7 +717,7 @@ class BlueprintTestCase(FlaskTestCase): return isinstance(value, bool) app.register_blueprint(bp, url_prefix='/py') rv = app.test_client().get('/') - self.assert_true(b'Success!' in rv.data) + self.assert_in(b'Success!', rv.data) def test_add_template_test_with_template(self): bp = flask.Blueprint('bp', __name__) @@ -730,7 +730,7 @@ class BlueprintTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_true(b'Success!' in rv.data) + self.assert_in(b'Success!', rv.data) def test_template_test_with_name_and_template(self): bp = flask.Blueprint('bp', __name__) @@ -743,7 +743,7 @@ class BlueprintTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_true(b'Success!' in rv.data) + self.assert_in(b'Success!', rv.data) def test_add_template_test_with_name_and_template(self): bp = flask.Blueprint('bp', __name__) @@ -756,7 +756,7 @@ class BlueprintTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_true(b'Success!' in rv.data) + self.assert_in(b'Success!', rv.data) def suite(): suite = unittest.TestSuite() diff --git a/flask/testsuite/config.py b/flask/testsuite/config.py index 6633c6ba..8aaf5285 100644 --- a/flask/testsuite/config.py +++ b/flask/testsuite/config.py @@ -28,7 +28,7 @@ class ConfigTestCase(FlaskTestCase): def common_object_test(self, app): self.assert_equal(app.secret_key, 'devkey') self.assert_equal(app.config['TEST_KEY'], 'foo') - self.assert_true('ConfigTestCase' not in app.config) + self.assert_not_in('ConfigTestCase', app.config) def test_config_from_file(self): app = flask.Flask(__name__) @@ -141,7 +141,7 @@ class InstanceTestCase(FlaskTestCase): try: flask.Flask(__name__, instance_path='instance') except ValueError as e: - self.assert_true('must be absolute' in str(e)) + self.assert_in('must be absolute', str(e)) else: self.fail('Expected value error') diff --git a/flask/testsuite/ext.py b/flask/testsuite/ext.py index a6d1be9d..04226181 100644 --- a/flask/testsuite/ext.py +++ b/flask/testsuite/ext.py @@ -42,7 +42,7 @@ class ExtImportHookTestCase(FlaskTestCase): def teardown(self): from flask import ext for key in ext.__dict__: - self.assert_true('.' not in key) + self.assert_not_in('.', key) def test_flaskext_new_simple_import_normal(self): from flask.ext.newext_simple import ext_id @@ -113,7 +113,7 @@ class ExtImportHookTestCase(FlaskTestCase): self.assert_true(tb.tb_frame.f_globals is globals()) next = tb.tb_next - self.assert_true('flask_broken/__init__.py' in next.tb_frame.f_code.co_filename) + self.assert_in('flask_broken/__init__.py', next.tb_frame.f_code.co_filename) def suite(): diff --git a/flask/testsuite/helpers.py b/flask/testsuite/helpers.py index 702ab517..b76d36d1 100644 --- a/flask/testsuite/helpers.py +++ b/flask/testsuite/helpers.py @@ -48,8 +48,8 @@ class JSONTestCase(FlaskTestCase): rv = c.post('/json', data='malformed', content_type='application/json') self.assert_equal(rv.status_code, 400) self.assert_equal(rv.mimetype, 'application/json') - self.assert_true('description' in flask.json.loads(rv.data)) - self.assert_true('

' not in flask.json.loads(rv.data)['description']) + self.assert_in('description', flask.json.loads(rv.data)) + self.assert_not_in('

', flask.json.loads(rv.data)['description']) def test_json_body_encoding(self): app = flask.Flask(__name__) @@ -178,7 +178,7 @@ class SendfileTestCase(FlaskTestCase): with app.test_request_context(): rv = flask.send_file('static/index.html') self.assert_true(rv.direct_passthrough) - self.assert_true('x-sendfile' in rv.headers) + self.assert_in('x-sendfile', rv.headers) self.assert_equal(rv.headers['x-sendfile'], os.path.join(app.root_path, 'static/index.html')) self.assert_equal(rv.mimetype, 'text/html') @@ -201,7 +201,7 @@ class SendfileTestCase(FlaskTestCase): f = open(os.path.join(app.root_path, 'static/index.html')) rv = flask.send_file(f) self.assert_equal(rv.mimetype, 'text/html') - self.assert_true('x-sendfile' in rv.headers) + self.assert_in('x-sendfile', rv.headers) self.assert_equal(rv.headers['x-sendfile'], os.path.join(app.root_path, 'static/index.html')) # mimetypes + etag @@ -229,7 +229,7 @@ class SendfileTestCase(FlaskTestCase): with app.test_request_context(): f = StringIO('Test') rv = flask.send_file(f) - self.assert_true('x-sendfile' not in rv.headers) + self.assert_not_in('x-sendfile', rv.headers) # etags self.assert_equal(len(captured), 1) @@ -325,10 +325,10 @@ class LoggingTestCase(FlaskTestCase): with catch_stderr() as err: c.get('/') out = err.getvalue() - self.assert_true('WARNING in helpers [' in out) - self.assert_true(os.path.basename(__file__.rsplit('.', 1)[0] + '.py') in out) - self.assert_true('the standard library is dead' in out) - self.assert_true('this is a debug statement' in out) + self.assert_in('WARNING in helpers [', out) + self.assert_in(os.path.basename(__file__.rsplit('.', 1)[0] + '.py'), out) + self.assert_in('the standard library is dead', out) + self.assert_in('this is a debug statement', out) with catch_stderr() as err: try: @@ -357,13 +357,13 @@ class LoggingTestCase(FlaskTestCase): rv = app.test_client().get('/') self.assert_equal(rv.status_code, 500) - self.assert_true(b'Internal Server Error' in rv.data) + self.assert_in(b'Internal Server Error', rv.data) err = out.getvalue() - self.assert_true('Exception on / [GET]' in err) - self.assert_true('Traceback (most recent call last):' in err) - self.assert_true('1/0' in err) - self.assert_true('ZeroDivisionError:' in err) + self.assert_in('Exception on / [GET]', err) + self.assert_in('Traceback (most recent call last):', err) + self.assert_in('1/0', err) + self.assert_in('ZeroDivisionError:', err) def test_processor_exceptions(self): app = flask.Flask(__name__) diff --git a/flask/testsuite/subclassing.py b/flask/testsuite/subclassing.py index a3cf5d0e..dbfdd499 100644 --- a/flask/testsuite/subclassing.py +++ b/flask/testsuite/subclassing.py @@ -34,7 +34,7 @@ class FlaskSubclassingTestCase(FlaskTestCase): rv = app.test_client().get('/') self.assert_equal(rv.status_code, 500) - self.assert_true(b'Internal Server Error' in rv.data) + self.assert_in(b'Internal Server Error', rv.data) err = out.getvalue() self.assert_equal(err, '') diff --git a/flask/testsuite/templating.py b/flask/testsuite/templating.py index 08a54d06..b2870dea 100644 --- a/flask/testsuite/templating.py +++ b/flask/testsuite/templating.py @@ -99,7 +99,7 @@ class TemplatingTestCase(FlaskTestCase): @app.template_filter() def my_reverse(s): return s[::-1] - self.assert_true('my_reverse' in app.jinja_env.filters.keys()) + self.assert_in('my_reverse', app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse) self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba') @@ -108,7 +108,7 @@ class TemplatingTestCase(FlaskTestCase): def my_reverse(s): return s[::-1] app.add_template_filter(my_reverse) - self.assert_true('my_reverse' in app.jinja_env.filters.keys()) + self.assert_in('my_reverse', app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse) self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba') @@ -117,7 +117,7 @@ class TemplatingTestCase(FlaskTestCase): @app.template_filter('strrev') def my_reverse(s): return s[::-1] - self.assert_true('strrev' in app.jinja_env.filters.keys()) + self.assert_in('strrev', app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['strrev'], my_reverse) self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba') @@ -126,7 +126,7 @@ class TemplatingTestCase(FlaskTestCase): def my_reverse(s): return s[::-1] app.add_template_filter(my_reverse, 'strrev') - self.assert_true('strrev' in app.jinja_env.filters.keys()) + self.assert_in('strrev', app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['strrev'], my_reverse) self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba') @@ -179,7 +179,7 @@ class TemplatingTestCase(FlaskTestCase): @app.template_test() def boolean(value): return isinstance(value, bool) - self.assert_true('boolean' in app.jinja_env.tests.keys()) + self.assert_in('boolean', app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['boolean'], boolean) self.assert_true(app.jinja_env.tests['boolean'](False)) @@ -188,7 +188,7 @@ class TemplatingTestCase(FlaskTestCase): def boolean(value): return isinstance(value, bool) app.add_template_test(boolean) - self.assert_true('boolean' in app.jinja_env.tests.keys()) + self.assert_in('boolean', app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['boolean'], boolean) self.assert_true(app.jinja_env.tests['boolean'](False)) @@ -197,7 +197,7 @@ class TemplatingTestCase(FlaskTestCase): @app.template_test('boolean') def is_boolean(value): return isinstance(value, bool) - self.assert_true('boolean' in app.jinja_env.tests.keys()) + self.assert_in('boolean', app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['boolean'], is_boolean) self.assert_true(app.jinja_env.tests['boolean'](False)) @@ -206,7 +206,7 @@ class TemplatingTestCase(FlaskTestCase): def is_boolean(value): return isinstance(value, bool) app.add_template_test(is_boolean, 'boolean') - self.assert_true('boolean' in app.jinja_env.tests.keys()) + self.assert_in('boolean', app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['boolean'], is_boolean) self.assert_true(app.jinja_env.tests['boolean'](False)) @@ -219,7 +219,7 @@ class TemplatingTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_true(b'Success!' in rv.data) + self.assert_in(b'Success!', rv.data) def test_add_template_test_with_template(self): app = flask.Flask(__name__) @@ -230,7 +230,7 @@ class TemplatingTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_true(b'Success!' in rv.data) + self.assert_in(b'Success!', rv.data) def test_template_test_with_name_and_template(self): app = flask.Flask(__name__) @@ -241,7 +241,7 @@ class TemplatingTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_true(b'Success!' in rv.data) + self.assert_in(b'Success!', rv.data) def test_add_template_test_with_name_and_template(self): app = flask.Flask(__name__) @@ -252,14 +252,14 @@ class TemplatingTestCase(FlaskTestCase): def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') - self.assert_true(b'Success!' in rv.data) + self.assert_in(b'Success!', rv.data) def test_add_template_global(self): app = flask.Flask(__name__) @app.template_global() def get_stuff(): return 42 - self.assert_true('get_stuff' in app.jinja_env.globals.keys()) + self.assert_in('get_stuff', app.jinja_env.globals.keys()) self.assert_equal(app.jinja_env.globals['get_stuff'], get_stuff) self.assert_true(app.jinja_env.globals['get_stuff'](), 42) with app.app_context(): diff --git a/flask/testsuite/testing.py b/flask/testsuite/testing.py index 2e735c47..a60109e1 100644 --- a/flask/testsuite/testing.py +++ b/flask/testsuite/testing.py @@ -106,7 +106,7 @@ class TestToolsTestCase(FlaskTestCase): with c.session_transaction() as sess: pass except RuntimeError as e: - self.assert_true('Session backend did not open a session' in str(e)) + self.assert_in('Session backend did not open a session', str(e)) else: self.fail('Expected runtime error') @@ -130,7 +130,7 @@ class TestToolsTestCase(FlaskTestCase): with c.session_transaction() as s: pass except RuntimeError as e: - self.assert_true('cookies' in str(e)) + self.assert_in('cookies', str(e)) else: self.fail('Expected runtime error') @@ -153,7 +153,7 @@ class TestToolsTestCase(FlaskTestCase): resp = c.get('/other') self.assert_true(not hasattr(flask.g, 'value')) - self.assert_true(b'Internal Server Error' in resp.data) + self.assert_in(b'Internal Server Error', resp.data) self.assert_equal(resp.status_code, 500) flask.g.value = 23 From 62e7275bdf2bce19eb9fcfd31780e9314f96f092 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Wed, 22 May 2013 20:17:29 +0200 Subject: [PATCH 27/58] Use assert_false where appropriate --- flask/testsuite/__init__.py | 3 +++ flask/testsuite/basic.py | 8 ++++---- flask/testsuite/config.py | 4 ++-- flask/testsuite/reqctx.py | 10 +++++----- flask/testsuite/testing.py | 2 +- 5 files changed, 15 insertions(+), 12 deletions(-) diff --git a/flask/testsuite/__init__.py b/flask/testsuite/__init__.py index 72de1963..88cd4d88 100644 --- a/flask/testsuite/__init__.py +++ b/flask/testsuite/__init__.py @@ -145,6 +145,9 @@ class FlaskTestCase(unittest.TestCase): def assert_true(self, x, msg=None): self.assertTrue(x, msg) + def assert_false(self, x, msg=None): + self.assertFalse(x, msg) + def assert_in(self, x, y): self.assertIn(x, y) diff --git a/flask/testsuite/basic.py b/flask/testsuite/basic.py index 0abcac10..85b758b1 100644 --- a/flask/testsuite/basic.py +++ b/flask/testsuite/basic.py @@ -78,7 +78,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS']) rv = c.head('/') self.assert_equal(rv.status_code, 200) - self.assert_true(not rv.data) # head truncates + self.assert_false(rv.data) # head truncates self.assert_equal(c.post('/more').data, b'POST') self.assert_equal(c.get('/more').data, b'GET') rv = c.delete('/more') @@ -102,7 +102,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS']) rv = c.head('/') self.assert_equal(rv.status_code, 200) - self.assert_true(not rv.data) # head truncates + self.assert_false(rv.data) # head truncates self.assert_equal(c.post('/more').data, b'POST') self.assert_equal(c.get('/more').data, b'GET') rv = c.delete('/more') @@ -347,7 +347,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): app.secret_key = 'testkey' with app.test_request_context(): - self.assert_true(not flask.session.modified) + self.assert_false(flask.session.modified) flask.flash('Zap') flask.session.modified = False flask.flash('Zip') @@ -967,7 +967,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): @app.route('/') def index(): return 'Awesome' - self.assert_true(not app.got_first_request) + self.assert_false(app.got_first_request) self.assert_equal(app.test_client().get('/').data, b'Awesome') try: @app.route('/foo') diff --git a/flask/testsuite/config.py b/flask/testsuite/config.py index 8aaf5285..477c6db9 100644 --- a/flask/testsuite/config.py +++ b/flask/testsuite/config.py @@ -60,7 +60,7 @@ class ConfigTestCase(FlaskTestCase): self.assert_true("'FOO_SETTINGS' is not set" in str(e)) else: self.assert_true(0, 'expected exception') - self.assert_true(not app.config.from_envvar('FOO_SETTINGS', silent=True)) + self.assert_false(app.config.from_envvar('FOO_SETTINGS', silent=True)) os.environ = {'FOO_SETTINGS': __file__.rsplit('.', 1)[0] + '.py'} self.assert_true(app.config.from_envvar('FOO_SETTINGS')) @@ -97,7 +97,7 @@ class ConfigTestCase(FlaskTestCase): self.assert_true(msg.endswith("missing.cfg'")) else: self.assert_true(0, 'expected config') - self.assert_true(not app.config.from_pyfile('missing.cfg', silent=True)) + self.assert_false(app.config.from_pyfile('missing.cfg', silent=True)) def test_session_lifetime(self): app = flask.Flask(__name__) diff --git a/flask/testsuite/reqctx.py b/flask/testsuite/reqctx.py index 69b43f84..c232a74c 100644 --- a/flask/testsuite/reqctx.py +++ b/flask/testsuite/reqctx.py @@ -97,8 +97,8 @@ class RequestContextTestCase(FlaskTestCase): def test_context_test(self): app = flask.Flask(__name__) - self.assert_true(not flask.request) - self.assert_true(not flask.has_request_context()) + self.assert_false(flask.request) + self.assert_false(flask.has_request_context()) ctx = app.test_request_context() ctx.push() try: @@ -132,14 +132,14 @@ class RequestContextTestCase(FlaskTestCase): def index(): reqctx = flask._request_ctx_stack.top.copy() def g(): - self.assert_true(not flask.request) - self.assert_true(not flask.current_app) + self.assert_false(flask.request) + self.assert_false(flask.current_app) with reqctx: self.assert_true(flask.request) self.assert_equal(flask.current_app, app) self.assert_equal(flask.request.path, '/') self.assert_equal(flask.request.args['foo'], 'bar') - self.assert_true(not flask.request) + self.assert_false(flask.request) return 42 greenlets.append(greenlet(g)) return 'Hello World!' diff --git a/flask/testsuite/testing.py b/flask/testsuite/testing.py index a60109e1..e7206d21 100644 --- a/flask/testsuite/testing.py +++ b/flask/testsuite/testing.py @@ -152,7 +152,7 @@ class TestToolsTestCase(FlaskTestCase): self.assert_equal(resp.status_code, 200) resp = c.get('/other') - self.assert_true(not hasattr(flask.g, 'value')) + self.assert_false(hasattr(flask.g, 'value')) self.assert_in(b'Internal Server Error', resp.data) self.assert_equal(resp.status_code, 500) flask.g.value = 23 From 8f73c552a96cc54e6abefcfc0c4e9d4cdd7dc040 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Wed, 22 May 2013 20:53:32 +0200 Subject: [PATCH 28/58] Add missing assertIn, assertNotIn methods on 2.6 --- flask/testsuite/__init__.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/flask/testsuite/__init__.py b/flask/testsuite/__init__.py index 88cd4d88..89b8cec1 100644 --- a/flask/testsuite/__init__.py +++ b/flask/testsuite/__init__.py @@ -154,6 +154,13 @@ class FlaskTestCase(unittest.TestCase): def assert_not_in(self, x, y): self.assertNotIn(x, y) + if sys.version_info[:2] == (2, 6): + def assertIn(self, x, y): + assert x in y, "%r unexpectedly not in %r" % (x, y) + + def assertNotIn(self, x, y): + assert x not in y, "%r unexpectedly in %r" % (x, y) + class _ExceptionCatcher(object): From 3f80b0fd6c054d924c41a3c91152ec1984d8c28c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Wed, 22 May 2013 21:03:01 +0200 Subject: [PATCH 29/58] module name is quoted in ImportErrors on 3.x --- flask/testsuite/ext.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/flask/testsuite/ext.py b/flask/testsuite/ext.py index 04226181..f6209c67 100644 --- a/flask/testsuite/ext.py +++ b/flask/testsuite/ext.py @@ -12,6 +12,7 @@ import sys import unittest from flask.testsuite import FlaskTestCase +from flask._compat import PY2 from six.moves import reload_module class ExtImportHookTestCase(FlaskTestCase): @@ -109,7 +110,11 @@ class ExtImportHookTestCase(FlaskTestCase): except ImportError: exc_type, exc_value, tb = sys.exc_info() self.assert_true(exc_type is ImportError) - self.assert_equal(str(exc_value), 'No module named missing_module') + if PY2: + message = 'No module named missing_module' + else: + message = 'No module named \'missing_module\'' + self.assert_equal(str(exc_value), message) self.assert_true(tb.tb_frame.f_globals is globals()) next = tb.tb_next From 4bea6bbe6d2200dfdbcca3dfc2fe561488c82a8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Wed, 22 May 2013 21:07:53 +0200 Subject: [PATCH 30/58] Make DebugFilesKeyError.__str__ return str on 3.x --- flask/debughelpers.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/flask/debughelpers.py b/flask/debughelpers.py index 504fab93..f3bac185 100644 --- a/flask/debughelpers.py +++ b/flask/debughelpers.py @@ -8,6 +8,7 @@ :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ +from flask._compat import implements_to_string class UnexpectedUnicodeError(AssertionError, UnicodeError): @@ -16,6 +17,7 @@ class UnexpectedUnicodeError(AssertionError, UnicodeError): """ +@implements_to_string class DebugFilesKeyError(KeyError, AssertionError): """Raised from request.files during debugging. The idea is that it can provide a better error message than just a generic KeyError/BadRequest. @@ -33,7 +35,7 @@ class DebugFilesKeyError(KeyError, AssertionError): buf.append('\n\nThe browser instead transmitted some file names. ' 'This was submitted: %s' % ', '.join('"%s"' % x for x in form_matches)) - self.msg = ''.join(buf).encode('utf-8') + self.msg = ''.join(buf) def __str__(self): return self.msg From 3d36d6efb9371be92f6f22c844ed6a17c87f4a88 Mon Sep 17 00:00:00 2001 From: Markus Unterwaditzer Date: Wed, 22 May 2013 21:09:32 +0200 Subject: [PATCH 31/58] Fix leak in leak detection code If ensure_clean_request_context found a leak, it would raise an AssertionError and not clean up the leak, and therefore affect other testcases. --- flask/testsuite/__init__.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/flask/testsuite/__init__.py b/flask/testsuite/__init__.py index 88cd4d88..5f5935cd 100644 --- a/flask/testsuite/__init__.py +++ b/flask/testsuite/__init__.py @@ -116,7 +116,10 @@ class FlaskTestCase(unittest.TestCase): def ensure_clean_request_context(self): # make sure we're not leaking a request context since we are # testing flask internally in debug mode in a few cases - self.assert_equal(flask._request_ctx_stack.top, None) + leaks = [] + while flask._request_ctx_stack.top is not None: + leaks.append(flask._request_ctx_stack.pop()) + self.assert_equal(leaks, []) def setup(self): pass From 135c53a5f2f990512d2be348dc16ef719233a314 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Wed, 22 May 2013 21:30:45 +0200 Subject: [PATCH 32/58] Fix .iteritems() access in flask.sessions --- flask/sessions.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/flask/sessions.py b/flask/sessions.py index 04b7f8af..0b35b1c2 100644 --- a/flask/sessions.py +++ b/flask/sessions.py @@ -15,9 +15,9 @@ from datetime import datetime from werkzeug.http import http_date, parse_date from werkzeug.datastructures import CallbackDict from . import Markup, json +from ._compat import iteritems, text_type from itsdangerous import URLSafeTimedSerializer, BadSignature -import six def total_seconds(td): @@ -63,16 +63,16 @@ class TaggedJSONSerializer(object): elif isinstance(value, uuid.UUID): return {' u': value.hex} elif callable(getattr(value, '__html__', None)): - return {' m': six.text_type(value.__html__())} + return {' m': text_type(value.__html__())} elif isinstance(value, list): return [_tag(x) for x in value] elif isinstance(value, datetime): return {' d': http_date(value)} elif isinstance(value, dict): - return dict((k, _tag(v)) for k, v in six.iteritems(value)) + return dict((k, _tag(v)) for k, v in iteritems(value)) elif isinstance(value, str): try: - return six.text_type(value) + return text_type(value) except UnicodeError: raise UnexpectedUnicodeError(u'A byte string with ' u'non-ASCII data was passed to the session system ' @@ -85,7 +85,7 @@ class TaggedJSONSerializer(object): def object_hook(obj): if len(obj) != 1: return obj - the_key, the_value = six.advance_iterator(obj.iteritems()) + the_key, the_value = next(iteritems(obj)) if the_key == ' t': return tuple(the_value) elif the_key == ' u': From a0801719f8f24a0e3192eca203bbd341c4e557ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Wed, 22 May 2013 21:40:30 +0200 Subject: [PATCH 33/58] Remove six dependency --- flask/helpers.py | 3 +-- flask/json.py | 4 ++-- flask/templating.py | 6 +++--- flask/testsuite/basic.py | 4 ++-- flask/testsuite/blueprints.py | 4 ++-- flask/testsuite/ext.py | 5 ++++- flask/testsuite/helpers.py | 11 +++++------ flask/testsuite/testing.py | 4 ++-- setup.py | 1 - 9 files changed, 21 insertions(+), 21 deletions(-) diff --git a/flask/helpers.py b/flask/helpers.py index 1359bba6..dbbbf2e6 100644 --- a/flask/helpers.py +++ b/flask/helpers.py @@ -24,7 +24,6 @@ from functools import update_wrapper from werkzeug.datastructures import Headers from werkzeug.exceptions import NotFound -import six from flask._compat import string_types, text_type # this was moved in 0.7 @@ -128,7 +127,7 @@ def stream_with_context(generator_or_function): # pushed. This item is discarded. Then when the iteration continues the # real generator is executed. wrapped_g = generator() - six.advance_iterator(wrapped_g) + next(wrapped_g) return wrapped_g diff --git a/flask/json.py b/flask/json.py index 6b95fde0..7777ba5d 100644 --- a/flask/json.py +++ b/flask/json.py @@ -11,13 +11,13 @@ import uuid from datetime import datetime from .globals import current_app, request +from ._compat import text_type from werkzeug.http import http_date # Use the same json implementation as itsdangerous on which we # depend anyways. from itsdangerous import json as _json -import six # figure out if simplejson escapes slashes. This behavior was changed @@ -60,7 +60,7 @@ class JSONEncoder(_json.JSONEncoder): if isinstance(o, uuid.UUID): return str(o) if hasattr(o, '__html__'): - return six.text_type(o.__html__()) + return text_type(o.__html__()) return _json.JSONEncoder.default(self, o) diff --git a/flask/templating.py b/flask/templating.py index 754c6893..63adb092 100644 --- a/flask/templating.py +++ b/flask/templating.py @@ -15,7 +15,7 @@ from jinja2 import BaseLoader, Environment as BaseEnvironment, \ from .globals import _request_ctx_stack, _app_ctx_stack from .signals import template_rendered from .module import blueprint_is_module -import six +from ._compat import itervalues, iteritems def _default_template_ctx_processor(): @@ -80,7 +80,7 @@ class DispatchingJinjaLoader(BaseLoader): except (ValueError, KeyError): pass - for blueprint in six.itervalues(self.app.blueprints): + for blueprint in itervalues(self.app.blueprints): if blueprint_is_module(blueprint): continue loader = blueprint.jinja_loader @@ -93,7 +93,7 @@ class DispatchingJinjaLoader(BaseLoader): if loader is not None: result.update(loader.list_templates()) - for name, blueprint in six.iteritems(self.app.blueprints): + for name, blueprint in iteritems(self.app.blueprints): loader = blueprint.jinja_loader if loader is not None: for template in loader.list_templates(): diff --git a/flask/testsuite/basic.py b/flask/testsuite/basic.py index 85b758b1..485ed5fd 100644 --- a/flask/testsuite/basic.py +++ b/flask/testsuite/basic.py @@ -17,10 +17,10 @@ import unittest from datetime import datetime from threading import Thread from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning +from flask._compat import text_type from werkzeug.exceptions import BadRequest, NotFound from werkzeug.http import parse_date from werkzeug.routing import BuildError -import six class BasicFunctionalityTestCase(FlaskTestCase): @@ -276,7 +276,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): @app.route('/test') def test(): - return six.text_type(flask.session.permanent) + return text_type(flask.session.permanent) client = app.test_client() rv = client.get('/') diff --git a/flask/testsuite/blueprints.py b/flask/testsuite/blueprints.py index 89a8f2d7..97a196d7 100644 --- a/flask/testsuite/blueprints.py +++ b/flask/testsuite/blueprints.py @@ -13,10 +13,10 @@ import flask import unittest import warnings from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning +from flask._compat import text_type from werkzeug.exceptions import NotFound from werkzeug.http import parse_cache_control_header from jinja2 import TemplateNotFound -import six # import moduleapp here because it uses deprecated features and we don't @@ -303,7 +303,7 @@ class BlueprintTestCase(FlaskTestCase): @bp.route('/bar') def bar(bar): - return six.text_type(bar) + return text_type(bar) app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23}) diff --git a/flask/testsuite/ext.py b/flask/testsuite/ext.py index f6209c67..370a31d8 100644 --- a/flask/testsuite/ext.py +++ b/flask/testsuite/ext.py @@ -11,9 +11,12 @@ import sys import unittest +try: + from imp import reload as reload_module +except ImportError: + reload_module = reload from flask.testsuite import FlaskTestCase from flask._compat import PY2 -from six.moves import reload_module class ExtImportHookTestCase(FlaskTestCase): diff --git a/flask/testsuite/helpers.py b/flask/testsuite/helpers.py index b76d36d1..d0054de1 100644 --- a/flask/testsuite/helpers.py +++ b/flask/testsuite/helpers.py @@ -15,8 +15,7 @@ import unittest from logging import StreamHandler from flask.testsuite import FlaskTestCase, catch_warnings, catch_stderr from werkzeug.http import parse_cache_control_header, parse_options_header -import six -from flask._compat import StringIO +from flask._compat import StringIO, text_type def has_encoding(name): @@ -34,7 +33,7 @@ class JSONTestCase(FlaskTestCase): app = flask.Flask(__name__) @app.route('/json', methods=['POST']) def return_json(): - return six.text_type(flask.request.json) + return text_type(flask.request.json) c = app.test_client() rv = c.post('/json', data='malformed', content_type='application/json') self.assert_equal(rv.status_code, 400) @@ -43,7 +42,7 @@ class JSONTestCase(FlaskTestCase): app = flask.Flask(__name__) @app.route('/json', methods=['POST']) def return_json(): - return six.text_type(flask.request.json) + return text_type(flask.request.json) c = app.test_client() rv = c.post('/json', data='malformed', content_type='application/json') self.assert_equal(rv.status_code, 400) @@ -95,7 +94,7 @@ class JSONTestCase(FlaskTestCase): app = flask.Flask(__name__) @app.route('/add', methods=['POST']) def add(): - return six.text_type(flask.request.json['a'] + flask.request.json['b']) + return text_type(flask.request.json['a'] + flask.request.json['b']) c = app.test_client() rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}), content_type='application/json') @@ -506,7 +505,7 @@ class StreamingTestCase(FlaskTestCase): def close(self): called.append(42) def next(self): - return six.advance_iterator(self._gen) + return next(self._gen) @app.route('/') def index(): def generate(): diff --git a/flask/testsuite/testing.py b/flask/testsuite/testing.py index e7206d21..cd96b497 100644 --- a/flask/testsuite/testing.py +++ b/flask/testsuite/testing.py @@ -12,7 +12,7 @@ import flask import unittest from flask.testsuite import FlaskTestCase -import six +from flask._compat import text_type class TestToolsTestCase(FlaskTestCase): @@ -84,7 +84,7 @@ class TestToolsTestCase(FlaskTestCase): @app.route('/') def index(): - return six.text_type(flask.session['foo']) + return text_type(flask.session['foo']) with app.test_client() as c: with c.session_transaction() as sess: diff --git a/setup.py b/setup.py index 1d3e36ad..ddc83251 100644 --- a/setup.py +++ b/setup.py @@ -91,7 +91,6 @@ setup( zip_safe=False, platforms='any', install_requires=[ - 'six>=1.3.0', 'Werkzeug>=0.7', 'Jinja2>=2.4', 'itsdangerous>=0.17' From 43b6d0a6d062ace75cc2b0f7200b770eac23edcd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Wed, 22 May 2013 22:49:25 +0200 Subject: [PATCH 34/58] Ensure that config file is closed immediately --- flask/config.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/flask/config.py b/flask/config.py index ddb113a5..4d9ac23a 100644 --- a/flask/config.py +++ b/flask/config.py @@ -125,7 +125,8 @@ class Config(dict): d = imp.new_module('config') d.__file__ = filename try: - exec(compile(open(filename).read(), filename, 'exec'), d.__dict__) + with open(filename) as config_file: + exec(compile(config_file.read(), filename, 'exec'), d.__dict__) except IOError as e: if silent and e.errno in (errno.ENOENT, errno.EISDIR): return False From 79ec3d81c1c0e4db7eb800e69f2c7aab3d8d02b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Wed, 22 May 2013 22:58:12 +0200 Subject: [PATCH 35/58] Prevent UnboundLocalError in test_build_error_handler --- flask/testsuite/basic.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/flask/testsuite/basic.py b/flask/testsuite/basic.py index 485ed5fd..656233b8 100644 --- a/flask/testsuite/basic.py +++ b/flask/testsuite/basic.py @@ -753,8 +753,8 @@ class BasicFunctionalityTestCase(FlaskTestCase): try: with app.test_request_context(): flask.url_for('spam') - except BuildError as error: - pass + except BuildError as err: + error = err try: raise RuntimeError('Test case where BuildError is not current.') except RuntimeError: From 85ba8c96e9371368cff772e4e270cf685d015e03 Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Thu, 23 May 2013 14:07:25 +0100 Subject: [PATCH 36/58] Fixed a broken test --- flask/testsuite/ext.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/flask/testsuite/ext.py b/flask/testsuite/ext.py index 370a31d8..1a7a4a5a 100644 --- a/flask/testsuite/ext.py +++ b/flask/testsuite/ext.py @@ -120,7 +120,8 @@ class ExtImportHookTestCase(FlaskTestCase): self.assert_equal(str(exc_value), message) self.assert_true(tb.tb_frame.f_globals is globals()) - next = tb.tb_next + # reraise() adds a second frame so we need to skip that one too. + next = tb.tb_next.tb_next self.assert_in('flask_broken/__init__.py', next.tb_frame.f_code.co_filename) From 8bb972e5ae647650457bc4e94ff51cb5e34951dd Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Sat, 25 May 2013 19:13:48 +0200 Subject: [PATCH 37/58] fix minitwit/flaskr test errors, improve docs about file open mode app.open_resource needs to get called with the correct mode param (python3 will read bytes [not str] if the wrong mode is used), add mode param docs. rv.data is bytes, fix the data type we compare it with to be also bytes --- docs/patterns/sqlite3.rst | 2 +- docs/tutorial/dbinit.rst | 2 +- examples/flaskr/flaskr.py | 2 +- examples/flaskr/flaskr_tests.py | 16 ++++----- examples/minitwit/minitwit.py | 2 +- examples/minitwit/minitwit_tests.py | 56 ++++++++++++++--------------- flask/app.py | 1 + flask/helpers.py | 1 + 8 files changed, 42 insertions(+), 40 deletions(-) diff --git a/docs/patterns/sqlite3.rst b/docs/patterns/sqlite3.rst index 76fec0b2..e625d15b 100644 --- a/docs/patterns/sqlite3.rst +++ b/docs/patterns/sqlite3.rst @@ -124,7 +124,7 @@ can do that for you:: def init_db(): with app.app_context(): db = get_db() - with app.open_resource('schema.sql') as f: + with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() diff --git a/docs/tutorial/dbinit.rst b/docs/tutorial/dbinit.rst index b32a8eda..1241193a 100644 --- a/docs/tutorial/dbinit.rst +++ b/docs/tutorial/dbinit.rst @@ -33,7 +33,7 @@ earlier. Just add that function below the `connect_db` function in def init_db(): with closing(connect_db()) as db: - with app.open_resource('schema.sql') as f: + with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() diff --git a/examples/flaskr/flaskr.py b/examples/flaskr/flaskr.py index 20254660..b193e94e 100644 --- a/examples/flaskr/flaskr.py +++ b/examples/flaskr/flaskr.py @@ -31,7 +31,7 @@ def init_db(): """Creates the database tables.""" with app.app_context(): db = get_db() - with app.open_resource('schema.sql') as f: + with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() diff --git a/examples/flaskr/flaskr_tests.py b/examples/flaskr/flaskr_tests.py index cfac3782..dd16c038 100644 --- a/examples/flaskr/flaskr_tests.py +++ b/examples/flaskr/flaskr_tests.py @@ -42,21 +42,21 @@ class FlaskrTestCase(unittest.TestCase): def test_empty_db(self): """Start with a blank database.""" rv = self.app.get('/') - assert 'No entries here so far' in rv.data + assert b'No entries here so far' in rv.data def test_login_logout(self): """Make sure login and logout works""" rv = self.login(flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD']) - assert 'You were logged in' in rv.data + assert b'You were logged in' in rv.data rv = self.logout() - assert 'You were logged out' in rv.data + assert b'You were logged out' in rv.data rv = self.login(flaskr.app.config['USERNAME'] + 'x', flaskr.app.config['PASSWORD']) - assert 'Invalid username' in rv.data + assert b'Invalid username' in rv.data rv = self.login(flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'] + 'x') - assert 'Invalid password' in rv.data + assert b'Invalid password' in rv.data def test_messages(self): """Test that messages work""" @@ -66,9 +66,9 @@ class FlaskrTestCase(unittest.TestCase): title='', text='HTML allowed here' ), follow_redirects=True) - assert 'No entries here so far' not in rv.data - assert '<Hello>' in rv.data - assert 'HTML allowed here' in rv.data + assert b'No entries here so far' not in rv.data + assert b'<Hello>' in rv.data + assert b'HTML allowed here' in rv.data if __name__ == '__main__': diff --git a/examples/minitwit/minitwit.py b/examples/minitwit/minitwit.py index 2863de50..baa204f9 100644 --- a/examples/minitwit/minitwit.py +++ b/examples/minitwit/minitwit.py @@ -53,7 +53,7 @@ def init_db(): """Creates the database tables.""" with app.app_context(): db = get_db() - with app.open_resource('schema.sql') as f: + with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() diff --git a/examples/minitwit/minitwit_tests.py b/examples/minitwit/minitwit_tests.py index 87741165..c213466d 100644 --- a/examples/minitwit/minitwit_tests.py +++ b/examples/minitwit/minitwit_tests.py @@ -63,7 +63,7 @@ class MiniTwitTestCase(unittest.TestCase): rv = self.app.post('/add_message', data={'text': text}, follow_redirects=True) if text: - assert 'Your message was recorded' in rv.data + assert b'Your message was recorded' in rv.data return rv # testing functions @@ -71,29 +71,29 @@ class MiniTwitTestCase(unittest.TestCase): def test_register(self): """Make sure registering works""" rv = self.register('user1', 'default') - assert 'You were successfully registered ' \ - 'and can login now' in rv.data + assert b'You were successfully registered ' \ + b'and can login now' in rv.data rv = self.register('user1', 'default') - assert 'The username is already taken' in rv.data + assert b'The username is already taken' in rv.data rv = self.register('', 'default') - assert 'You have to enter a username' in rv.data + assert b'You have to enter a username' in rv.data rv = self.register('meh', '') - assert 'You have to enter a password' in rv.data + assert b'You have to enter a password' in rv.data rv = self.register('meh', 'x', 'y') - assert 'The two passwords do not match' in rv.data + assert b'The two passwords do not match' in rv.data rv = self.register('meh', 'foo', email='broken') - assert 'You have to enter a valid email address' in rv.data + assert b'You have to enter a valid email address' in rv.data def test_login_logout(self): """Make sure logging in and logging out works""" rv = self.register_and_login('user1', 'default') - assert 'You were logged in' in rv.data + assert b'You were logged in' in rv.data rv = self.logout() - assert 'You were logged out' in rv.data + assert b'You were logged out' in rv.data rv = self.login('user1', 'wrongpassword') - assert 'Invalid password' in rv.data + assert b'Invalid password' in rv.data rv = self.login('user2', 'wrongpassword') - assert 'Invalid username' in rv.data + assert b'Invalid username' in rv.data def test_message_recording(self): """Check if adding messages works""" @@ -101,8 +101,8 @@ class MiniTwitTestCase(unittest.TestCase): self.add_message('test message 1') self.add_message('') rv = self.app.get('/') - assert 'test message 1' in rv.data - assert '<test message 2>' in rv.data + assert b'test message 1' in rv.data + assert b'<test message 2>' in rv.data def test_timelines(self): """Make sure that timelines work""" @@ -112,37 +112,37 @@ class MiniTwitTestCase(unittest.TestCase): self.register_and_login('bar', 'default') self.add_message('the message by bar') rv = self.app.get('/public') - assert 'the message by foo' in rv.data - assert 'the message by bar' in rv.data + assert b'the message by foo' in rv.data + assert b'the message by bar' in rv.data # bar's timeline should just show bar's message rv = self.app.get('/') - assert 'the message by foo' not in rv.data - assert 'the message by bar' in rv.data + assert b'the message by foo' not in rv.data + assert b'the message by bar' in rv.data # now let's follow foo rv = self.app.get('/foo/follow', follow_redirects=True) - assert 'You are now following "foo"' in rv.data + assert b'You are now following "foo"' in rv.data # we should now see foo's message rv = self.app.get('/') - assert 'the message by foo' in rv.data - assert 'the message by bar' in rv.data + assert b'the message by foo' in rv.data + assert b'the message by bar' in rv.data # but on the user's page we only want the user's message rv = self.app.get('/bar') - assert 'the message by foo' not in rv.data - assert 'the message by bar' in rv.data + assert b'the message by foo' not in rv.data + assert b'the message by bar' in rv.data rv = self.app.get('/foo') - assert 'the message by foo' in rv.data - assert 'the message by bar' not in rv.data + assert b'the message by foo' in rv.data + assert b'the message by bar' not in rv.data # now unfollow and check if that worked rv = self.app.get('/foo/unfollow', follow_redirects=True) - assert 'You are no longer following "foo"' in rv.data + assert b'You are no longer following "foo"' in rv.data rv = self.app.get('/') - assert 'the message by foo' not in rv.data - assert 'the message by bar' in rv.data + assert b'the message by foo' not in rv.data + assert b'the message by bar' in rv.data if __name__ == '__main__': diff --git a/flask/app.py b/flask/app.py index dc684489..77e4799c 100644 --- a/flask/app.py +++ b/flask/app.py @@ -630,6 +630,7 @@ class Flask(_PackageBoundObject): :param resource: the name of the resource. To access resources within subfolders use forward slashes as separator. + :param mode: resource file opening mode, default is 'rb'. """ return open(os.path.join(self.instance_path, resource), mode) diff --git a/flask/helpers.py b/flask/helpers.py index dbbbf2e6..37d3bb49 100644 --- a/flask/helpers.py +++ b/flask/helpers.py @@ -838,6 +838,7 @@ class _PackageBoundObject(object): :param resource: the name of the resource. To access resources within subfolders use forward slashes as separator. + :param mode: resource file opening mode, default is 'rb'. """ if mode not in ('r', 'rb'): raise ValueError('Resources can only be opened for reading') From af5576a6c50ec849a824c1ace15f187d378db771 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Sat, 25 May 2013 19:46:26 +0200 Subject: [PATCH 38/58] fix iterator in testsuite helpers --- flask/testsuite/helpers.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/flask/testsuite/helpers.py b/flask/testsuite/helpers.py index 21c9f791..90e9e020 100644 --- a/flask/testsuite/helpers.py +++ b/flask/testsuite/helpers.py @@ -15,7 +15,7 @@ import unittest from logging import StreamHandler from flask.testsuite import FlaskTestCase, catch_warnings, catch_stderr from werkzeug.http import parse_cache_control_header, parse_options_header -from flask._compat import StringIO, text_type +from flask._compat import StringIO, text_type, implements_iterator def has_encoding(name): @@ -485,6 +485,7 @@ class StreamingTestCase(FlaskTestCase): app = flask.Flask(__name__) app.testing = True called = [] + @implements_iterator class Wrapper(object): def __init__(self, gen): self._gen = gen @@ -492,7 +493,7 @@ class StreamingTestCase(FlaskTestCase): return self def close(self): called.append(42) - def next(self): + def __next__(self): return next(self._gen) @app.route('/') def index(): From 83f76585725fd380b61f35576bb1c307fe2a1a5e Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Sat, 25 May 2013 20:19:17 +0200 Subject: [PATCH 39/58] fix metaclass usage for py3 --- flask/views.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/flask/views.py b/flask/views.py index 5192c1c1..b3b61b52 100644 --- a/flask/views.py +++ b/flask/views.py @@ -9,6 +9,7 @@ :license: BSD, see LICENSE for more details. """ from .globals import request +from ._compat import with_metaclass http_method_funcs = frozenset(['get', 'post', 'head', 'options', @@ -119,7 +120,7 @@ class MethodViewType(type): return rv -class MethodView(View): +class MethodView(with_metaclass(MethodViewType, View)): """Like a regular class-based view but that dispatches requests to particular methods. For instance if you implement a method called :meth:`get` it means you will response to ``'GET'`` requests and @@ -138,8 +139,6 @@ class MethodView(View): app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter')) """ - __metaclass__ = MethodViewType - def dispatch_request(self, *args, **kwargs): meth = getattr(self, request.method.lower(), None) # if the request method is HEAD and we don't have a handler for it From 96b8ffbb29eaba834a30352554e42cf2406c7e06 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Sat, 25 May 2013 20:24:14 +0200 Subject: [PATCH 40/58] always import from ._compat --- flask/app.py | 2 +- flask/config.py | 2 +- flask/debughelpers.py | 2 +- flask/exthook.py | 2 +- flask/helpers.py | 2 +- flask/testing.py | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/flask/app.py b/flask/app.py index 77e4799c..84ef1013 100644 --- a/flask/app.py +++ b/flask/app.py @@ -34,7 +34,7 @@ from .templating import DispatchingJinjaLoader, Environment, \ _default_template_ctx_processor from .signals import request_started, request_finished, got_request_exception, \ request_tearing_down, appcontext_tearing_down -from flask._compat import reraise, string_types, integer_types +from ._compat import reraise, string_types, integer_types # a lock used for logger initialization _logger_lock = Lock() diff --git a/flask/config.py b/flask/config.py index 4d9ac23a..155afa2f 100644 --- a/flask/config.py +++ b/flask/config.py @@ -14,7 +14,7 @@ import os import errno from werkzeug.utils import import_string -from flask._compat import string_types +from ._compat import string_types class ConfigAttribute(object): diff --git a/flask/debughelpers.py b/flask/debughelpers.py index f3bac185..2f8510f9 100644 --- a/flask/debughelpers.py +++ b/flask/debughelpers.py @@ -8,7 +8,7 @@ :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ -from flask._compat import implements_to_string +from ._compat import implements_to_string class UnexpectedUnicodeError(AssertionError, UnicodeError): diff --git a/flask/exthook.py b/flask/exthook.py index 89dac47b..d0d814c6 100644 --- a/flask/exthook.py +++ b/flask/exthook.py @@ -21,7 +21,7 @@ """ import sys import os -from flask._compat import reraise +from ._compat import reraise class ExtensionImporter(object): diff --git a/flask/helpers.py b/flask/helpers.py index 37d3bb49..49fd0278 100644 --- a/flask/helpers.py +++ b/flask/helpers.py @@ -24,7 +24,6 @@ from functools import update_wrapper from werkzeug.datastructures import Headers from werkzeug.exceptions import NotFound -from flask._compat import string_types, text_type # this was moved in 0.7 try: @@ -37,6 +36,7 @@ from jinja2 import FileSystemLoader from .signals import message_flashed from .globals import session, _request_ctx_stack, _app_ctx_stack, \ current_app, request +from ._compat import string_types, text_type # sentinel diff --git a/flask/testing.py b/flask/testing.py index ef116cf3..4c1f4550 100644 --- a/flask/testing.py +++ b/flask/testing.py @@ -13,7 +13,7 @@ from contextlib import contextmanager from werkzeug.test import Client, EnvironBuilder from flask import _request_ctx_stack -from flask._compat import urlparse +from ._compat import urlparse def make_test_environ_builder(app, path='/', base_url=None, *args, **kwargs): From f9e9e774646ff7cbd2df6386c7055760936a9fcd Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Sat, 25 May 2013 20:58:12 +0200 Subject: [PATCH 41/58] fix data types in after_request test TODO: why was that bug not causing / displaying an exception somehow? should give a TypeError in py 3.3. --- flask/testsuite/basic.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/flask/testsuite/basic.py b/flask/testsuite/basic.py index 656233b8..9bbe10e3 100644 --- a/flask/testsuite/basic.py +++ b/flask/testsuite/basic.py @@ -443,7 +443,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): evts.append('before') @app.after_request def after_request(response): - response.data += '|after' + response.data += b'|after' evts.append('after') return response @app.route('/') @@ -453,7 +453,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): return 'request' self.assert_not_in('after', evts) rv = app.test_client().get('/').data - self.assert_in(b'after', evts) + self.assert_in('after', evts) self.assert_equal(rv, b'request|after') def test_after_request_processing(self): From 13cc69911c6b5c742489ffe6e8c6458dec32e230 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Sat, 25 May 2013 22:01:14 +0200 Subject: [PATCH 42/58] fix typos --- flask/_compat.py | 2 +- flask/app.py | 10 +++++----- flask/ctx.py | 2 +- flask/helpers.py | 2 +- flask/testsuite/blueprints.py | 4 ++-- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/flask/_compat.py b/flask/_compat.py index 27f61137..7c960ac6 100644 --- a/flask/_compat.py +++ b/flask/_compat.py @@ -91,7 +91,7 @@ else: def with_metaclass(meta, *bases): # This requires a bit of explanation: the basic idea is to make a - # dummy metaclass for one level of class instanciation that replaces + # dummy metaclass for one level of class instantiation that replaces # itself with the actual metaclass. Because of internal type checks # we also need to make sure that we downgrade the custom metaclass # for one level to something closer to type (that's why __call__ and diff --git a/flask/app.py b/flask/app.py index 84ef1013..c3bbc907 100644 --- a/flask/app.py +++ b/flask/app.py @@ -177,7 +177,7 @@ class Flask(_PackageBoundObject): #: The debug flag. Set this to `True` to enable debugging of the #: application. In debug mode the debugger will kick in when an unhandled - #: exception ocurrs and the integrated server will automatically reload + #: exception occurs and the integrated server will automatically reload #: the application if changes in the code are detected. #: #: This attribute can also be configured from the config with the `DEBUG` @@ -522,7 +522,7 @@ class Flask(_PackageBoundObject): """The name of the application. This is usually the import name with the difference that it's guessed from the run file if the import name is main. This name is used as a display name when - Flask needs the name of the application. It can be set and overriden + Flask needs the name of the application. It can be set and overridden to change the value. .. versionadded:: 0.8 @@ -697,7 +697,7 @@ class Flask(_PackageBoundObject): This injects request, session, config and g into the template context as well as everything template context processors want to inject. Note that the as of Flask 0.6, the original values - in the context will not be overriden if a context processor + in the context will not be overridden if a context processor decides to return a value with the same key. :param context: the context as a dictionary that is updated in place @@ -1045,7 +1045,7 @@ class Flask(_PackageBoundObject): app.error_handler_spec[None][404] = page_not_found Setting error handlers via assignments to :attr:`error_handler_spec` - however is discouraged as it requires fidling with nested dictionaries + however is discouraged as it requires fiddling with nested dictionaries and the special case for arbitrary exception types. The first `None` refers to the active blueprint. If the error @@ -1550,7 +1550,7 @@ class Flask(_PackageBoundObject): # When we create a response object directly, we let the constructor # set the headers and status. We do this because there can be # some extra logic involved when creating these objects with - # specific values (like defualt content type selection). + # specific values (like default content type selection). if isinstance(rv, string_types): rv = self.response_class(rv, headers=headers, status=status) headers = status = None diff --git a/flask/ctx.py b/flask/ctx.py index 320f2f0e..6ab5b1ff 100644 --- a/flask/ctx.py +++ b/flask/ctx.py @@ -286,7 +286,7 @@ class RequestContext(object): def push(self): """Binds the request context to the current context.""" - # If an exception ocurrs in debug mode or if context preservation is + # If an exception occurs in debug mode or if context preservation is # activated under exception situations exactly one context stays # on the stack. The rationale is that you want to access that # information under debug situations. However if someone forgets to diff --git a/flask/helpers.py b/flask/helpers.py index 49fd0278..02b66797 100644 --- a/flask/helpers.py +++ b/flask/helpers.py @@ -330,7 +330,7 @@ def get_template_attribute(template_name, attribute): .. versionadded:: 0.2 :param template_name: the name of the template - :param attribute: the name of the variable of macro to acccess + :param attribute: the name of the variable of macro to access """ return getattr(current_app.jinja_env.get_template(template_name).module, attribute) diff --git a/flask/testsuite/blueprints.py b/flask/testsuite/blueprints.py index 97a196d7..b3771fde 100644 --- a/flask/testsuite/blueprints.py +++ b/flask/testsuite/blueprints.py @@ -105,7 +105,7 @@ class ModuleTestCase(FlaskTestCase): app = flask.Flask(__name__) admin = flask.Module(__name__, 'admin', url_prefix='/admin') @app.context_processor - def inject_all_regualr(): + def inject_all_regular(): return {'a': 1} @admin.context_processor def inject_admin(): @@ -534,7 +534,7 @@ class BlueprintTestCase(FlaskTestCase): c = app.test_client() self.assertEqual(c.get('/py/foo').data, b'bp.foo') - # The rule's din't actually made it through + # The rule's didn't actually made it through rv = c.get('/py/bar') assert rv.status_code == 404 rv = c.get('/py/bar/123') From bb2e20f53fd66981190658a58e206a3f8aa4f3e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Sun, 26 May 2013 15:37:52 +0200 Subject: [PATCH 43/58] Depends on itsdangerous>=0.12 now --- setup.py | 2 +- tox.ini | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/setup.py b/setup.py index ddc83251..a0a65cf4 100644 --- a/setup.py +++ b/setup.py @@ -93,7 +93,7 @@ setup( install_requires=[ 'Werkzeug>=0.7', 'Jinja2>=2.4', - 'itsdangerous>=0.17' + 'itsdangerous>=0.21' ], classifiers=[ 'Development Status :: 4 - Beta', diff --git a/tox.ini b/tox.ini index c699ac48..161e86fb 100644 --- a/tox.ini +++ b/tox.ini @@ -3,5 +3,4 @@ envlist = py26, py27, pypy, py33 [testenv] deps = -egit+git://github.com/mitsuhiko/werkzeug.git@sprint-branch#egg=werkzeug - -egit+git://github.com/mitsuhiko/itsdangerous.git#egg=itsdangerous commands = python run-tests.py [] From ac04bc78361d5562f8289e8efe16a2e9a97b0d01 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Sun, 26 May 2013 20:33:22 +0200 Subject: [PATCH 44/58] replace 1/0 by 1 // 0 to get rid of DeprecationWarning (and PEP8 issue) --- flask/testsuite/basic.py | 6 +++--- flask/testsuite/helpers.py | 10 +++++----- flask/testsuite/signals.py | 2 +- flask/testsuite/subclassing.py | 2 +- flask/testsuite/testing.py | 2 +- flask/testsuite/views.py | 4 ++-- 6 files changed, 13 insertions(+), 13 deletions(-) diff --git a/flask/testsuite/basic.py b/flask/testsuite/basic.py index 9bbe10e3..a172ed85 100644 --- a/flask/testsuite/basic.py +++ b/flask/testsuite/basic.py @@ -529,7 +529,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): pass @app.route('/') def fails(): - 1/0 + 1 // 0 rv = app.test_client().get('/') self.assert_equal(rv.status_code, 500) self.assert_in(b'Internal Server Error', rv.data) @@ -866,7 +866,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): app = flask.Flask(__name__) @app.route('/') def index(): - 1/0 + 1 // 0 c = app.test_client() if config_key is not None: app.config[config_key] = True @@ -1054,7 +1054,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): @app.route('/fail') def fail_func(): - 1/0 + 1 // 0 c = app.test_client() for x in range(3): diff --git a/flask/testsuite/helpers.py b/flask/testsuite/helpers.py index 90e9e020..2b04f73a 100644 --- a/flask/testsuite/helpers.py +++ b/flask/testsuite/helpers.py @@ -306,7 +306,7 @@ class LoggingTestCase(FlaskTestCase): @app.route('/exc') def exc(): - 1/0 + 1 // 0 with app.test_client() as c: with catch_stderr() as err: @@ -340,7 +340,7 @@ class LoggingTestCase(FlaskTestCase): @app.route('/') def index(): - 1/0 + 1 // 0 rv = app.test_client().get('/') self.assert_equal(rv.status_code, 500) @@ -349,7 +349,7 @@ class LoggingTestCase(FlaskTestCase): err = out.getvalue() self.assert_in('Exception on / [GET]', err) self.assert_in('Traceback (most recent call last):', err) - self.assert_in('1/0', err) + self.assert_in('1 // 0', err) self.assert_in('ZeroDivisionError:', err) def test_processor_exceptions(self): @@ -357,11 +357,11 @@ class LoggingTestCase(FlaskTestCase): @app.before_request def before_request(): if trigger == 'before': - 1/0 + 1 // 0 @app.after_request def after_request(response): if trigger == 'after': - 1/0 + 1 // 0 return response @app.route('/') def index(): diff --git a/flask/testsuite/signals.py b/flask/testsuite/signals.py index ffd575c1..94262f17 100644 --- a/flask/testsuite/signals.py +++ b/flask/testsuite/signals.py @@ -83,7 +83,7 @@ class SignalsTestCase(FlaskTestCase): @app.route('/') def index(): - 1/0 + 1 // 0 def record(sender, exception): recorded.append(exception) diff --git a/flask/testsuite/subclassing.py b/flask/testsuite/subclassing.py index dbfdd499..6b81db98 100644 --- a/flask/testsuite/subclassing.py +++ b/flask/testsuite/subclassing.py @@ -30,7 +30,7 @@ class FlaskSubclassingTestCase(FlaskTestCase): @app.route('/') def index(): - 1/0 + 1 // 0 rv = app.test_client().get('/') self.assert_equal(rv.status_code, 500) diff --git a/flask/testsuite/testing.py b/flask/testsuite/testing.py index cd96b497..a618f0b8 100644 --- a/flask/testsuite/testing.py +++ b/flask/testsuite/testing.py @@ -143,7 +143,7 @@ class TestToolsTestCase(FlaskTestCase): @app.route('/other') def other(): - 1/0 + 1 // 0 with app.test_client() as c: resp = c.get('/') diff --git a/flask/testsuite/views.py b/flask/testsuite/views.py index 9dd463f2..4eee015b 100644 --- a/flask/testsuite/views.py +++ b/flask/testsuite/views.py @@ -55,9 +55,9 @@ class ViewTestCase(FlaskTestCase): class Index(flask.views.MethodView): def get(self): - 1/0 + 1 // 0 def post(self): - 1/0 + 1 // 0 class Other(Index): def get(self): From 404265110ab52ffd2a5d4991f115913aacba94a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Neuha=CC=88user?= Date: Sun, 26 May 2013 21:46:22 +0200 Subject: [PATCH 45/58] Always return a list from get_flashed_messages --- flask/helpers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flask/helpers.py b/flask/helpers.py index 02b66797..3dade16c 100644 --- a/flask/helpers.py +++ b/flask/helpers.py @@ -398,7 +398,7 @@ def get_flashed_messages(with_categories=False, category_filter=[]): _request_ctx_stack.top.flashes = flashes = session.pop('_flashes') \ if '_flashes' in session else [] if category_filter: - flashes = filter(lambda f: f[0] in category_filter, flashes) + flashes = list(filter(lambda f: f[0] in category_filter, flashes)) if not with_categories: return [x[1] for x in flashes] return flashes From 775c76ac5c4365deb31061d0a8ef942d0585f81d Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Thu, 30 May 2013 12:48:04 +0100 Subject: [PATCH 46/58] Enabled test mode for an app --- flask/testsuite/helpers.py | 1 + 1 file changed, 1 insertion(+) diff --git a/flask/testsuite/helpers.py b/flask/testsuite/helpers.py index 2b04f73a..bba66bda 100644 --- a/flask/testsuite/helpers.py +++ b/flask/testsuite/helpers.py @@ -133,6 +133,7 @@ class JSONTestCase(FlaskTestCase): class ModifiedRequest(flask.Request): url_charset = 'euc-kr' app = flask.Flask(__name__) + app.testing = True app.request_class = ModifiedRequest app.url_map.charset = 'euc-kr' From ffd9296507db6bfad1339b75c0ccdc7fa030cb67 Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Thu, 30 May 2013 12:51:12 +0100 Subject: [PATCH 47/58] Close request objects if they support closing. --- flask/ctx.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/flask/ctx.py b/flask/ctx.py index 6ab5b1ff..259c5e2f 100644 --- a/flask/ctx.py +++ b/flask/ctx.py @@ -334,6 +334,9 @@ class RequestContext(object): if exc is None: exc = sys.exc_info()[1] self.app.do_teardown_request(exc) + request_close = getattr(self.request, 'close', None) + if request_close is not None: + request_close() clear_request = True rv = _request_ctx_stack.pop() From 47572c5b4006c54f0991587d5c07d599d0ad3325 Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Thu, 30 May 2013 14:24:29 +0100 Subject: [PATCH 48/58] Set the content length automatically before calling wrap_file --- flask/helpers.py | 1 + flask/testsuite/basic.py | 1 + 2 files changed, 2 insertions(+) diff --git a/flask/helpers.py b/flask/helpers.py index 3dade16c..f52b5ae4 100644 --- a/flask/helpers.py +++ b/flask/helpers.py @@ -516,6 +516,7 @@ def send_file(filename_or_fp, mimetype=None, as_attachment=False, if file is None: file = open(filename, 'rb') mtime = os.path.getmtime(filename) + headers['Content-Length'] = os.path.getsize(filename) data = wrap_file(request.environ, file) rv = current_app.response_class(data, mimetype=mimetype, headers=headers, diff --git a/flask/testsuite/basic.py b/flask/testsuite/basic.py index a172ed85..810b5e66 100644 --- a/flask/testsuite/basic.py +++ b/flask/testsuite/basic.py @@ -786,6 +786,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): def test_static_files(self): app = flask.Flask(__name__) + app.testing = True rv = app.test_client().get('/static/index.html') self.assert_equal(rv.status_code, 200) self.assert_equal(rv.data.strip(), b'

Hello World!

') From eb622fb34f0b2433b21b6b5454273a597b77a6d4 Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Thu, 30 May 2013 14:31:36 +0100 Subject: [PATCH 49/58] Fixed a whole bunch of resource warnings in the flask testsuite --- flask/testsuite/basic.py | 1 + flask/testsuite/blueprints.py | 5 +++++ flask/testsuite/helpers.py | 16 ++++++++++++++++ 3 files changed, 22 insertions(+) diff --git a/flask/testsuite/basic.py b/flask/testsuite/basic.py index 810b5e66..8cd3a822 100644 --- a/flask/testsuite/basic.py +++ b/flask/testsuite/basic.py @@ -793,6 +793,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): with app.test_request_context(): self.assert_equal(flask.url_for('static', filename='index.html'), '/static/index.html') + rv.close() def test_none_response(self): app = flask.Flask(__name__) diff --git a/flask/testsuite/blueprints.py b/flask/testsuite/blueprints.py index b3771fde..5935a473 100644 --- a/flask/testsuite/blueprints.py +++ b/flask/testsuite/blueprints.py @@ -172,8 +172,10 @@ class ModuleTestCase(FlaskTestCase): self.assert_equal(rv.data, b'Hello from the Admin') rv = c.get('/admin/static/test.txt') self.assert_equal(rv.data.strip(), b'Admin File') + rv.close() rv = c.get('/admin/static/css/test.css') self.assert_equal(rv.data.strip(), b'/* nested file */') + rv.close() with app.test_request_context(): self.assert_equal(flask.url_for('admin.static', filename='test.txt'), @@ -354,8 +356,10 @@ class BlueprintTestCase(FlaskTestCase): self.assert_equal(rv.data, b'Hello from the Admin') rv = c.get('/admin/static/test.txt') self.assert_equal(rv.data.strip(), b'Admin File') + rv.close() rv = c.get('/admin/static/css/test.css') self.assert_equal(rv.data.strip(), b'/* nested file */') + rv.close() # try/finally, in case other tests use this app for Blueprint tests. max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT'] @@ -405,6 +409,7 @@ class BlueprintTestCase(FlaskTestCase): rv = blueprint.send_static_file('index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assert_equal(cc.max_age, 100) + rv.close() finally: app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default diff --git a/flask/testsuite/helpers.py b/flask/testsuite/helpers.py index bba66bda..b74ad6bb 100644 --- a/flask/testsuite/helpers.py +++ b/flask/testsuite/helpers.py @@ -159,6 +159,7 @@ class SendfileTestCase(FlaskTestCase): self.assert_equal(rv.mimetype, 'text/html') with app.open_resource('static/index.html') as f: self.assert_equal(rv.data, f.read()) + rv.close() def test_send_file_xsendfile(self): app = flask.Flask(__name__) @@ -170,6 +171,7 @@ class SendfileTestCase(FlaskTestCase): self.assert_equal(rv.headers['x-sendfile'], os.path.join(app.root_path, 'static/index.html')) self.assert_equal(rv.mimetype, 'text/html') + rv.close() def test_send_file_object(self): app = flask.Flask(__name__) @@ -180,6 +182,7 @@ class SendfileTestCase(FlaskTestCase): with app.open_resource('static/index.html') as f: self.assert_equal(rv.data, f.read()) self.assert_equal(rv.mimetype, 'text/html') + rv.close() # mimetypes + etag self.assert_equal(len(captured), 2) @@ -192,6 +195,7 @@ class SendfileTestCase(FlaskTestCase): self.assert_in('x-sendfile', rv.headers) self.assert_equal(rv.headers['x-sendfile'], os.path.join(app.root_path, 'static/index.html')) + rv.close() # mimetypes + etag self.assert_equal(len(captured), 2) @@ -202,6 +206,7 @@ class SendfileTestCase(FlaskTestCase): rv = flask.send_file(f) self.assert_equal(rv.data, b'Test') self.assert_equal(rv.mimetype, 'application/octet-stream') + rv.close() # etags self.assert_equal(len(captured), 1) with catch_warnings() as captured: @@ -209,6 +214,7 @@ class SendfileTestCase(FlaskTestCase): rv = flask.send_file(f, mimetype='text/plain') self.assert_equal(rv.data, b'Test') self.assert_equal(rv.mimetype, 'text/plain') + rv.close() # etags self.assert_equal(len(captured), 1) @@ -218,6 +224,7 @@ class SendfileTestCase(FlaskTestCase): f = StringIO('Test') rv = flask.send_file(f) self.assert_not_in('x-sendfile', rv.headers) + rv.close() # etags self.assert_equal(len(captured), 1) @@ -229,6 +236,7 @@ class SendfileTestCase(FlaskTestCase): rv = flask.send_file(f, as_attachment=True) value, options = parse_options_header(rv.headers['Content-Disposition']) self.assert_equal(value, 'attachment') + rv.close() # mimetypes + etag self.assert_equal(len(captured), 2) @@ -238,6 +246,7 @@ class SendfileTestCase(FlaskTestCase): value, options = parse_options_header(rv.headers['Content-Disposition']) self.assert_equal(value, 'attachment') self.assert_equal(options['filename'], 'index.html') + rv.close() with app.test_request_context(): rv = flask.send_file(StringIO('Test'), as_attachment=True, @@ -247,6 +256,7 @@ class SendfileTestCase(FlaskTestCase): value, options = parse_options_header(rv.headers['Content-Disposition']) self.assert_equal(value, 'attachment') self.assert_equal(options['filename'], 'index.txt') + rv.close() def test_static_file(self): app = flask.Flask(__name__) @@ -256,20 +266,24 @@ class SendfileTestCase(FlaskTestCase): rv = app.send_static_file('index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assert_equal(cc.max_age, 12 * 60 * 60) + rv.close() # Test again with direct use of send_file utility. rv = flask.send_file('static/index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assert_equal(cc.max_age, 12 * 60 * 60) + rv.close() app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600 with app.test_request_context(): # Test with static file handler. rv = app.send_static_file('index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assert_equal(cc.max_age, 3600) + rv.close() # Test again with direct use of send_file utility. rv = flask.send_file('static/index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assert_equal(cc.max_age, 3600) + rv.close() class StaticFileApp(flask.Flask): def get_send_file_max_age(self, filename): return 10 @@ -279,10 +293,12 @@ class SendfileTestCase(FlaskTestCase): rv = app.send_static_file('index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assert_equal(cc.max_age, 10) + rv.close() # Test again with direct use of send_file utility. rv = flask.send_file('static/index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assert_equal(cc.max_age, 10) + rv.close() class LoggingTestCase(FlaskTestCase): From 8aaf3025864acbb803b652495d282bc5aa7a8128 Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Thu, 30 May 2013 14:35:23 +0100 Subject: [PATCH 50/58] Disable direct passthrough for accessing the data attribute on newer Werkzeugs --- flask/testsuite/helpers.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/flask/testsuite/helpers.py b/flask/testsuite/helpers.py index b74ad6bb..20c15262 100644 --- a/flask/testsuite/helpers.py +++ b/flask/testsuite/helpers.py @@ -158,6 +158,7 @@ class SendfileTestCase(FlaskTestCase): self.assert_true(rv.direct_passthrough) self.assert_equal(rv.mimetype, 'text/html') with app.open_resource('static/index.html') as f: + rv.direct_passthrough = False self.assert_equal(rv.data, f.read()) rv.close() @@ -179,6 +180,7 @@ class SendfileTestCase(FlaskTestCase): with app.test_request_context(): f = open(os.path.join(app.root_path, 'static/index.html')) rv = flask.send_file(f) + rv.direct_passthrough = False with app.open_resource('static/index.html') as f: self.assert_equal(rv.data, f.read()) self.assert_equal(rv.mimetype, 'text/html') From 51042f4c9f2c68a63ad5b8ee3000a52518a4b87b Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Thu, 30 May 2013 16:00:43 +0200 Subject: [PATCH 51/58] fix issues in test_context_refcounts that were unnoticed yet as they did not make the test fail --- flask/testsuite/appctx.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/flask/testsuite/appctx.py b/flask/testsuite/appctx.py index 54b9014e..8524d22b 100644 --- a/flask/testsuite/appctx.py +++ b/flask/testsuite/appctx.py @@ -87,8 +87,9 @@ class AppContextTestCase(FlaskTestCase): with flask._app_ctx_stack.top: with flask._request_ctx_stack.top: pass - self.assert_true(flask._request_ctx_stack.request.environ + self.assert_true(flask._request_ctx_stack.top.request.environ ['werkzeug.request'] is not None) + return u'' c = app.test_client() c.get('/') self.assertEqual(called, ['request', 'app']) From bbfef4c406506d89c662038c11c6c67bc97b67e3 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Thu, 30 May 2013 16:02:28 +0200 Subject: [PATCH 52/58] flask view function may return bytes/str/unicode --- flask/app.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flask/app.py b/flask/app.py index c3bbc907..bfd615b7 100644 --- a/flask/app.py +++ b/flask/app.py @@ -1551,7 +1551,7 @@ class Flask(_PackageBoundObject): # set the headers and status. We do this because there can be # some extra logic involved when creating these objects with # specific values (like default content type selection). - if isinstance(rv, string_types): + if isinstance(rv, string_types + (bytes, )): rv = self.response_class(rv, headers=headers, status=status) headers = status = None else: From abc1505196ba3bc9517ec142ced7c1204c3ac21b Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Thu, 30 May 2013 15:07:18 +0100 Subject: [PATCH 53/58] Fixed various issues on the Python 3 port --- flask/_compat.py | 4 ---- flask/json.py | 34 ++++++++++++++++++++++++++++++---- flask/testing.py | 8 ++++++-- 3 files changed, 36 insertions(+), 10 deletions(-) diff --git a/flask/_compat.py b/flask/_compat.py index 7c960ac6..edc9957a 100644 --- a/flask/_compat.py +++ b/flask/_compat.py @@ -47,8 +47,6 @@ if not PY2: encode_filename = _identity get_next = lambda x: x.__next__ - from urllib.parse import urlparse - else: unichr = unichr text_type = unicode @@ -86,8 +84,6 @@ else: return filename.encode('utf-8') return filename - from urlparse import urlparse - def with_metaclass(meta, *bases): # This requires a bit of explanation: the basic idea is to make a diff --git a/flask/json.py b/flask/json.py index 22f6067d..9e56073c 100644 --- a/flask/json.py +++ b/flask/json.py @@ -8,10 +8,11 @@ :copyright: (c) 2012 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ +import io import uuid from datetime import datetime from .globals import current_app, request -from ._compat import text_type +from ._compat import text_type, PY2 from werkzeug.http import http_date @@ -33,6 +34,20 @@ __all__ = ['dump', 'dumps', 'load', 'loads', 'htmlsafe_dump', 'jsonify'] +def _wrap_reader_for_text(fp, encoding): + if isinstance(fp.read(0), bytes): + fp = io.TextIOWrapper(io.BufferedReader(fp), encoding) + return fp + + +def _wrap_writer_for_text(fp, encoding): + try: + fp.write('') + except TypeError: + fp = io.TextIOWrapper(fp, encoding) + return fp + + class JSONEncoder(_json.JSONEncoder): """The default Flask JSON encoder. This one extends the default simplejson encoder by also supporting ``datetime`` objects, ``UUID`` as well as @@ -100,13 +115,20 @@ def dumps(obj, **kwargs): and can be overriden by the simplejson ``ensure_ascii`` parameter. """ _dump_arg_defaults(kwargs) - return _json.dumps(obj, **kwargs) + encoding = kwargs.pop('encoding', None) + rv = _json.dumps(obj, **kwargs) + if encoding is not None and isinstance(rv, text_type): + rv = rv.encode(encoding) + return rv def dump(obj, fp, **kwargs): """Like :func:`dumps` but writes into a file object.""" _dump_arg_defaults(kwargs) - return _json.dump(obj, fp, **kwargs) + encoding = kwargs.pop('encoding', None) + if encoding is not None: + fp = _wrap_writer_for_text(fp, encoding) + _json.dump(obj, fp, **kwargs) def loads(s, **kwargs): @@ -115,6 +137,8 @@ def loads(s, **kwargs): application on the stack. """ _load_arg_defaults(kwargs) + if isinstance(s, bytes): + s = s.decode(kwargs.pop('encoding', None) or 'utf-8') return _json.loads(s, **kwargs) @@ -122,6 +146,8 @@ def load(fp, **kwargs): """Like :func:`loads` but reads from a file object. """ _load_arg_defaults(kwargs) + if not PY2: + fp = _wrap_reader_for_text(fp, kwargs.pop('encoding', None) or 'utf-8') return _json.load(fp, **kwargs) @@ -148,7 +174,7 @@ def jsonify(*args, **kwargs): to this function are the same as to the :class:`dict` constructor. Example usage:: - + from flask import jsonify @app.route('/_get_current_user') diff --git a/flask/testing.py b/flask/testing.py index 4c1f4550..1dc383af 100644 --- a/flask/testing.py +++ b/flask/testing.py @@ -13,7 +13,11 @@ from contextlib import contextmanager from werkzeug.test import Client, EnvironBuilder from flask import _request_ctx_stack -from ._compat import urlparse + +try: + from werkzeug.urls import url_parse +except ImportError: + from urlparse import urlsplit as url_parse def make_test_environ_builder(app, path='/', base_url=None, *args, **kwargs): @@ -21,7 +25,7 @@ def make_test_environ_builder(app, path='/', base_url=None, *args, **kwargs): http_host = app.config.get('SERVER_NAME') app_root = app.config.get('APPLICATION_ROOT') if base_url is None: - url = urlparse(path) + url = url_parse(path) base_url = 'http://%s/' % (url.netloc or http_host or 'localhost') if app_root: base_url += app_root.lstrip('/') From 9ae8487330e0dc3a8d169d89cadf85fb11ded1ea Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Thu, 30 May 2013 16:16:39 +0100 Subject: [PATCH 54/58] Fixed a broekn testcase --- flask/helpers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flask/helpers.py b/flask/helpers.py index f52b5ae4..06343cf3 100644 --- a/flask/helpers.py +++ b/flask/helpers.py @@ -516,7 +516,7 @@ def send_file(filename_or_fp, mimetype=None, as_attachment=False, if file is None: file = open(filename, 'rb') mtime = os.path.getmtime(filename) - headers['Content-Length'] = os.path.getsize(filename) + headers['Content-Length'] = os.path.getsize(filename) data = wrap_file(request.environ, file) rv = current_app.response_class(data, mimetype=mimetype, headers=headers, From 90e3906d02780c47e813649b1e282bfd279d7cb1 Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Thu, 30 May 2013 17:58:27 +0100 Subject: [PATCH 55/58] Fixed some test failures --- flask/testsuite/basic.py | 6 ++++-- flask/testsuite/blueprints.py | 1 + flask/testsuite/helpers.py | 2 ++ 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/flask/testsuite/basic.py b/flask/testsuite/basic.py index 8cd3a822..bd5b2760 100644 --- a/flask/testsuite/basic.py +++ b/flask/testsuite/basic.py @@ -513,7 +513,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): # test that all teardown_requests get passed the same original # exception. try: - raise TypeError + raise TypeError() except: pass @app.teardown_request @@ -524,7 +524,7 @@ class BasicFunctionalityTestCase(FlaskTestCase): # test that all teardown_requests get passed the same original # exception. try: - raise TypeError + raise TypeError() except: pass @app.route('/') @@ -1098,7 +1098,9 @@ class SubdomainTestCase(FlaskTestCase): app.register_module(mod) c = app.test_client() rv = c.get('/static/hello.txt', 'http://foo.example.com/') + rv.direct_passthrough = False self.assert_equal(rv.data.strip(), b'Hello Subdomain') + rv.close() def test_subdomain_matching(self): app = flask.Flask(__name__) diff --git a/flask/testsuite/blueprints.py b/flask/testsuite/blueprints.py index 5935a473..3414eeaa 100644 --- a/flask/testsuite/blueprints.py +++ b/flask/testsuite/blueprints.py @@ -371,6 +371,7 @@ class BlueprintTestCase(FlaskTestCase): rv = c.get('/admin/static/css/test.css') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assert_equal(cc.max_age, expected_max_age) + rv.close() finally: app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default diff --git a/flask/testsuite/helpers.py b/flask/testsuite/helpers.py index 20c15262..7750ae52 100644 --- a/flask/testsuite/helpers.py +++ b/flask/testsuite/helpers.py @@ -206,6 +206,7 @@ class SendfileTestCase(FlaskTestCase): with catch_warnings() as captured: f = StringIO('Test') rv = flask.send_file(f) + rv.direct_passthrough = False self.assert_equal(rv.data, b'Test') self.assert_equal(rv.mimetype, 'application/octet-stream') rv.close() @@ -214,6 +215,7 @@ class SendfileTestCase(FlaskTestCase): with catch_warnings() as captured: f = StringIO('Test') rv = flask.send_file(f, mimetype='text/plain') + rv.direct_passthrough = False self.assert_equal(rv.data, b'Test') self.assert_equal(rv.mimetype, 'text/plain') rv.close() From f1918093ac70d589a4d67af0d77140734c06c13d Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Thu, 30 May 2013 18:15:17 +0100 Subject: [PATCH 56/58] Changed teardown error handling to be more reliable. --- CHANGES | 3 +++ flask/app.py | 20 +++++++++++++++++++- flask/ctx.py | 13 ++++++++----- 3 files changed, 30 insertions(+), 6 deletions(-) diff --git a/CHANGES b/CHANGES index fbde1e2a..17290290 100644 --- a/CHANGES +++ b/CHANGES @@ -59,6 +59,9 @@ Release date to be decided. strongly discouraged as the interface was flawed. - Python requirements changed: requiring Python 2.6 or 2.7 now to prepare for Python 3.3 port. +- Changed how the teardown system is informed about exceptions. This is now + more reliable in case something handles an exception halfway through + the error handling process. Version 0.9 ----------- diff --git a/flask/app.py b/flask/app.py index bfd615b7..28a0a59a 100644 --- a/flask/app.py +++ b/flask/app.py @@ -1510,6 +1510,16 @@ class Flask(_PackageBoundObject): rv.allow.update(methods) return rv + def should_ignore_error(self, error): + """This is called to figure out if an error should be ignored + or not as far as the teardown system is concerned. If this + function returns `True` then the teardown handlers will not be + passed the error. + + .. versionadded:: 0.10 + """ + return False + def make_response(self, rv): """Converts the return value from a view function to a real response object that is an instance of :attr:`response_class`. @@ -1790,12 +1800,20 @@ class Flask(_PackageBoundObject): a list of headers and an optional exception context to start the response """ - with self.request_context(environ): + ctx = self.request_context(environ) + ctx.push() + error = None + try: try: response = self.full_dispatch_request() except Exception as e: + error = e response = self.make_response(self.handle_exception(e)) return response(environ, start_response) + finally: + if self.should_ignore_error(error): + error = None + ctx.auto_pop(error) @property def modules(self): diff --git a/flask/ctx.py b/flask/ctx.py index 259c5e2f..5e1ee2e3 100644 --- a/flask/ctx.py +++ b/flask/ctx.py @@ -352,6 +352,13 @@ class RequestContext(object): if app_ctx is not None: app_ctx.pop(exc) + def auto_pop(self, exc): + if self.request.environ.get('flask._preserve_context') or \ + (exc is not None and self.app.preserve_context_on_exception): + self.preserved = True + else: + self.pop(exc) + def __enter__(self): self.push() return self @@ -362,11 +369,7 @@ class RequestContext(object): # access the request object in the interactive shell. Furthermore # the context can be force kept alive for the test client. # See flask.testing for how this works. - if self.request.environ.get('flask._preserve_context') or \ - (tb is not None and self.app.preserve_context_on_exception): - self.preserved = True - else: - self.pop(exc_value) + self.auto_pop(exc_value) def __repr__(self): return '<%s \'%s\' [%s] of %s>' % ( From e07dcb5562c336975e31ce014aa33d2ab1f5ac98 Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Thu, 30 May 2013 18:17:04 +0100 Subject: [PATCH 57/58] Adjusted a testcase for Python 3 --- flask/testsuite/ext.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/flask/testsuite/ext.py b/flask/testsuite/ext.py index 1a7a4a5a..5cc3df43 100644 --- a/flask/testsuite/ext.py +++ b/flask/testsuite/ext.py @@ -121,7 +121,10 @@ class ExtImportHookTestCase(FlaskTestCase): self.assert_true(tb.tb_frame.f_globals is globals()) # reraise() adds a second frame so we need to skip that one too. + # On PY3 we even have another one :( next = tb.tb_next.tb_next + if not PY2: + next = next.tb_next self.assert_in('flask_broken/__init__.py', next.tb_frame.f_code.co_filename) From b8aa9fed9a6837d29c472c642539dcf3496479ab Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Thu, 30 May 2013 18:19:01 +0100 Subject: [PATCH 58/58] Added tox-test command --- Makefile | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 4b5e4fe2..b67c8a9f 100644 --- a/Makefile +++ b/Makefile @@ -1,10 +1,13 @@ -.PHONY: clean-pyc ext-test test test-with-mem upload-docs docs audit +.PHONY: clean-pyc ext-test test tox-test test-with-mem upload-docs docs audit all: clean-pyc test test: python run-tests.py +tox-test: + tox + test-with-mem: RUN_FLASK_MEMORY_TESTS=1 python run-tests.py