Browse Source

Rewrite assertion methods

pull/1165/head
Markus Unterwaditzer 10 years ago
parent
commit
5da2c00419
  1. 34
      tests/__init__.py
  2. 33
      tests/test_appctx.py
  3. 505
      tests/test_basic.py
  4. 150
      tests/test_blueprints.py
  5. 66
      tests/test_config.py
  6. 53
      tests/test_ext.py
  7. 194
      tests/test_helpers.py
  8. 10
      tests/test_regression.py
  9. 95
      tests/test_reqctx.py
  10. 33
      tests/test_signals.py
  11. 6
      tests/test_subclassing.py
  12. 128
      tests/test_templating.py
  13. 74
      tests/test_testing.py
  14. 32
      tests/test_views.py

34
tests/__init__.py

@ -78,9 +78,9 @@ def emits_module_deprecation_warning(f):
def new_f(self, *args, **kwargs): def new_f(self, *args, **kwargs):
with catch_warnings() as log: with catch_warnings() as log:
f(self, *args, **kwargs) f(self, *args, **kwargs)
self.assert_true(log, 'expected deprecation warning') assert log, 'expected deprecation warning'
for entry in log: for entry in log:
self.assert_in('Modules are deprecated', str(entry['message'])) assert 'Modules are deprecated' in str(entry['message'])
return update_wrapper(new_f, f) return update_wrapper(new_f, f)
@ -107,7 +107,7 @@ class TestFlask(object):
leaks = [] leaks = []
while flask._request_ctx_stack.top is not None: while flask._request_ctx_stack.top is not None:
leaks.append(flask._request_ctx_stack.pop()) leaks.append(flask._request_ctx_stack.pop())
self.assert_equal(leaks, []) assert leaks == []
def setup_method(self, method): def setup_method(self, method):
self.setup() self.setup()
@ -120,31 +120,3 @@ class TestFlask(object):
def teardown(self): def teardown(self):
pass pass
def assert_equal(self, x, y):
assert x == y
def assert_raises(self, exc_type, callable=None, *args, **kwargs):
if callable:
return pytest.raises(exc_type, callable, *args, **kwargs)
else:
return pytest.raises(exc_type)
def assert_true(self, x, msg=None):
assert x
assert_ = assert_true
def assert_false(self, x, msg=None):
assert not x
def assert_in(self, x, y):
assert x in y
def assert_not_in(self, x, y):
assert x not in y
def assert_isinstance(self, obj, cls):
assert isinstance(obj, cls)
def fail(self, msg):
raise AssertionError(msg)

33
tests/test_appctx.py

@ -9,6 +9,8 @@
:license: BSD, see LICENSE for more details. :license: BSD, see LICENSE for more details.
""" """
import pytest
import flask import flask
import unittest import unittest
from tests import TestFlask from tests import TestFlask
@ -27,29 +29,29 @@ class TestAppContext(TestFlask):
with app.app_context(): with app.app_context():
rv = flask.url_for('index') rv = flask.url_for('index')
self.assert_equal(rv, 'https://localhost/') assert rv == 'https://localhost/'
def test_url_generation_requires_server_name(self): def test_url_generation_requires_server_name(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
with app.app_context(): with app.app_context():
with self.assert_raises(RuntimeError): with pytest.raises(RuntimeError):
flask.url_for('index') flask.url_for('index')
def test_url_generation_without_context_fails(self): def test_url_generation_without_context_fails(self):
with self.assert_raises(RuntimeError): with pytest.raises(RuntimeError):
flask.url_for('index') flask.url_for('index')
def test_request_context_means_app_context(self): def test_request_context_means_app_context(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
with app.test_request_context(): with app.test_request_context():
self.assert_equal(flask.current_app._get_current_object(), app) assert flask.current_app._get_current_object() == app
self.assert_equal(flask._app_ctx_stack.top, None) assert flask._app_ctx_stack.top == None
def test_app_context_provides_current_app(self): def test_app_context_provides_current_app(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
with app.app_context(): with app.app_context():
self.assert_equal(flask.current_app._get_current_object(), app) assert flask.current_app._get_current_object() == app
self.assert_equal(flask._app_ctx_stack.top, None) assert flask._app_ctx_stack.top == None
def test_app_tearing_down(self): def test_app_tearing_down(self):
cleanup_stuff = [] cleanup_stuff = []
@ -61,7 +63,7 @@ class TestAppContext(TestFlask):
with app.app_context(): with app.app_context():
pass pass
self.assert_equal(cleanup_stuff, [None]) assert cleanup_stuff == [None]
def test_app_tearing_down_with_previous_exception(self): def test_app_tearing_down_with_previous_exception(self):
cleanup_stuff = [] cleanup_stuff = []
@ -78,7 +80,7 @@ class TestAppContext(TestFlask):
with app.app_context(): with app.app_context():
pass pass
self.assert_equal(cleanup_stuff, [None]) assert cleanup_stuff == [None]
def test_custom_app_ctx_globals_class(self): def test_custom_app_ctx_globals_class(self):
class CustomRequestGlobals(object): class CustomRequestGlobals(object):
@ -87,8 +89,7 @@ class TestAppContext(TestFlask):
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.app_ctx_globals_class = CustomRequestGlobals app.app_ctx_globals_class = CustomRequestGlobals
with app.app_context(): with app.app_context():
self.assert_equal( assert flask.render_template_string('{{ g.spam }}') == 'eggs'
flask.render_template_string('{{ g.spam }}'), 'eggs')
def test_context_refcounts(self): def test_context_refcounts(self):
called = [] called = []
@ -104,12 +105,14 @@ class TestAppContext(TestFlask):
with flask._app_ctx_stack.top: with flask._app_ctx_stack.top:
with flask._request_ctx_stack.top: with flask._request_ctx_stack.top:
pass pass
self.assert_true(flask._request_ctx_stack.top.request.environ env = flask._request_ctx_stack.top.request.environ
['werkzeug.request'] is not None) assert env['werkzeug.request'] is not None
return u'' return u''
c = app.test_client() c = app.test_client()
c.get('/') res = c.get('/')
self.assert_equal(called, ['request', 'app']) assert res.status_code == 200
assert res.data == u''
assert called == ['request', 'app']
def suite(): def suite():

505
tests/test_basic.py

File diff suppressed because it is too large Load Diff

150
tests/test_blueprints.py

@ -9,6 +9,8 @@
:license: BSD, see LICENSE for more details. :license: BSD, see LICENSE for more details.
""" """
import pytest
import flask import flask
import unittest import unittest
from tests import TestFlask from tests import TestFlask
@ -55,9 +57,9 @@ class TestBlueprint(TestFlask):
c = app.test_client() c = app.test_client()
self.assert_equal(c.get('/frontend-no').data, b'frontend says no') assert c.get('/frontend-no').data == b'frontend says no'
self.assert_equal(c.get('/backend-no').data, b'backend says no') assert c.get('/backend-no').data == b'backend says no'
self.assert_equal(c.get('/what-is-a-sideend').data, b'application itself says no') assert c.get('/what-is-a-sideend').data == b'application itself says no'
def test_blueprint_specific_user_error_handling(self): def test_blueprint_specific_user_error_handling(self):
class MyDecoratorException(Exception): class MyDecoratorException(Exception):
@ -69,11 +71,11 @@ class TestBlueprint(TestFlask):
@blue.errorhandler(MyDecoratorException) @blue.errorhandler(MyDecoratorException)
def my_decorator_exception_handler(e): def my_decorator_exception_handler(e):
self.assert_true(isinstance(e, MyDecoratorException)) assert isinstance(e, MyDecoratorException)
return 'boom' return 'boom'
def my_function_exception_handler(e): def my_function_exception_handler(e):
self.assert_true(isinstance(e, MyFunctionException)) assert isinstance(e, MyFunctionException)
return 'bam' return 'bam'
blue.register_error_handler(MyFunctionException, my_function_exception_handler) blue.register_error_handler(MyFunctionException, my_function_exception_handler)
@ -89,8 +91,8 @@ class TestBlueprint(TestFlask):
c = app.test_client() c = app.test_client()
self.assert_equal(c.get('/decorator').data, b'boom') assert c.get('/decorator').data == b'boom'
self.assert_equal(c.get('/function').data, b'bam') assert c.get('/function').data == b'bam'
def test_blueprint_url_definitions(self): def test_blueprint_url_definitions(self):
bp = flask.Blueprint('test', __name__) bp = flask.Blueprint('test', __name__)
@ -108,10 +110,10 @@ class TestBlueprint(TestFlask):
app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19}) app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19})
c = app.test_client() c = app.test_client()
self.assert_equal(c.get('/1/foo').data, b'23/42') assert c.get('/1/foo').data == b'23/42'
self.assert_equal(c.get('/2/foo').data, b'19/42') assert c.get('/2/foo').data == b'19/42'
self.assert_equal(c.get('/1/bar').data, b'23') assert c.get('/1/bar').data == b'23'
self.assert_equal(c.get('/2/bar').data, b'19') assert c.get('/2/bar').data == b'19'
def test_blueprint_url_processors(self): def test_blueprint_url_processors(self):
bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>') bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')
@ -137,24 +139,24 @@ class TestBlueprint(TestFlask):
c = app.test_client() c = app.test_client()
self.assert_equal(c.get('/de/').data, b'/de/about') assert c.get('/de/').data == b'/de/about'
self.assert_equal(c.get('/de/about').data, b'/de/') assert c.get('/de/about').data == b'/de/'
def test_templates_and_static(self): def test_templates_and_static(self):
from blueprintapp import app from blueprintapp import app
c = app.test_client() c = app.test_client()
rv = c.get('/') rv = c.get('/')
self.assert_equal(rv.data, b'Hello from the Frontend') assert rv.data == b'Hello from the Frontend'
rv = c.get('/admin/') rv = c.get('/admin/')
self.assert_equal(rv.data, b'Hello from the Admin') assert rv.data == b'Hello from the Admin'
rv = c.get('/admin/index2') rv = c.get('/admin/index2')
self.assert_equal(rv.data, b'Hello from the Admin') assert rv.data == b'Hello from the Admin'
rv = c.get('/admin/static/test.txt') rv = c.get('/admin/static/test.txt')
self.assert_equal(rv.data.strip(), b'Admin File') assert rv.data.strip() == b'Admin File'
rv.close() rv.close()
rv = c.get('/admin/static/css/test.css') rv = c.get('/admin/static/css/test.css')
self.assert_equal(rv.data.strip(), b'/* nested file */') assert rv.data.strip() == b'/* nested file */'
rv.close() rv.close()
# try/finally, in case other tests use this app for Blueprint tests. # try/finally, in case other tests use this app for Blueprint tests.
@ -166,25 +168,24 @@ class TestBlueprint(TestFlask):
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age
rv = c.get('/admin/static/css/test.css') rv = c.get('/admin/static/css/test.css')
cc = parse_cache_control_header(rv.headers['Cache-Control']) cc = parse_cache_control_header(rv.headers['Cache-Control'])
self.assert_equal(cc.max_age, expected_max_age) assert cc.max_age == expected_max_age
rv.close() rv.close()
finally: finally:
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default
with app.test_request_context(): with app.test_request_context():
self.assert_equal(flask.url_for('admin.static', filename='test.txt'), assert flask.url_for('admin.static', filename='test.txt') == '/admin/static/test.txt'
'/admin/static/test.txt')
with app.test_request_context(): with app.test_request_context():
try: try:
flask.render_template('missing.html') flask.render_template('missing.html')
except TemplateNotFound as e: except TemplateNotFound as e:
self.assert_equal(e.name, 'missing.html') assert e.name == 'missing.html'
else: else:
self.assert_true(0, 'expected exception') assert 0, 'expected exception'
with flask.Flask(__name__).test_request_context(): with flask.Flask(__name__).test_request_context():
self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested') assert flask.render_template('nested/nested.txt') == 'I\'m nested'
def test_default_static_cache_timeout(self): def test_default_static_cache_timeout(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -205,7 +206,7 @@ class TestBlueprint(TestFlask):
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = unexpected_max_age app.config['SEND_FILE_MAX_AGE_DEFAULT'] = unexpected_max_age
rv = blueprint.send_static_file('index.html') rv = blueprint.send_static_file('index.html')
cc = parse_cache_control_header(rv.headers['Cache-Control']) cc = parse_cache_control_header(rv.headers['Cache-Control'])
self.assert_equal(cc.max_age, 100) assert cc.max_age == 100
rv.close() rv.close()
finally: finally:
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default
@ -213,8 +214,7 @@ class TestBlueprint(TestFlask):
def test_templates_list(self): def test_templates_list(self):
from blueprintapp import app from blueprintapp import app
templates = sorted(app.jinja_env.list_templates()) templates = sorted(app.jinja_env.list_templates())
self.assert_equal(templates, ['admin/index.html', assert templates == ['admin/index.html', 'frontend/index.html']
'frontend/index.html'])
def test_dotted_names(self): def test_dotted_names(self):
frontend = flask.Blueprint('myapp.frontend', __name__) frontend = flask.Blueprint('myapp.frontend', __name__)
@ -237,9 +237,9 @@ class TestBlueprint(TestFlask):
app.register_blueprint(backend) app.register_blueprint(backend)
c = app.test_client() c = app.test_client()
self.assert_equal(c.get('/fe').data.strip(), b'/be') assert c.get('/fe').data.strip() == b'/be'
self.assert_equal(c.get('/fe2').data.strip(), b'/fe') assert c.get('/fe2').data.strip() == b'/fe'
self.assert_equal(c.get('/be').data.strip(), b'/fe') assert c.get('/be').data.strip() == b'/fe'
def test_dotted_names_from_app(self): def test_dotted_names_from_app(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -258,7 +258,7 @@ class TestBlueprint(TestFlask):
with app.test_client() as c: with app.test_client() as c:
rv = c.get('/') rv = c.get('/')
self.assert_equal(rv.data, b'/test/') assert rv.data == b'/test/'
def test_empty_url_defaults(self): def test_empty_url_defaults(self):
bp = flask.Blueprint('bp', __name__) bp = flask.Blueprint('bp', __name__)
@ -272,8 +272,8 @@ class TestBlueprint(TestFlask):
app.register_blueprint(bp) app.register_blueprint(bp)
c = app.test_client() c = app.test_client()
self.assert_equal(c.get('/').data, b'1') assert c.get('/').data == b'1'
self.assert_equal(c.get('/page/2').data, b'2') assert c.get('/page/2').data == b'2'
def test_route_decorator_custom_endpoint(self): def test_route_decorator_custom_endpoint(self):
@ -303,11 +303,11 @@ class TestBlueprint(TestFlask):
return flask.request.endpoint return flask.request.endpoint
c = app.test_client() c = app.test_client()
self.assert_equal(c.get('/').data, b'index') assert c.get('/').data == b'index'
self.assert_equal(c.get('/py/foo').data, b'bp.foo') assert c.get('/py/foo').data == b'bp.foo'
self.assert_equal(c.get('/py/bar').data, b'bp.bar') assert c.get('/py/bar').data == b'bp.bar'
self.assert_equal(c.get('/py/bar/123').data, b'bp.123') assert c.get('/py/bar/123').data == b'bp.123'
self.assert_equal(c.get('/py/bar/foo').data, b'bp.bar_foo') assert c.get('/py/bar/foo').data == b'bp.bar_foo'
def test_route_decorator_custom_endpoint_with_dots(self): def test_route_decorator_custom_endpoint_with_dots(self):
bp = flask.Blueprint('bp', __name__) bp = flask.Blueprint('bp', __name__)
@ -337,14 +337,14 @@ class TestBlueprint(TestFlask):
def foo_foo_foo(): def foo_foo_foo():
pass pass
self.assert_raises( pytest.raises(
AssertionError, AssertionError,
lambda: bp.add_url_rule( lambda: bp.add_url_rule(
'/bar/123', endpoint='bar.123', view_func=foo_foo_foo '/bar/123', endpoint='bar.123', view_func=foo_foo_foo
) )
) )
self.assert_raises( pytest.raises(
AssertionError, AssertionError,
bp.route('/bar/123', endpoint='bar.123'), bp.route('/bar/123', endpoint='bar.123'),
lambda: None lambda: None
@ -354,7 +354,7 @@ class TestBlueprint(TestFlask):
app.register_blueprint(bp, url_prefix='/py') app.register_blueprint(bp, url_prefix='/py')
c = app.test_client() c = app.test_client()
self.assert_equal(c.get('/py/foo').data, b'bp.foo') assert c.get('/py/foo').data == b'bp.foo'
# The rule's didn't actually made it through # The rule's didn't actually made it through
rv = c.get('/py/bar') rv = c.get('/py/bar')
assert rv.status_code == 404 assert rv.status_code == 404
@ -368,9 +368,9 @@ class TestBlueprint(TestFlask):
return s[::-1] return s[::-1]
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py') app.register_blueprint(bp, url_prefix='/py')
self.assert_in('my_reverse', app.jinja_env.filters.keys()) assert 'my_reverse' in app.jinja_env.filters.keys()
self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse) assert app.jinja_env.filters['my_reverse'] == my_reverse
self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba') assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'
def test_add_template_filter(self): def test_add_template_filter(self):
bp = flask.Blueprint('bp', __name__) bp = flask.Blueprint('bp', __name__)
@ -379,9 +379,9 @@ class TestBlueprint(TestFlask):
bp.add_app_template_filter(my_reverse) bp.add_app_template_filter(my_reverse)
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py') app.register_blueprint(bp, url_prefix='/py')
self.assert_in('my_reverse', app.jinja_env.filters.keys()) assert 'my_reverse' in app.jinja_env.filters.keys()
self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse) assert app.jinja_env.filters['my_reverse'] == my_reverse
self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba') assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'
def test_template_filter_with_name(self): def test_template_filter_with_name(self):
bp = flask.Blueprint('bp', __name__) bp = flask.Blueprint('bp', __name__)
@ -390,9 +390,9 @@ class TestBlueprint(TestFlask):
return s[::-1] return s[::-1]
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py') app.register_blueprint(bp, url_prefix='/py')
self.assert_in('strrev', app.jinja_env.filters.keys()) assert 'strrev' in app.jinja_env.filters.keys()
self.assert_equal(app.jinja_env.filters['strrev'], my_reverse) assert app.jinja_env.filters['strrev'] == my_reverse
self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba') assert app.jinja_env.filters['strrev']('abcd') == 'dcba'
def test_add_template_filter_with_name(self): def test_add_template_filter_with_name(self):
bp = flask.Blueprint('bp', __name__) bp = flask.Blueprint('bp', __name__)
@ -401,9 +401,9 @@ class TestBlueprint(TestFlask):
bp.add_app_template_filter(my_reverse, 'strrev') bp.add_app_template_filter(my_reverse, 'strrev')
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py') app.register_blueprint(bp, url_prefix='/py')
self.assert_in('strrev', app.jinja_env.filters.keys()) assert 'strrev' in app.jinja_env.filters.keys()
self.assert_equal(app.jinja_env.filters['strrev'], my_reverse) assert app.jinja_env.filters['strrev'] == my_reverse
self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba') assert app.jinja_env.filters['strrev']('abcd') == 'dcba'
def test_template_filter_with_template(self): def test_template_filter_with_template(self):
bp = flask.Blueprint('bp', __name__) bp = flask.Blueprint('bp', __name__)
@ -416,7 +416,7 @@ class TestBlueprint(TestFlask):
def index(): def index():
return flask.render_template('template_filter.html', value='abcd') return flask.render_template('template_filter.html', value='abcd')
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_equal(rv.data, b'dcba') assert rv.data == b'dcba'
def test_template_filter_after_route_with_template(self): def test_template_filter_after_route_with_template(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -429,7 +429,7 @@ class TestBlueprint(TestFlask):
return s[::-1] return s[::-1]
app.register_blueprint(bp, url_prefix='/py') app.register_blueprint(bp, url_prefix='/py')
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_equal(rv.data, b'dcba') assert rv.data == b'dcba'
def test_add_template_filter_with_template(self): def test_add_template_filter_with_template(self):
bp = flask.Blueprint('bp', __name__) bp = flask.Blueprint('bp', __name__)
@ -442,7 +442,7 @@ class TestBlueprint(TestFlask):
def index(): def index():
return flask.render_template('template_filter.html', value='abcd') return flask.render_template('template_filter.html', value='abcd')
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_equal(rv.data, b'dcba') assert rv.data == b'dcba'
def test_template_filter_with_name_and_template(self): def test_template_filter_with_name_and_template(self):
bp = flask.Blueprint('bp', __name__) bp = flask.Blueprint('bp', __name__)
@ -455,7 +455,7 @@ class TestBlueprint(TestFlask):
def index(): def index():
return flask.render_template('template_filter.html', value='abcd') return flask.render_template('template_filter.html', value='abcd')
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_equal(rv.data, b'dcba') assert rv.data == b'dcba'
def test_add_template_filter_with_name_and_template(self): def test_add_template_filter_with_name_and_template(self):
bp = flask.Blueprint('bp', __name__) bp = flask.Blueprint('bp', __name__)
@ -468,7 +468,7 @@ class TestBlueprint(TestFlask):
def index(): def index():
return flask.render_template('template_filter.html', value='abcd') return flask.render_template('template_filter.html', value='abcd')
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_equal(rv.data, b'dcba') assert rv.data == b'dcba'
def test_template_test(self): def test_template_test(self):
bp = flask.Blueprint('bp', __name__) bp = flask.Blueprint('bp', __name__)
@ -477,9 +477,9 @@ class TestBlueprint(TestFlask):
return isinstance(value, bool) return isinstance(value, bool)
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py') app.register_blueprint(bp, url_prefix='/py')
self.assert_in('is_boolean', app.jinja_env.tests.keys()) assert 'is_boolean' in app.jinja_env.tests.keys()
self.assert_equal(app.jinja_env.tests['is_boolean'], is_boolean) assert app.jinja_env.tests['is_boolean'] == is_boolean
self.assert_true(app.jinja_env.tests['is_boolean'](False)) assert app.jinja_env.tests['is_boolean'](False)
def test_add_template_test(self): def test_add_template_test(self):
bp = flask.Blueprint('bp', __name__) bp = flask.Blueprint('bp', __name__)
@ -488,9 +488,9 @@ class TestBlueprint(TestFlask):
bp.add_app_template_test(is_boolean) bp.add_app_template_test(is_boolean)
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py') app.register_blueprint(bp, url_prefix='/py')
self.assert_in('is_boolean', app.jinja_env.tests.keys()) assert 'is_boolean' in app.jinja_env.tests.keys()
self.assert_equal(app.jinja_env.tests['is_boolean'], is_boolean) assert app.jinja_env.tests['is_boolean'] == is_boolean
self.assert_true(app.jinja_env.tests['is_boolean'](False)) assert app.jinja_env.tests['is_boolean'](False)
def test_template_test_with_name(self): def test_template_test_with_name(self):
bp = flask.Blueprint('bp', __name__) bp = flask.Blueprint('bp', __name__)
@ -499,9 +499,9 @@ class TestBlueprint(TestFlask):
return isinstance(value, bool) return isinstance(value, bool)
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py') app.register_blueprint(bp, url_prefix='/py')
self.assert_in('boolean', app.jinja_env.tests.keys()) assert 'boolean' in app.jinja_env.tests.keys()
self.assert_equal(app.jinja_env.tests['boolean'], is_boolean) assert app.jinja_env.tests['boolean'] == is_boolean
self.assert_true(app.jinja_env.tests['boolean'](False)) assert app.jinja_env.tests['boolean'](False)
def test_add_template_test_with_name(self): def test_add_template_test_with_name(self):
bp = flask.Blueprint('bp', __name__) bp = flask.Blueprint('bp', __name__)
@ -510,9 +510,9 @@ class TestBlueprint(TestFlask):
bp.add_app_template_test(is_boolean, 'boolean') bp.add_app_template_test(is_boolean, 'boolean')
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.register_blueprint(bp, url_prefix='/py') app.register_blueprint(bp, url_prefix='/py')
self.assert_in('boolean', app.jinja_env.tests.keys()) assert 'boolean' in app.jinja_env.tests.keys()
self.assert_equal(app.jinja_env.tests['boolean'], is_boolean) assert app.jinja_env.tests['boolean'] == is_boolean
self.assert_true(app.jinja_env.tests['boolean'](False)) assert app.jinja_env.tests['boolean'](False)
def test_template_test_with_template(self): def test_template_test_with_template(self):
bp = flask.Blueprint('bp', __name__) bp = flask.Blueprint('bp', __name__)
@ -525,7 +525,7 @@ class TestBlueprint(TestFlask):
def index(): def index():
return flask.render_template('template_test.html', value=False) return flask.render_template('template_test.html', value=False)
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_in(b'Success!', rv.data) assert b'Success!' in rv.data
def test_template_test_after_route_with_template(self): def test_template_test_after_route_with_template(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -538,7 +538,7 @@ class TestBlueprint(TestFlask):
return isinstance(value, bool) return isinstance(value, bool)
app.register_blueprint(bp, url_prefix='/py') app.register_blueprint(bp, url_prefix='/py')
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_in(b'Success!', rv.data) assert b'Success!' in rv.data
def test_add_template_test_with_template(self): def test_add_template_test_with_template(self):
bp = flask.Blueprint('bp', __name__) bp = flask.Blueprint('bp', __name__)
@ -551,7 +551,7 @@ class TestBlueprint(TestFlask):
def index(): def index():
return flask.render_template('template_test.html', value=False) return flask.render_template('template_test.html', value=False)
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_in(b'Success!', rv.data) assert b'Success!' in rv.data
def test_template_test_with_name_and_template(self): def test_template_test_with_name_and_template(self):
bp = flask.Blueprint('bp', __name__) bp = flask.Blueprint('bp', __name__)
@ -564,7 +564,7 @@ class TestBlueprint(TestFlask):
def index(): def index():
return flask.render_template('template_test.html', value=False) return flask.render_template('template_test.html', value=False)
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_in(b'Success!', rv.data) assert b'Success!' in rv.data
def test_add_template_test_with_name_and_template(self): def test_add_template_test_with_name_and_template(self):
bp = flask.Blueprint('bp', __name__) bp = flask.Blueprint('bp', __name__)
@ -577,7 +577,7 @@ class TestBlueprint(TestFlask):
def index(): def index():
return flask.render_template('template_test.html', value=False) return flask.render_template('template_test.html', value=False)
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_in(b'Success!', rv.data) assert b'Success!' in rv.data
def suite(): def suite():
suite = unittest.TestSuite() suite = unittest.TestSuite()

66
tests/test_config.py

@ -30,9 +30,9 @@ SECRET_KEY = 'devkey'
class TestConfig(TestFlask): class TestConfig(TestFlask):
def common_object_test(self, app): def common_object_test(self, app):
self.assert_equal(app.secret_key, 'devkey') assert app.secret_key == 'devkey'
self.assert_equal(app.config['TEST_KEY'], 'foo') assert app.config['TEST_KEY'] == 'foo'
self.assert_not_in('TestConfig', app.config) assert 'TestConfig' not in app.config
def test_config_from_file(self): def test_config_from_file(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -73,7 +73,7 @@ class TestConfig(TestFlask):
self.common_object_test(app) self.common_object_test(app)
app = flask.Flask(__name__) app = flask.Flask(__name__)
with self.assert_raises(TypeError): with pytest.raises(TypeError):
app.config.from_mapping( app.config.from_mapping(
{}, {} {}, {}
) )
@ -95,13 +95,13 @@ class TestConfig(TestFlask):
try: try:
app.config.from_envvar('FOO_SETTINGS') app.config.from_envvar('FOO_SETTINGS')
except RuntimeError as e: except RuntimeError as e:
self.assert_true("'FOO_SETTINGS' is not set" in str(e)) assert "'FOO_SETTINGS' is not set" in str(e)
else: else:
self.assert_true(0, 'expected exception') assert 0, 'expected exception'
self.assert_false(app.config.from_envvar('FOO_SETTINGS', silent=True)) assert not app.config.from_envvar('FOO_SETTINGS', silent=True)
os.environ = {'FOO_SETTINGS': __file__.rsplit('.', 1)[0] + '.py'} os.environ = {'FOO_SETTINGS': __file__.rsplit('.', 1)[0] + '.py'}
self.assert_true(app.config.from_envvar('FOO_SETTINGS')) assert app.config.from_envvar('FOO_SETTINGS')
self.common_object_test(app) self.common_object_test(app)
finally: finally:
os.environ = env os.environ = env
@ -115,12 +115,12 @@ class TestConfig(TestFlask):
app.config.from_envvar('FOO_SETTINGS') app.config.from_envvar('FOO_SETTINGS')
except IOError as e: except IOError as e:
msg = str(e) msg = str(e)
self.assert_true(msg.startswith('[Errno 2] Unable to load configuration ' assert msg.startswith('[Errno 2] Unable to load configuration '
'file (No such file or directory):')) 'file (No such file or directory):')
self.assert_true(msg.endswith("missing.cfg'")) assert msg.endswith("missing.cfg'")
else: else:
self.fail('expected IOError') assert False, 'expected IOError'
self.assert_false(app.config.from_envvar('FOO_SETTINGS', silent=True)) assert not app.config.from_envvar('FOO_SETTINGS', silent=True)
finally: finally:
os.environ = env os.environ = env
@ -130,12 +130,12 @@ class TestConfig(TestFlask):
app.config.from_pyfile('missing.cfg') app.config.from_pyfile('missing.cfg')
except IOError as e: except IOError as e:
msg = str(e) msg = str(e)
self.assert_true(msg.startswith('[Errno 2] Unable to load configuration ' assert msg.startswith('[Errno 2] Unable to load configuration '
'file (No such file or directory):')) 'file (No such file or directory):')
self.assert_true(msg.endswith("missing.cfg'")) assert msg.endswith("missing.cfg'")
else: else:
self.assert_true(0, 'expected config') assert 0, 'expected config'
self.assert_false(app.config.from_pyfile('missing.cfg', silent=True)) assert not app.config.from_pyfile('missing.cfg', silent=True)
def test_config_missing_json(self): def test_config_missing_json(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -143,12 +143,12 @@ class TestConfig(TestFlask):
app.config.from_json('missing.json') app.config.from_json('missing.json')
except IOError as e: except IOError as e:
msg = str(e) msg = str(e)
self.assert_true(msg.startswith('[Errno 2] Unable to load configuration ' assert msg.startswith('[Errno 2] Unable to load configuration '
'file (No such file or directory):')) 'file (No such file or directory):')
self.assert_true(msg.endswith("missing.json'")) assert msg.endswith("missing.json'")
else: else:
self.assert_true(0, 'expected config') assert 0, 'expected config'
self.assert_false(app.config.from_json('missing.json', silent=True)) assert not app.config.from_json('missing.json', silent=True)
def test_custom_config_class(self): def test_custom_config_class(self):
class Config(flask.Config): class Config(flask.Config):
@ -156,14 +156,14 @@ class TestConfig(TestFlask):
class Flask(flask.Flask): class Flask(flask.Flask):
config_class = Config config_class = Config
app = Flask(__name__) app = Flask(__name__)
self.assert_isinstance(app.config, Config) assert isinstance(app.config, Config)
app.config.from_object(__name__) app.config.from_object(__name__)
self.common_object_test(app) self.common_object_test(app)
def test_session_lifetime(self): def test_session_lifetime(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.config['PERMANENT_SESSION_LIFETIME'] = 42 app.config['PERMANENT_SESSION_LIFETIME'] = 42
self.assert_equal(app.permanent_session_lifetime.seconds, 42) assert app.permanent_session_lifetime.seconds == 42
def test_get_namespace(self): def test_get_namespace(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -172,13 +172,13 @@ class TestConfig(TestFlask):
app.config['BAR_STUFF_1'] = 'bar stuff 1' app.config['BAR_STUFF_1'] = 'bar stuff 1'
app.config['BAR_STUFF_2'] = 'bar stuff 2' app.config['BAR_STUFF_2'] = 'bar stuff 2'
foo_options = app.config.get_namespace('FOO_') foo_options = app.config.get_namespace('FOO_')
self.assert_equal(2, len(foo_options)) assert 2 == len(foo_options)
self.assert_equal('foo option 1', foo_options['option_1']) assert 'foo option 1' == foo_options['option_1']
self.assert_equal('foo option 2', foo_options['option_2']) assert 'foo option 2' == foo_options['option_2']
bar_options = app.config.get_namespace('BAR_', lowercase=False) bar_options = app.config.get_namespace('BAR_', lowercase=False)
self.assert_equal(2, len(bar_options)) assert 2 == len(bar_options)
self.assert_equal('bar stuff 1', bar_options['STUFF_1']) assert 'bar stuff 1' == bar_options['STUFF_1']
self.assert_equal('bar stuff 2', bar_options['STUFF_2']) assert 'bar stuff 2' == bar_options['STUFF_2']
class TestInstance(TestFlask): class TestInstance(TestFlask):
@ -188,7 +188,7 @@ class TestInstance(TestFlask):
assert 'must be absolute' in str(excinfo.value) assert 'must be absolute' in str(excinfo.value)
app = flask.Flask(__name__, instance_path=str(apps_tmpdir)) app = flask.Flask(__name__, instance_path=str(apps_tmpdir))
self.assert_equal(app.instance_path, str(apps_tmpdir)) assert app.instance_path == str(apps_tmpdir)
def test_main_module_paths(self, apps_tmpdir, purge_module): def test_main_module_paths(self, apps_tmpdir, purge_module):
app = apps_tmpdir.join('main_app.py') app = apps_tmpdir.join('main_app.py')
@ -285,7 +285,7 @@ class TestInstance(TestFlask):
return self return self
sys.meta_path.append(Loader()) sys.meta_path.append(Loader())
try: try:
with self.assert_raises(AttributeError): with pytest.raises(AttributeError):
flask.Flask(__name__) flask.Flask(__name__)
finally: finally:
sys.meta_path.pop() sys.meta_path.pop()

53
tests/test_ext.py

@ -11,6 +11,8 @@
import sys import sys
import unittest import unittest
import pytest
try: try:
from imp import reload as reload_module from imp import reload as reload_module
except ImportError: except ImportError:
@ -41,70 +43,70 @@ class TestExtImportHook(TestFlask):
if cls.__module__ == 'flask.exthook' and \ if cls.__module__ == 'flask.exthook' and \
cls.__name__ == 'ExtensionImporter': cls.__name__ == 'ExtensionImporter':
import_hooks += 1 import_hooks += 1
self.assert_equal(import_hooks, 1) assert import_hooks == 1
def teardown(self): def teardown(self):
from flask import ext from flask import ext
for key in ext.__dict__: for key in ext.__dict__:
self.assert_not_in('.', key) assert '.' not in key
def test_flaskext_new_simple_import_normal(self): def test_flaskext_new_simple_import_normal(self):
from flask.ext.newext_simple import ext_id from flask.ext.newext_simple import ext_id
self.assert_equal(ext_id, 'newext_simple') assert ext_id == 'newext_simple'
def test_flaskext_new_simple_import_module(self): def test_flaskext_new_simple_import_module(self):
from flask.ext import newext_simple from flask.ext import newext_simple
self.assert_equal(newext_simple.ext_id, 'newext_simple') assert newext_simple.ext_id == 'newext_simple'
self.assert_equal(newext_simple.__name__, 'flask_newext_simple') assert newext_simple.__name__ == 'flask_newext_simple'
def test_flaskext_new_package_import_normal(self): def test_flaskext_new_package_import_normal(self):
from flask.ext.newext_package import ext_id from flask.ext.newext_package import ext_id
self.assert_equal(ext_id, 'newext_package') assert ext_id == 'newext_package'
def test_flaskext_new_package_import_module(self): def test_flaskext_new_package_import_module(self):
from flask.ext import newext_package from flask.ext import newext_package
self.assert_equal(newext_package.ext_id, 'newext_package') assert newext_package.ext_id == 'newext_package'
self.assert_equal(newext_package.__name__, 'flask_newext_package') assert newext_package.__name__ == 'flask_newext_package'
def test_flaskext_new_package_import_submodule_function(self): def test_flaskext_new_package_import_submodule_function(self):
from flask.ext.newext_package.submodule import test_function from flask.ext.newext_package.submodule import test_function
self.assert_equal(test_function(), 42) assert test_function() == 42
def test_flaskext_new_package_import_submodule(self): def test_flaskext_new_package_import_submodule(self):
from flask.ext.newext_package import submodule from flask.ext.newext_package import submodule
self.assert_equal(submodule.__name__, 'flask_newext_package.submodule') assert submodule.__name__ == 'flask_newext_package.submodule'
self.assert_equal(submodule.test_function(), 42) assert submodule.test_function() == 42
def test_flaskext_old_simple_import_normal(self): def test_flaskext_old_simple_import_normal(self):
from flask.ext.oldext_simple import ext_id from flask.ext.oldext_simple import ext_id
self.assert_equal(ext_id, 'oldext_simple') assert ext_id == 'oldext_simple'
def test_flaskext_old_simple_import_module(self): def test_flaskext_old_simple_import_module(self):
from flask.ext import oldext_simple from flask.ext import oldext_simple
self.assert_equal(oldext_simple.ext_id, 'oldext_simple') assert oldext_simple.ext_id == 'oldext_simple'
self.assert_equal(oldext_simple.__name__, 'flaskext.oldext_simple') assert oldext_simple.__name__ == 'flaskext.oldext_simple'
def test_flaskext_old_package_import_normal(self): def test_flaskext_old_package_import_normal(self):
from flask.ext.oldext_package import ext_id from flask.ext.oldext_package import ext_id
self.assert_equal(ext_id, 'oldext_package') assert ext_id == 'oldext_package'
def test_flaskext_old_package_import_module(self): def test_flaskext_old_package_import_module(self):
from flask.ext import oldext_package from flask.ext import oldext_package
self.assert_equal(oldext_package.ext_id, 'oldext_package') assert oldext_package.ext_id == 'oldext_package'
self.assert_equal(oldext_package.__name__, 'flaskext.oldext_package') assert oldext_package.__name__ == 'flaskext.oldext_package'
def test_flaskext_old_package_import_submodule(self): def test_flaskext_old_package_import_submodule(self):
from flask.ext.oldext_package import submodule from flask.ext.oldext_package import submodule
self.assert_equal(submodule.__name__, 'flaskext.oldext_package.submodule') assert submodule.__name__ == 'flaskext.oldext_package.submodule'
self.assert_equal(submodule.test_function(), 42) assert submodule.test_function() == 42
def test_flaskext_old_package_import_submodule_function(self): def test_flaskext_old_package_import_submodule_function(self):
from flask.ext.oldext_package.submodule import test_function from flask.ext.oldext_package.submodule import test_function
self.assert_equal(test_function(), 42) assert test_function() == 42
def test_flaskext_broken_package_no_module_caching(self): def test_flaskext_broken_package_no_module_caching(self):
for x in range(2): for x in range(2):
with self.assert_raises(ImportError): with pytest.raises(ImportError):
import flask.ext.broken import flask.ext.broken
def test_no_error_swallowing(self): def test_no_error_swallowing(self):
@ -112,13 +114,13 @@ class TestExtImportHook(TestFlask):
import flask.ext.broken import flask.ext.broken
except ImportError: except ImportError:
exc_type, exc_value, tb = sys.exc_info() exc_type, exc_value, tb = sys.exc_info()
self.assert_true(exc_type is ImportError) assert exc_type is ImportError
if PY2: if PY2:
message = 'No module named missing_module' message = 'No module named missing_module'
else: else:
message = 'No module named \'missing_module\'' message = 'No module named \'missing_module\''
self.assert_equal(str(exc_value), message) assert str(exc_value) == message
self.assert_true(tb.tb_frame.f_globals is globals()) assert tb.tb_frame.f_globals is globals()
# reraise() adds a second frame so we need to skip that one too. # reraise() adds a second frame so we need to skip that one too.
# On PY3 we even have another one :( # On PY3 we even have another one :(
@ -127,7 +129,8 @@ class TestExtImportHook(TestFlask):
next = next.tb_next next = next.tb_next
import os.path import os.path
self.assert_in(os.path.join('flask_broken', '__init__.py'), next.tb_frame.f_code.co_filename) assert os.path.join('flask_broken', '__init__.py') in \
next.tb_frame.f_code.co_filename
def suite(): def suite():

194
tests/test_helpers.py

@ -9,6 +9,8 @@
:license: BSD, see LICENSE for more details. :license: BSD, see LICENSE for more details.
""" """
import pytest
import os import os
import flask import flask
import unittest import unittest
@ -36,7 +38,7 @@ class TestJSON(TestFlask):
return flask.jsonify(foo=text_type(flask.request.get_json())) return flask.jsonify(foo=text_type(flask.request.get_json()))
c = app.test_client() c = app.test_client()
rv = c.post('/json', data='malformed', content_type='application/json') rv = c.post('/json', data='malformed', content_type='application/json')
self.assert_equal(rv.status_code, 400) assert rv.status_code == 400
def test_json_custom_mimetypes(self): def test_json_custom_mimetypes(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -45,7 +47,7 @@ class TestJSON(TestFlask):
return flask.request.get_json() return flask.request.get_json()
c = app.test_client() c = app.test_client()
rv = c.post('/json', data='"foo"', content_type='application/x+json') rv = c.post('/json', data='"foo"', content_type='application/x+json')
self.assert_equal(rv.data, b'foo') assert rv.data == b'foo'
def test_json_body_encoding(self): def test_json_body_encoding(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -57,7 +59,7 @@ class TestJSON(TestFlask):
c = app.test_client() c = app.test_client()
resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'), resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),
content_type='application/json; charset=iso-8859-15') content_type='application/json; charset=iso-8859-15')
self.assert_equal(resp.data, u'Hällo Wörld'.encode('utf-8')) assert resp.data == u'Hällo Wörld'.encode('utf-8')
def test_jsonify(self): def test_jsonify(self):
d = dict(a=23, b=42, c=[1, 2, 3]) d = dict(a=23, b=42, c=[1, 2, 3])
@ -71,8 +73,8 @@ class TestJSON(TestFlask):
c = app.test_client() c = app.test_client()
for url in '/kw', '/dict': for url in '/kw', '/dict':
rv = c.get(url) rv = c.get(url)
self.assert_equal(rv.mimetype, 'application/json') assert rv.mimetype == 'application/json'
self.assert_equal(flask.json.loads(rv.data), d) assert flask.json.loads(rv.data) == d
def test_json_as_unicode(self): def test_json_as_unicode(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -80,12 +82,12 @@ class TestJSON(TestFlask):
app.config['JSON_AS_ASCII'] = True app.config['JSON_AS_ASCII'] = True
with app.app_context(): with app.app_context():
rv = flask.json.dumps(u'\N{SNOWMAN}') rv = flask.json.dumps(u'\N{SNOWMAN}')
self.assert_equal(rv, '"\\u2603"') assert rv == '"\\u2603"'
app.config['JSON_AS_ASCII'] = False app.config['JSON_AS_ASCII'] = False
with app.app_context(): with app.app_context():
rv = flask.json.dumps(u'\N{SNOWMAN}') rv = flask.json.dumps(u'\N{SNOWMAN}')
self.assert_equal(rv, u'"\u2603"') assert rv == u'"\u2603"'
def test_json_attr(self): def test_json_attr(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -96,29 +98,28 @@ class TestJSON(TestFlask):
c = app.test_client() c = app.test_client()
rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}), rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),
content_type='application/json') content_type='application/json')
self.assert_equal(rv.data, b'3') assert rv.data == b'3'
def test_template_escaping(self): def test_template_escaping(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
render = flask.render_template_string render = flask.render_template_string
with app.test_request_context(): with app.test_request_context():
rv = flask.json.htmlsafe_dumps('</script>') rv = flask.json.htmlsafe_dumps('</script>')
self.assert_equal(rv, u'"\\u003c/script\\u003e"') assert rv == u'"\\u003c/script\\u003e"'
self.assert_equal(type(rv), text_type) assert type(rv) == text_type
rv = render('{{ "</script>"|tojson }}') rv = render('{{ "</script>"|tojson }}')
self.assert_equal(rv, '"\\u003c/script\\u003e"') assert rv == '"\\u003c/script\\u003e"'
rv = render('{{ "<\0/script>"|tojson }}') rv = render('{{ "<\0/script>"|tojson }}')
self.assert_equal(rv, '"\\u003c\\u0000/script\\u003e"') assert rv == '"\\u003c\\u0000/script\\u003e"'
rv = render('{{ "<!--<script>"|tojson }}') rv = render('{{ "<!--<script>"|tojson }}')
self.assert_equal(rv, '"\\u003c!--\\u003cscript\\u003e"') assert rv == '"\\u003c!--\\u003cscript\\u003e"'
rv = render('{{ "&"|tojson }}') rv = render('{{ "&"|tojson }}')
self.assert_equal(rv, '"\\u0026"') assert rv == '"\\u0026"'
rv = render('{{ "\'"|tojson }}') rv = render('{{ "\'"|tojson }}')
self.assert_equal(rv, '"\\u0027"') assert rv == '"\\u0027"'
rv = render("<a ng-data='{{ data|tojson }}'></a>", rv = render("<a ng-data='{{ data|tojson }}'></a>",
data={'x': ["foo", "bar", "baz'"]}) data={'x': ["foo", "bar", "baz'"]})
self.assert_equal(rv, assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'
'<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>')
def test_json_customization(self): def test_json_customization(self):
class X(object): class X(object):
@ -148,7 +149,7 @@ class TestJSON(TestFlask):
rv = c.post('/', data=flask.json.dumps({ rv = c.post('/', data=flask.json.dumps({
'x': {'_foo': 42} 'x': {'_foo': 42}
}), content_type='application/json') }), content_type='application/json')
self.assert_equal(rv.data, b'"<42>"') assert rv.data == b'"<42>"'
def test_modified_url_encoding(self): def test_modified_url_encoding(self):
class ModifiedRequest(flask.Request): class ModifiedRequest(flask.Request):
@ -163,8 +164,8 @@ class TestJSON(TestFlask):
return flask.request.args['foo'] return flask.request.args['foo']
rv = app.test_client().get(u'/?foo=정상처리'.encode('euc-kr')) rv = app.test_client().get(u'/?foo=정상처리'.encode('euc-kr'))
self.assert_equal(rv.status_code, 200) assert rv.status_code == 200
self.assert_equal(rv.data, u'정상처리'.encode('utf-8')) assert rv.data == u'정상처리'.encode('utf-8')
if not has_encoding('euc-kr'): if not has_encoding('euc-kr'):
test_modified_url_encoding = None test_modified_url_encoding = None
@ -172,7 +173,7 @@ class TestJSON(TestFlask):
def test_json_key_sorting(self): def test_json_key_sorting(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.testing = True app.testing = True
self.assert_equal(app.config['JSON_SORT_KEYS'], True) assert app.config['JSON_SORT_KEYS'] == True
d = dict.fromkeys(range(20), 'foo') d = dict.fromkeys(range(20), 'foo')
@app.route('/') @app.route('/')
@ -236,9 +237,9 @@ class TestJSON(TestFlask):
] ]
try: try:
self.assert_equal(lines, sorted_by_int) assert lines == sorted_by_int
except AssertionError: except AssertionError:
self.assert_equal(lines, sorted_by_str) assert lines == sorted_by_str
class TestSendfile(TestFlask): class TestSendfile(TestFlask):
@ -246,11 +247,11 @@ class TestSendfile(TestFlask):
app = flask.Flask(__name__) app = flask.Flask(__name__)
with app.test_request_context(): with app.test_request_context():
rv = flask.send_file('static/index.html') rv = flask.send_file('static/index.html')
self.assert_true(rv.direct_passthrough) assert rv.direct_passthrough
self.assert_equal(rv.mimetype, 'text/html') assert rv.mimetype == 'text/html'
with app.open_resource('static/index.html') as f: with app.open_resource('static/index.html') as f:
rv.direct_passthrough = False rv.direct_passthrough = False
self.assert_equal(rv.data, f.read()) assert rv.data == f.read()
rv.close() rv.close()
def test_send_file_xsendfile(self): def test_send_file_xsendfile(self):
@ -258,11 +259,11 @@ class TestSendfile(TestFlask):
app.use_x_sendfile = True app.use_x_sendfile = True
with app.test_request_context(): with app.test_request_context():
rv = flask.send_file('static/index.html') rv = flask.send_file('static/index.html')
self.assert_true(rv.direct_passthrough) assert rv.direct_passthrough
self.assert_in('x-sendfile', rv.headers) assert 'x-sendfile' in rv.headers
self.assert_equal(rv.headers['x-sendfile'], assert rv.headers['x-sendfile'] == \
os.path.join(app.root_path, 'static/index.html')) os.path.join(app.root_path, 'static/index.html')
self.assert_equal(rv.mimetype, 'text/html') assert rv.mimetype == 'text/html'
rv.close() rv.close()
def test_send_file_object(self): def test_send_file_object(self):
@ -273,24 +274,24 @@ class TestSendfile(TestFlask):
rv = flask.send_file(f) rv = flask.send_file(f)
rv.direct_passthrough = False rv.direct_passthrough = False
with app.open_resource('static/index.html') as f: with app.open_resource('static/index.html') as f:
self.assert_equal(rv.data, f.read()) assert rv.data == f.read()
self.assert_equal(rv.mimetype, 'text/html') assert rv.mimetype == 'text/html'
rv.close() rv.close()
# mimetypes + etag # mimetypes + etag
self.assert_equal(len(captured), 2) assert len(captured) == 2
app.use_x_sendfile = True app.use_x_sendfile = True
with catch_warnings() as captured: with catch_warnings() as captured:
with app.test_request_context(): with app.test_request_context():
f = open(os.path.join(app.root_path, 'static/index.html')) f = open(os.path.join(app.root_path, 'static/index.html'))
rv = flask.send_file(f) rv = flask.send_file(f)
self.assert_equal(rv.mimetype, 'text/html') assert rv.mimetype == 'text/html'
self.assert_in('x-sendfile', rv.headers) assert 'x-sendfile' in rv.headers
self.assert_equal(rv.headers['x-sendfile'], assert rv.headers['x-sendfile'] == \
os.path.join(app.root_path, 'static/index.html')) os.path.join(app.root_path, 'static/index.html')
rv.close() rv.close()
# mimetypes + etag # mimetypes + etag
self.assert_equal(len(captured), 2) assert len(captured) == 2
app.use_x_sendfile = False app.use_x_sendfile = False
with app.test_request_context(): with app.test_request_context():
@ -298,11 +299,11 @@ class TestSendfile(TestFlask):
f = StringIO('Test') f = StringIO('Test')
rv = flask.send_file(f) rv = flask.send_file(f)
rv.direct_passthrough = False rv.direct_passthrough = False
self.assert_equal(rv.data, b'Test') assert rv.data == b'Test'
self.assert_equal(rv.mimetype, 'application/octet-stream') assert rv.mimetype == 'application/octet-stream'
rv.close() rv.close()
# etags # etags
self.assert_equal(len(captured), 1) assert len(captured) == 1
with catch_warnings() as captured: with catch_warnings() as captured:
class PyStringIO(object): class PyStringIO(object):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
@ -313,30 +314,30 @@ class TestSendfile(TestFlask):
f.name = 'test.txt' f.name = 'test.txt'
rv = flask.send_file(f) rv = flask.send_file(f)
rv.direct_passthrough = False rv.direct_passthrough = False
self.assert_equal(rv.data, b'Test') assert rv.data == b'Test'
self.assert_equal(rv.mimetype, 'text/plain') assert rv.mimetype == 'text/plain'
rv.close() rv.close()
# attachment_filename and etags # attachment_filename and etags
self.assert_equal(len(captured), 3) assert len(captured) == 3
with catch_warnings() as captured: with catch_warnings() as captured:
f = StringIO('Test') f = StringIO('Test')
rv = flask.send_file(f, mimetype='text/plain') rv = flask.send_file(f, mimetype='text/plain')
rv.direct_passthrough = False rv.direct_passthrough = False
self.assert_equal(rv.data, b'Test') assert rv.data == b'Test'
self.assert_equal(rv.mimetype, 'text/plain') assert rv.mimetype == 'text/plain'
rv.close() rv.close()
# etags # etags
self.assert_equal(len(captured), 1) assert len(captured) == 1
app.use_x_sendfile = True app.use_x_sendfile = True
with catch_warnings() as captured: with catch_warnings() as captured:
with app.test_request_context(): with app.test_request_context():
f = StringIO('Test') f = StringIO('Test')
rv = flask.send_file(f) rv = flask.send_file(f)
self.assert_not_in('x-sendfile', rv.headers) assert 'x-sendfile' not in rv.headers
rv.close() rv.close()
# etags # etags
self.assert_equal(len(captured), 1) assert len(captured) == 1
def test_attachment(self): def test_attachment(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -345,27 +346,27 @@ class TestSendfile(TestFlask):
f = open(os.path.join(app.root_path, 'static/index.html')) f = open(os.path.join(app.root_path, 'static/index.html'))
rv = flask.send_file(f, as_attachment=True) rv = flask.send_file(f, as_attachment=True)
value, options = parse_options_header(rv.headers['Content-Disposition']) value, options = parse_options_header(rv.headers['Content-Disposition'])
self.assert_equal(value, 'attachment') assert value == 'attachment'
rv.close() rv.close()
# mimetypes + etag # mimetypes + etag
self.assert_equal(len(captured), 2) assert len(captured) == 2
with app.test_request_context(): with app.test_request_context():
self.assert_equal(options['filename'], 'index.html') assert options['filename'] == 'index.html'
rv = flask.send_file('static/index.html', as_attachment=True) rv = flask.send_file('static/index.html', as_attachment=True)
value, options = parse_options_header(rv.headers['Content-Disposition']) value, options = parse_options_header(rv.headers['Content-Disposition'])
self.assert_equal(value, 'attachment') assert value == 'attachment'
self.assert_equal(options['filename'], 'index.html') assert options['filename'] == 'index.html'
rv.close() rv.close()
with app.test_request_context(): with app.test_request_context():
rv = flask.send_file(StringIO('Test'), as_attachment=True, rv = flask.send_file(StringIO('Test'), as_attachment=True,
attachment_filename='index.txt', attachment_filename='index.txt',
add_etags=False) add_etags=False)
self.assert_equal(rv.mimetype, 'text/plain') assert rv.mimetype == 'text/plain'
value, options = parse_options_header(rv.headers['Content-Disposition']) value, options = parse_options_header(rv.headers['Content-Disposition'])
self.assert_equal(value, 'attachment') assert value == 'attachment'
self.assert_equal(options['filename'], 'index.txt') assert options['filename'] == 'index.txt'
rv.close() rv.close()
def test_static_file(self): def test_static_file(self):
@ -375,24 +376,24 @@ class TestSendfile(TestFlask):
# Test with static file handler. # Test with static file handler.
rv = app.send_static_file('index.html') rv = app.send_static_file('index.html')
cc = parse_cache_control_header(rv.headers['Cache-Control']) cc = parse_cache_control_header(rv.headers['Cache-Control'])
self.assert_equal(cc.max_age, 12 * 60 * 60) assert cc.max_age == 12 * 60 * 60
rv.close() rv.close()
# Test again with direct use of send_file utility. # Test again with direct use of send_file utility.
rv = flask.send_file('static/index.html') rv = flask.send_file('static/index.html')
cc = parse_cache_control_header(rv.headers['Cache-Control']) cc = parse_cache_control_header(rv.headers['Cache-Control'])
self.assert_equal(cc.max_age, 12 * 60 * 60) assert cc.max_age == 12 * 60 * 60
rv.close() rv.close()
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600
with app.test_request_context(): with app.test_request_context():
# Test with static file handler. # Test with static file handler.
rv = app.send_static_file('index.html') rv = app.send_static_file('index.html')
cc = parse_cache_control_header(rv.headers['Cache-Control']) cc = parse_cache_control_header(rv.headers['Cache-Control'])
self.assert_equal(cc.max_age, 3600) assert cc.max_age == 3600
rv.close() rv.close()
# Test again with direct use of send_file utility. # Test again with direct use of send_file utility.
rv = flask.send_file('static/index.html') rv = flask.send_file('static/index.html')
cc = parse_cache_control_header(rv.headers['Cache-Control']) cc = parse_cache_control_header(rv.headers['Cache-Control'])
self.assert_equal(cc.max_age, 3600) assert cc.max_age == 3600
rv.close() rv.close()
class StaticFileApp(flask.Flask): class StaticFileApp(flask.Flask):
def get_send_file_max_age(self, filename): def get_send_file_max_age(self, filename):
@ -402,12 +403,12 @@ class TestSendfile(TestFlask):
# Test with static file handler. # Test with static file handler.
rv = app.send_static_file('index.html') rv = app.send_static_file('index.html')
cc = parse_cache_control_header(rv.headers['Cache-Control']) cc = parse_cache_control_header(rv.headers['Cache-Control'])
self.assert_equal(cc.max_age, 10) assert cc.max_age == 10
rv.close() rv.close()
# Test again with direct use of send_file utility. # Test again with direct use of send_file utility.
rv = flask.send_file('static/index.html') rv = flask.send_file('static/index.html')
cc = parse_cache_control_header(rv.headers['Cache-Control']) cc = parse_cache_control_header(rv.headers['Cache-Control'])
self.assert_equal(cc.max_age, 10) assert cc.max_age == 10
rv.close() rv.close()
def test_send_from_directory(self): def test_send_from_directory(self):
@ -418,7 +419,7 @@ class TestSendfile(TestFlask):
with app.test_request_context(): with app.test_request_context():
rv = flask.send_from_directory('static', 'hello.txt') rv = flask.send_from_directory('static', 'hello.txt')
rv.direct_passthrough = False rv.direct_passthrough = False
self.assert_equal(rv.data.strip(), b'Hello Subdomain') assert rv.data.strip() == b'Hello Subdomain'
rv.close() rv.close()
@ -427,10 +428,10 @@ class TestLogging(TestFlask):
def test_logger_cache(self): def test_logger_cache(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
logger1 = app.logger logger1 = app.logger
self.assert_true(app.logger is logger1) assert app.logger is logger1
self.assert_equal(logger1.name, __name__) assert logger1.name == __name__
app.logger_name = __name__ + '/test_logger_cache' app.logger_name = __name__ + '/test_logger_cache'
self.assert_true(app.logger is not logger1) assert app.logger is not logger1
def test_debug_log(self): def test_debug_log(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -450,10 +451,10 @@ class TestLogging(TestFlask):
with catch_stderr() as err: with catch_stderr() as err:
c.get('/') c.get('/')
out = err.getvalue() out = err.getvalue()
self.assert_in('WARNING in test_helpers [', out) assert 'WARNING in test_helpers [' in out
self.assert_in(os.path.basename(__file__.rsplit('.', 1)[0] + '.py'), out) assert os.path.basename(__file__.rsplit('.', 1)[0] + '.py') in out
self.assert_in('the standard library is dead', out) assert 'the standard library is dead' in out
self.assert_in('this is a debug statement', out) assert 'this is a debug statement' in out
with catch_stderr() as err: with catch_stderr() as err:
try: try:
@ -461,14 +462,14 @@ class TestLogging(TestFlask):
except ZeroDivisionError: except ZeroDivisionError:
pass pass
else: else:
self.assert_true(False, 'debug log ate the exception') assert False, 'debug log ate the exception'
def test_debug_log_override(self): def test_debug_log_override(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.debug = True app.debug = True
app.logger_name = 'flask_tests/test_debug_log_override' app.logger_name = 'flask_tests/test_debug_log_override'
app.logger.level = 10 app.logger.level = 10
self.assert_equal(app.logger.level, 10) assert app.logger.level == 10
def test_exception_logging(self): def test_exception_logging(self):
out = StringIO() out = StringIO()
@ -482,14 +483,14 @@ class TestLogging(TestFlask):
1 // 0 1 // 0
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_equal(rv.status_code, 500) assert rv.status_code == 500
self.assert_in(b'Internal Server Error', rv.data) assert b'Internal Server Error' in rv.data
err = out.getvalue() err = out.getvalue()
self.assert_in('Exception on / [GET]', err) assert 'Exception on / [GET]' in err
self.assert_in('Traceback (most recent call last):', err) assert 'Traceback (most recent call last):' in err
self.assert_in('1 // 0', err) assert '1 // 0' in err
self.assert_in('ZeroDivisionError:', err) assert 'ZeroDivisionError:' in err
def test_processor_exceptions(self): def test_processor_exceptions(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -511,8 +512,8 @@ class TestLogging(TestFlask):
return 'Hello Server Error', 500 return 'Hello Server Error', 500
for trigger in 'before', 'after': for trigger in 'before', 'after':
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_equal(rv.status_code, 500) assert rv.status_code == 500
self.assert_equal(rv.data, b'Hello Server Error') assert rv.data == b'Hello Server Error'
def test_url_for_with_anchor(self): def test_url_for_with_anchor(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -520,8 +521,7 @@ class TestLogging(TestFlask):
def index(): def index():
return '42' return '42'
with app.test_request_context(): with app.test_request_context():
self.assert_equal(flask.url_for('index', _anchor='x y'), assert flask.url_for('index', _anchor='x y') == '/#x%20y'
'/#x%20y')
def test_url_for_with_scheme(self): def test_url_for_with_scheme(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -529,10 +529,7 @@ class TestLogging(TestFlask):
def index(): def index():
return '42' return '42'
with app.test_request_context(): with app.test_request_context():
self.assert_equal(flask.url_for('index', assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'
_external=True,
_scheme='https'),
'https://localhost/')
def test_url_for_with_scheme_not_external(self): def test_url_for_with_scheme_not_external(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -540,7 +537,7 @@ class TestLogging(TestFlask):
def index(): def index():
return '42' return '42'
with app.test_request_context(): with app.test_request_context():
self.assert_raises(ValueError, pytest.raises(ValueError,
flask.url_for, flask.url_for,
'index', 'index',
_scheme='https') _scheme='https')
@ -564,12 +561,9 @@ class TestLogging(TestFlask):
view_func=myview) view_func=myview)
with app.test_request_context(): with app.test_request_context():
self.assert_equal(flask.url_for('myview', _method='GET'), assert flask.url_for('myview', _method='GET') == '/myview/'
'/myview/') assert flask.url_for('myview', id=42, _method='GET') == '/myview/42'
self.assert_equal(flask.url_for('myview', id=42, _method='GET'), assert flask.url_for('myview', _method='POST') == '/myview/create'
'/myview/42')
self.assert_equal(flask.url_for('myview', _method='POST'),
'/myview/create')
class TestNoImports(TestFlask): class TestNoImports(TestFlask):
@ -587,7 +581,7 @@ class TestNoImports(TestFlask):
try: try:
flask.Flask('importerror') flask.Flask('importerror')
except NotImplementedError: except NotImplementedError:
self.fail('Flask(import_name) is importing import_name.') assert False, 'Flask(import_name) is importing import_name.'
class TestStreaming(TestFlask): class TestStreaming(TestFlask):
@ -604,7 +598,7 @@ class TestStreaming(TestFlask):
return flask.Response(flask.stream_with_context(generate())) return flask.Response(flask.stream_with_context(generate()))
c = app.test_client() c = app.test_client()
rv = c.get('/?name=World') rv = c.get('/?name=World')
self.assert_equal(rv.data, b'Hello World!') assert rv.data == b'Hello World!'
def test_streaming_with_context_as_decorator(self): def test_streaming_with_context_as_decorator(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -619,7 +613,7 @@ class TestStreaming(TestFlask):
return flask.Response(generate()) return flask.Response(generate())
c = app.test_client() c = app.test_client()
rv = c.get('/?name=World') rv = c.get('/?name=World')
self.assert_equal(rv.data, b'Hello World!') assert rv.data == b'Hello World!'
def test_streaming_with_context_and_custom_close(self): def test_streaming_with_context_and_custom_close(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -645,8 +639,8 @@ class TestStreaming(TestFlask):
Wrapper(generate()))) Wrapper(generate())))
c = app.test_client() c = app.test_client()
rv = c.get('/?name=World') rv = c.get('/?name=World')
self.assert_equal(rv.data, b'Hello World!') assert rv.data == b'Hello World!'
self.assert_equal(called, [42]) assert called == [42]
def suite(): def suite():

10
tests/test_regression.py

@ -69,8 +69,8 @@ class TestMemory(TestFlask):
def fire(): def fire():
with app.test_client() as c: with app.test_client() as c:
rv = c.get('/') rv = c.get('/')
self.assert_equal(rv.status_code, 200) assert rv.status_code == 200
self.assert_equal(rv.data, b'<h1>42</h1>') assert rv.data == b'<h1>42</h1>'
# Trigger caches # Trigger caches
fire() fire()
@ -84,7 +84,7 @@ class TestMemory(TestFlask):
def test_safe_join_toplevel_pardir(self): def test_safe_join_toplevel_pardir(self):
from flask.helpers import safe_join from flask.helpers import safe_join
with self.assert_raises(NotFound): with pytest.raises(NotFound):
safe_join('/foo', '..') safe_join('/foo', '..')
@ -110,6 +110,6 @@ class TestException(TestFlask):
with app.test_client() as c: with app.test_client() as c:
rv = c.get('/') rv = c.get('/')
self.assert_equal(rv.headers['Location'], 'http://localhost/test') assert rv.headers['Location'] == 'http://localhost/test'
rv = c.get('/test') rv = c.get('/test')
self.assert_equal(rv.data, b'42') assert rv.data == b'42'

95
tests/test_reqctx.py

@ -9,6 +9,8 @@
:license: BSD, see LICENSE for more details. :license: BSD, see LICENSE for more details.
""" """
import pytest
import flask import flask
import unittest import unittest
try: try:
@ -29,9 +31,9 @@ class TestRequestContext(TestFlask):
ctx = app.test_request_context() ctx = app.test_request_context()
ctx.push() ctx.push()
self.assert_equal(buffer, []) assert buffer == []
ctx.pop() ctx.pop()
self.assert_equal(buffer, [None]) assert buffer == [None]
def test_teardown_with_previous_exception(self): def test_teardown_with_previous_exception(self):
buffer = [] buffer = []
@ -46,8 +48,8 @@ class TestRequestContext(TestFlask):
pass pass
with app.test_request_context(): with app.test_request_context():
self.assert_equal(buffer, []) assert buffer == []
self.assert_equal(buffer, [None]) assert buffer == [None]
def test_proper_test_request_context(self): def test_proper_test_request_context(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -64,37 +66,30 @@ class TestRequestContext(TestFlask):
return None return None
with app.test_request_context('/'): with app.test_request_context('/'):
self.assert_equal(flask.url_for('index', _external=True), 'http://localhost.localdomain:5000/') assert flask.url_for('index', _external=True) == \
'http://localhost.localdomain:5000/'
with app.test_request_context('/'): with app.test_request_context('/'):
self.assert_equal(flask.url_for('sub', _external=True), 'http://foo.localhost.localdomain:5000/') assert flask.url_for('sub', _external=True) == \
'http://foo.localhost.localdomain:5000/'
try: try:
with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}): with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}):
pass pass
except Exception as e:
self.assert_true(isinstance(e, ValueError))
self.assert_equal(str(e), "the server name provided " +
"('localhost.localdomain:5000') does not match the " + \
"server name from the WSGI environment ('localhost')")
try:
app.config.update(SERVER_NAME='localhost')
with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}):
pass
except ValueError as e: except ValueError as e:
raise ValueError( assert str(e) == (
"No ValueError exception should have been raised \"%s\"" % e "the server name provided "
"('localhost.localdomain:5000') does not match the "
"server name from the WSGI environment ('localhost')"
) )
try: app.config.update(SERVER_NAME='localhost')
app.config.update(SERVER_NAME='localhost:80') with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}):
with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}): pass
pass
except ValueError as e: app.config.update(SERVER_NAME='localhost:80')
raise ValueError( with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}):
"No ValueError exception should have been raised \"%s\"" % e pass
)
def test_context_binding(self): def test_context_binding(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -106,20 +101,20 @@ class TestRequestContext(TestFlask):
return flask.request.url return flask.request.url
with app.test_request_context('/?name=World'): with app.test_request_context('/?name=World'):
self.assert_equal(index(), 'Hello World!') assert index() == 'Hello World!'
with app.test_request_context('/meh'): with app.test_request_context('/meh'):
self.assert_equal(meh(), 'http://localhost/meh') assert meh() == 'http://localhost/meh'
self.assert_true(flask._request_ctx_stack.top is None) assert flask._request_ctx_stack.top is None
def test_context_test(self): def test_context_test(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
self.assert_false(flask.request) assert not flask.request
self.assert_false(flask.has_request_context()) assert not flask.has_request_context()
ctx = app.test_request_context() ctx = app.test_request_context()
ctx.push() ctx.push()
try: try:
self.assert_true(flask.request) assert flask.request
self.assert_true(flask.has_request_context()) assert flask.has_request_context()
finally: finally:
ctx.pop() ctx.pop()
@ -131,14 +126,14 @@ class TestRequestContext(TestFlask):
ctx = app.test_request_context('/?name=World') ctx = app.test_request_context('/?name=World')
ctx.push() ctx.push()
self.assert_equal(index(), 'Hello World!') assert index() == 'Hello World!'
ctx.pop() ctx.pop()
try: try:
index() index()
except RuntimeError: except RuntimeError:
pass pass
else: else:
self.assert_true(0, 'expected runtime error') assert 0, 'expected runtime error'
def test_greenlet_context_copying(self): def test_greenlet_context_copying(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -148,23 +143,23 @@ class TestRequestContext(TestFlask):
def index(): def index():
reqctx = flask._request_ctx_stack.top.copy() reqctx = flask._request_ctx_stack.top.copy()
def g(): def g():
self.assert_false(flask.request) assert not flask.request
self.assert_false(flask.current_app) assert not flask.current_app
with reqctx: with reqctx:
self.assert_true(flask.request) assert flask.request
self.assert_equal(flask.current_app, app) assert flask.current_app == app
self.assert_equal(flask.request.path, '/') assert flask.request.path == '/'
self.assert_equal(flask.request.args['foo'], 'bar') assert flask.request.args['foo'] == 'bar'
self.assert_false(flask.request) assert not flask.request
return 42 return 42
greenlets.append(greenlet(g)) greenlets.append(greenlet(g))
return 'Hello World!' return 'Hello World!'
rv = app.test_client().get('/?foo=bar') rv = app.test_client().get('/?foo=bar')
self.assert_equal(rv.data, b'Hello World!') assert rv.data == b'Hello World!'
result = greenlets[0].run() result = greenlets[0].run()
self.assert_equal(result, 42) assert result == 42
def test_greenlet_context_copying_api(self): def test_greenlet_context_copying_api(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -175,19 +170,19 @@ class TestRequestContext(TestFlask):
reqctx = flask._request_ctx_stack.top.copy() reqctx = flask._request_ctx_stack.top.copy()
@flask.copy_current_request_context @flask.copy_current_request_context
def g(): def g():
self.assert_true(flask.request) assert flask.request
self.assert_equal(flask.current_app, app) assert flask.current_app == app
self.assert_equal(flask.request.path, '/') assert flask.request.path == '/'
self.assert_equal(flask.request.args['foo'], 'bar') assert flask.request.args['foo'] == 'bar'
return 42 return 42
greenlets.append(greenlet(g)) greenlets.append(greenlet(g))
return 'Hello World!' return 'Hello World!'
rv = app.test_client().get('/?foo=bar') rv = app.test_client().get('/?foo=bar')
self.assert_equal(rv.data, b'Hello World!') assert rv.data == b'Hello World!'
result = greenlets[0].run() result = greenlets[0].run()
self.assert_equal(result, 42) assert result == 42
# Disable test if we don't have greenlets available # Disable test if we don't have greenlets available
if greenlet is None: if greenlet is None:

33
tests/test_signals.py

@ -42,10 +42,10 @@ class TestSignals(TestFlask):
flask.template_rendered.connect(record, app) flask.template_rendered.connect(record, app)
try: try:
app.test_client().get('/') app.test_client().get('/')
self.assert_equal(len(recorded), 1) assert len(recorded) == 1
template, context = recorded[0] template, context = recorded[0]
self.assert_equal(template.name, 'simple_template.html') assert template.name == 'simple_template.html'
self.assert_equal(context['whiskey'], 42) assert context['whiskey'] == 42
finally: finally:
flask.template_rendered.disconnect(record, app) flask.template_rendered.disconnect(record, app)
@ -57,7 +57,7 @@ class TestSignals(TestFlask):
calls.append('before-signal') calls.append('before-signal')
def after_request_signal(sender, response): def after_request_signal(sender, response):
self.assert_equal(response.data, b'stuff') assert response.data == b'stuff'
calls.append('after-signal') calls.append('after-signal')
@app.before_request @app.before_request
@ -80,11 +80,10 @@ class TestSignals(TestFlask):
try: try:
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_equal(rv.data, b'stuff') assert rv.data == b'stuff'
self.assert_equal(calls, ['before-signal', 'before-handler', assert calls == ['before-signal', 'before-handler', 'handler',
'handler', 'after-handler', 'after-handler', 'after-signal']
'after-signal'])
finally: finally:
flask.request_started.disconnect(before_request_signal, app) flask.request_started.disconnect(before_request_signal, app)
flask.request_finished.disconnect(after_request_signal, app) flask.request_finished.disconnect(after_request_signal, app)
@ -102,9 +101,9 @@ class TestSignals(TestFlask):
flask.got_request_exception.connect(record, app) flask.got_request_exception.connect(record, app)
try: try:
self.assert_equal(app.test_client().get('/').status_code, 500) assert app.test_client().get('/').status_code == 500
self.assert_equal(len(recorded), 1) assert len(recorded) == 1
self.assert_true(isinstance(recorded[0], ZeroDivisionError)) assert isinstance(recorded[0], ZeroDivisionError)
finally: finally:
flask.got_request_exception.disconnect(record, app) flask.got_request_exception.disconnect(record, app)
@ -127,9 +126,9 @@ class TestSignals(TestFlask):
try: try:
with app.test_client() as c: with app.test_client() as c:
rv = c.get('/') rv = c.get('/')
self.assert_equal(rv.data, b'Hello') assert rv.data == b'Hello'
self.assert_equal(recorded, ['push']) assert recorded == ['push']
self.assert_equal(recorded, ['push', 'pop']) assert recorded == ['push', 'pop']
finally: finally:
flask.appcontext_pushed.disconnect(record_push, app) flask.appcontext_pushed.disconnect(record_push, app)
flask.appcontext_popped.disconnect(record_pop, app) flask.appcontext_popped.disconnect(record_pop, app)
@ -153,9 +152,9 @@ class TestSignals(TestFlask):
client = app.test_client() client = app.test_client()
with client.session_transaction(): with client.session_transaction():
client.get('/') client.get('/')
self.assert_equal(len(recorded), 1) assert len(recorded) == 1
message, category = recorded[0] message, category = recorded[0]
self.assert_equal(message, 'This is a flash message') assert message == 'This is a flash message'
self.assert_equal(category, 'notice') assert category == 'notice'
finally: finally:
flask.message_flashed.disconnect(record, app) flask.message_flashed.disconnect(record, app)

6
tests/test_subclassing.py

@ -33,11 +33,11 @@ class TestFlaskSubclassing(TestFlask):
1 // 0 1 // 0
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_equal(rv.status_code, 500) assert rv.status_code == 500
self.assert_in(b'Internal Server Error', rv.data) assert b'Internal Server Error' in rv.data
err = out.getvalue() err = out.getvalue()
self.assert_equal(err, '') assert err == ''
def suite(): def suite():

128
tests/test_templating.py

@ -28,7 +28,7 @@ class TestTemplating(TestFlask):
def index(): def index():
return flask.render_template('context_template.html', value=23) return flask.render_template('context_template.html', value=23)
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_equal(rv.data, b'<p>23|42') assert rv.data == b'<p>23|42'
def test_original_win(self): def test_original_win(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -36,7 +36,7 @@ class TestTemplating(TestFlask):
def index(): def index():
return flask.render_template_string('{{ config }}', config=42) return flask.render_template_string('{{ config }}', config=42)
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_equal(rv.data, b'42') assert rv.data == b'42'
def test_request_less_rendering(self): def test_request_less_rendering(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -48,7 +48,7 @@ class TestTemplating(TestFlask):
with app.app_context(): with app.app_context():
rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} ' rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} '
'{{ foo }}') '{{ foo }}')
self.assert_equal(rv, 'Hello Special World 42') assert rv == 'Hello Special World 42'
def test_standard_context(self): def test_standard_context(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -64,7 +64,7 @@ class TestTemplating(TestFlask):
{{ session.test }} {{ session.test }}
''') ''')
rv = app.test_client().get('/?foo=42') rv = app.test_client().get('/?foo=42')
self.assert_equal(rv.data.split(), [b'42', b'23', b'False', b'aha']) assert rv.data.split() == [b'42', b'23', b'False', b'aha']
def test_escaping(self): def test_escaping(self):
text = '<p>Hello World!' text = '<p>Hello World!'
@ -74,64 +74,64 @@ class TestTemplating(TestFlask):
return flask.render_template('escaping_template.html', text=text, return flask.render_template('escaping_template.html', text=text,
html=flask.Markup(text)) html=flask.Markup(text))
lines = app.test_client().get('/').data.splitlines() lines = app.test_client().get('/').data.splitlines()
self.assert_equal(lines, [ assert lines == [
b'&lt;p&gt;Hello World!', b'&lt;p&gt;Hello World!',
b'<p>Hello World!', b'<p>Hello World!',
b'<p>Hello World!', b'<p>Hello World!',
b'<p>Hello World!', b'<p>Hello World!',
b'&lt;p&gt;Hello World!', b'&lt;p&gt;Hello World!',
b'<p>Hello World!' b'<p>Hello World!'
]) ]
def test_no_escaping(self): def test_no_escaping(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
with app.test_request_context(): with app.test_request_context():
self.assert_equal(flask.render_template_string('{{ foo }}', assert flask.render_template_string(
foo='<test>'), '<test>') '{{ foo }}', foo='<test>') == '<test>'
self.assert_equal(flask.render_template('mail.txt', foo='<test>'), assert flask.render_template('mail.txt', foo='<test>') == \
'<test> Mail') '<test> Mail'
def test_macros(self): def test_macros(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
with app.test_request_context(): with app.test_request_context():
macro = flask.get_template_attribute('_macro.html', 'hello') macro = flask.get_template_attribute('_macro.html', 'hello')
self.assert_equal(macro('World'), 'Hello World!') assert macro('World') == 'Hello World!'
def test_template_filter(self): def test_template_filter(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@app.template_filter() @app.template_filter()
def my_reverse(s): def my_reverse(s):
return s[::-1] return s[::-1]
self.assert_in('my_reverse', app.jinja_env.filters.keys()) assert 'my_reverse' in app.jinja_env.filters.keys()
self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse) assert app.jinja_env.filters['my_reverse'] == my_reverse
self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba') assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'
def test_add_template_filter(self): def test_add_template_filter(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
def my_reverse(s): def my_reverse(s):
return s[::-1] return s[::-1]
app.add_template_filter(my_reverse) app.add_template_filter(my_reverse)
self.assert_in('my_reverse', app.jinja_env.filters.keys()) assert 'my_reverse' in app.jinja_env.filters.keys()
self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse) assert app.jinja_env.filters['my_reverse'] == my_reverse
self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba') assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'
def test_template_filter_with_name(self): def test_template_filter_with_name(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@app.template_filter('strrev') @app.template_filter('strrev')
def my_reverse(s): def my_reverse(s):
return s[::-1] return s[::-1]
self.assert_in('strrev', app.jinja_env.filters.keys()) assert 'strrev' in app.jinja_env.filters.keys()
self.assert_equal(app.jinja_env.filters['strrev'], my_reverse) assert app.jinja_env.filters['strrev'] == my_reverse
self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba') assert app.jinja_env.filters['strrev']('abcd') == 'dcba'
def test_add_template_filter_with_name(self): def test_add_template_filter_with_name(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
def my_reverse(s): def my_reverse(s):
return s[::-1] return s[::-1]
app.add_template_filter(my_reverse, 'strrev') app.add_template_filter(my_reverse, 'strrev')
self.assert_in('strrev', app.jinja_env.filters.keys()) assert 'strrev' in app.jinja_env.filters.keys()
self.assert_equal(app.jinja_env.filters['strrev'], my_reverse) assert app.jinja_env.filters['strrev'] == my_reverse
self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba') assert app.jinja_env.filters['strrev']('abcd') == 'dcba'
def test_template_filter_with_template(self): def test_template_filter_with_template(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -142,7 +142,7 @@ class TestTemplating(TestFlask):
def index(): def index():
return flask.render_template('template_filter.html', value='abcd') return flask.render_template('template_filter.html', value='abcd')
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_equal(rv.data, b'dcba') assert rv.data == b'dcba'
def test_add_template_filter_with_template(self): def test_add_template_filter_with_template(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -153,7 +153,7 @@ class TestTemplating(TestFlask):
def index(): def index():
return flask.render_template('template_filter.html', value='abcd') return flask.render_template('template_filter.html', value='abcd')
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_equal(rv.data, b'dcba') assert rv.data == b'dcba'
def test_template_filter_with_name_and_template(self): def test_template_filter_with_name_and_template(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -164,7 +164,7 @@ class TestTemplating(TestFlask):
def index(): def index():
return flask.render_template('template_filter.html', value='abcd') return flask.render_template('template_filter.html', value='abcd')
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_equal(rv.data, b'dcba') assert rv.data == b'dcba'
def test_add_template_filter_with_name_and_template(self): def test_add_template_filter_with_name_and_template(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -175,43 +175,43 @@ class TestTemplating(TestFlask):
def index(): def index():
return flask.render_template('template_filter.html', value='abcd') return flask.render_template('template_filter.html', value='abcd')
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_equal(rv.data, b'dcba') assert rv.data == b'dcba'
def test_template_test(self): def test_template_test(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@app.template_test() @app.template_test()
def boolean(value): def boolean(value):
return isinstance(value, bool) return isinstance(value, bool)
self.assert_in('boolean', app.jinja_env.tests.keys()) assert 'boolean' in app.jinja_env.tests.keys()
self.assert_equal(app.jinja_env.tests['boolean'], boolean) assert app.jinja_env.tests['boolean'] == boolean
self.assert_true(app.jinja_env.tests['boolean'](False)) assert app.jinja_env.tests['boolean'](False)
def test_add_template_test(self): def test_add_template_test(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
def boolean(value): def boolean(value):
return isinstance(value, bool) return isinstance(value, bool)
app.add_template_test(boolean) app.add_template_test(boolean)
self.assert_in('boolean', app.jinja_env.tests.keys()) assert 'boolean' in app.jinja_env.tests.keys()
self.assert_equal(app.jinja_env.tests['boolean'], boolean) assert app.jinja_env.tests['boolean'] == boolean
self.assert_true(app.jinja_env.tests['boolean'](False)) assert app.jinja_env.tests['boolean'](False)
def test_template_test_with_name(self): def test_template_test_with_name(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@app.template_test('boolean') @app.template_test('boolean')
def is_boolean(value): def is_boolean(value):
return isinstance(value, bool) return isinstance(value, bool)
self.assert_in('boolean', app.jinja_env.tests.keys()) assert 'boolean' in app.jinja_env.tests.keys()
self.assert_equal(app.jinja_env.tests['boolean'], is_boolean) assert app.jinja_env.tests['boolean'] == is_boolean
self.assert_true(app.jinja_env.tests['boolean'](False)) assert app.jinja_env.tests['boolean'](False)
def test_add_template_test_with_name(self): def test_add_template_test_with_name(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
def is_boolean(value): def is_boolean(value):
return isinstance(value, bool) return isinstance(value, bool)
app.add_template_test(is_boolean, 'boolean') app.add_template_test(is_boolean, 'boolean')
self.assert_in('boolean', app.jinja_env.tests.keys()) assert 'boolean' in app.jinja_env.tests.keys()
self.assert_equal(app.jinja_env.tests['boolean'], is_boolean) assert app.jinja_env.tests['boolean'] == is_boolean
self.assert_true(app.jinja_env.tests['boolean'](False)) assert app.jinja_env.tests['boolean'](False)
def test_template_test_with_template(self): def test_template_test_with_template(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -222,7 +222,7 @@ class TestTemplating(TestFlask):
def index(): def index():
return flask.render_template('template_test.html', value=False) return flask.render_template('template_test.html', value=False)
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_in(b'Success!', rv.data) assert b'Success!' in rv.data
def test_add_template_test_with_template(self): def test_add_template_test_with_template(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -233,7 +233,7 @@ class TestTemplating(TestFlask):
def index(): def index():
return flask.render_template('template_test.html', value=False) return flask.render_template('template_test.html', value=False)
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_in(b'Success!', rv.data) assert b'Success!' in rv.data
def test_template_test_with_name_and_template(self): def test_template_test_with_name_and_template(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -244,7 +244,7 @@ class TestTemplating(TestFlask):
def index(): def index():
return flask.render_template('template_test.html', value=False) return flask.render_template('template_test.html', value=False)
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_in(b'Success!', rv.data) assert b'Success!' in rv.data
def test_add_template_test_with_name_and_template(self): def test_add_template_test_with_name_and_template(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -255,19 +255,19 @@ class TestTemplating(TestFlask):
def index(): def index():
return flask.render_template('template_test.html', value=False) return flask.render_template('template_test.html', value=False)
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_in(b'Success!', rv.data) assert b'Success!' in rv.data
def test_add_template_global(self): def test_add_template_global(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@app.template_global() @app.template_global()
def get_stuff(): def get_stuff():
return 42 return 42
self.assert_in('get_stuff', app.jinja_env.globals.keys()) assert 'get_stuff' in app.jinja_env.globals.keys()
self.assert_equal(app.jinja_env.globals['get_stuff'], get_stuff) assert app.jinja_env.globals['get_stuff'] == get_stuff
self.assert_true(app.jinja_env.globals['get_stuff'](), 42) assert app.jinja_env.globals['get_stuff'](), 42
with app.app_context(): with app.app_context():
rv = flask.render_template_string('{{ get_stuff() }}') rv = flask.render_template_string('{{ get_stuff() }}')
self.assert_equal(rv, '42') assert rv == '42'
def test_custom_template_loader(self): def test_custom_template_loader(self):
class MyFlask(flask.Flask): class MyFlask(flask.Flask):
@ -280,7 +280,7 @@ class TestTemplating(TestFlask):
return flask.render_template('index.html') return flask.render_template('index.html')
c = app.test_client() c = app.test_client()
rv = c.get('/') rv = c.get('/')
self.assert_equal(rv.data, b'Hello Custom World!') assert rv.data == b'Hello Custom World!'
def test_iterable_loader(self): def test_iterable_loader(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -296,15 +296,15 @@ class TestTemplating(TestFlask):
value=23) value=23)
rv = app.test_client().get('/') rv = app.test_client().get('/')
self.assert_equal(rv.data, b'<h1>Jameson</h1>') assert rv.data == b'<h1>Jameson</h1>'
def test_templates_auto_reload(self): def test_templates_auto_reload(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
self.assert_true(app.config['TEMPLATES_AUTO_RELOAD']) assert app.config['TEMPLATES_AUTO_RELOAD']
self.assert_true(app.jinja_env.auto_reload) assert app.jinja_env.auto_reload
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = False app.config['TEMPLATES_AUTO_RELOAD'] = False
self.assert_false(app.jinja_env.auto_reload) assert not app.jinja_env.auto_reload
def test_template_loader_debugging(self): def test_template_loader_debugging(self):
from blueprintapp import app from blueprintapp import app
@ -314,17 +314,15 @@ class TestTemplating(TestFlask):
def handle(x, record): def handle(x, record):
called.append(True) called.append(True)
text = str(record.msg) text = str(record.msg)
self.assert_('1: trying loader of application ' assert '1: trying loader of application "blueprintapp"' in text
'"blueprintapp"' in text) assert ('2: trying loader of blueprint "admin" '
self.assert_('2: trying loader of blueprint "admin" ' '(blueprintapp.apps.admin)') in text
'(blueprintapp.apps.admin)' in text) assert ('trying loader of blueprint "frontend" '
self.assert_('trying loader of blueprint "frontend" ' '(blueprintapp.apps.frontend)') in text
'(blueprintapp.apps.frontend)' in text) assert 'Error: the template could not be found' in text
self.assert_('Error: the template could not be found' in text) assert ('looked up from an endpoint that belongs to '
self.assert_('looked up from an endpoint that belongs to ' 'the blueprint "frontend"') in text
'the blueprint "frontend"' in text) assert 'See http://flask.pocoo.org/docs/blueprints/#templates' in text
self.assert_(
'See http://flask.pocoo.org/docs/blueprints/#templates' in text)
with app.test_client() as c: with app.test_client() as c:
try: try:
@ -336,14 +334,14 @@ class TestTemplating(TestFlask):
try: try:
c.get('/missing') c.get('/missing')
except TemplateNotFound as e: except TemplateNotFound as e:
self.assert_('missing_template.html' in str(e)) assert 'missing_template.html' in str(e)
else: else:
self.fail('Expected template not found exception.') self.fail('Expected template not found exception.')
finally: finally:
app.logger.handlers[:] = old_handlers app.logger.handlers[:] = old_handlers
app.config['EXPLAIN_TEMPLATE_LOADING'] = old_load_setting app.config['EXPLAIN_TEMPLATE_LOADING'] = old_load_setting
self.assert_equal(len(called), 1) assert len(called) == 1
def suite(): def suite():

74
tests/test_testing.py

@ -28,10 +28,10 @@ class TestTestTools(TestFlask):
return flask.request.url return flask.request.url
ctx = app.test_request_context() ctx = app.test_request_context()
self.assert_equal(ctx.request.url, 'http://example.com:1234/foo/') assert ctx.request.url == 'http://example.com:1234/foo/'
with app.test_client() as c: with app.test_client() as c:
rv = c.get('/') rv = c.get('/')
self.assert_equal(rv.data, b'http://example.com:1234/foo/') assert rv.data == b'http://example.com:1234/foo/'
def test_environ_defaults(self): def test_environ_defaults(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -41,10 +41,10 @@ class TestTestTools(TestFlask):
return flask.request.url return flask.request.url
ctx = app.test_request_context() ctx = app.test_request_context()
self.assert_equal(ctx.request.url, 'http://localhost/') assert ctx.request.url == 'http://localhost/'
with app.test_client() as c: with app.test_client() as c:
rv = c.get('/') rv = c.get('/')
self.assert_equal(rv.data, b'http://localhost/') assert rv.data == b'http://localhost/'
def test_redirect_keep_session(self): def test_redirect_keep_session(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -89,14 +89,14 @@ class TestTestTools(TestFlask):
with app.test_client() as c: with app.test_client() as c:
with c.session_transaction() as sess: with c.session_transaction() as sess:
self.assert_equal(len(sess), 0) assert len(sess) == 0
sess['foo'] = [42] sess['foo'] = [42]
self.assert_equal(len(sess), 1) assert len(sess) == 1
rv = c.get('/') rv = c.get('/')
self.assert_equal(rv.data, b'[42]') assert rv.data == b'[42]'
with c.session_transaction() as sess: with c.session_transaction() as sess:
self.assert_equal(len(sess), 1) assert len(sess) == 1
self.assert_equal(sess['foo'], [42]) assert sess['foo'] == [42]
def test_session_transactions_no_null_sessions(self): def test_session_transactions_no_null_sessions(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -107,9 +107,9 @@ class TestTestTools(TestFlask):
with c.session_transaction() as sess: with c.session_transaction() as sess:
pass pass
except RuntimeError as e: except RuntimeError as e:
self.assert_in('Session backend did not open a session', str(e)) assert 'Session backend did not open a session' in str(e)
else: else:
self.fail('Expected runtime error') assert False, 'Expected runtime error'
def test_session_transactions_keep_context(self): def test_session_transactions_keep_context(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -119,9 +119,9 @@ class TestTestTools(TestFlask):
with app.test_client() as c: with app.test_client() as c:
rv = c.get('/') rv = c.get('/')
req = flask.request._get_current_object() req = flask.request._get_current_object()
self.assert_true(req is not None) assert req is not None
with c.session_transaction(): with c.session_transaction():
self.assert_true(req is flask.request._get_current_object()) assert req is flask.request._get_current_object()
def test_session_transaction_needs_cookies(self): def test_session_transaction_needs_cookies(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -131,9 +131,9 @@ class TestTestTools(TestFlask):
with c.session_transaction() as s: with c.session_transaction() as s:
pass pass
except RuntimeError as e: except RuntimeError as e:
self.assert_in('cookies', str(e)) assert 'cookies' in str(e)
else: else:
self.fail('Expected runtime error') assert False, 'Expected runtime error'
def test_test_client_context_binding(self): def test_test_client_context_binding(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -149,14 +149,14 @@ class TestTestTools(TestFlask):
with app.test_client() as c: with app.test_client() as c:
resp = c.get('/') resp = c.get('/')
self.assert_equal(flask.g.value, 42) assert flask.g.value == 42
self.assert_equal(resp.data, b'Hello World!') assert resp.data == b'Hello World!'
self.assert_equal(resp.status_code, 200) assert resp.status_code == 200
resp = c.get('/other') resp = c.get('/other')
self.assert_false(hasattr(flask.g, 'value')) assert not hasattr(flask.g, 'value')
self.assert_in(b'Internal Server Error', resp.data) assert b'Internal Server Error' in resp.data
self.assert_equal(resp.status_code, 500) assert resp.status_code == 500
flask.g.value = 23 flask.g.value = 23
try: try:
@ -171,10 +171,10 @@ class TestTestTools(TestFlask):
c = app.test_client() c = app.test_client()
with c: with c:
self.assert_equal(c.get('/').status_code, 404) assert c.get('/').status_code == 404
with c: with c:
self.assert_equal(c.get('/').status_code, 404) assert c.get('/').status_code == 404
def test_test_client_calls_teardown_handlers(self): def test_test_client_calls_teardown_handlers(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -184,19 +184,19 @@ class TestTestTools(TestFlask):
called.append(error) called.append(error)
with app.test_client() as c: with app.test_client() as c:
self.assert_equal(called, []) assert called == []
c.get('/') c.get('/')
self.assert_equal(called, []) assert called == []
self.assert_equal(called, [None]) assert called == [None]
del called[:] del called[:]
with app.test_client() as c: with app.test_client() as c:
self.assert_equal(called, []) assert called == []
c.get('/') c.get('/')
self.assert_equal(called, []) assert called == []
c.get('/') c.get('/')
self.assert_equal(called, [None]) assert called == [None]
self.assert_equal(called, [None, None]) assert called == [None, None]
def test_full_url_request(self): def test_full_url_request(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -208,9 +208,9 @@ class TestTestTools(TestFlask):
with app.test_client() as c: with app.test_client() as c:
rv = c.post('http://domain.com/action?vodka=42', data={'gin': 43}) rv = c.post('http://domain.com/action?vodka=42', data={'gin': 43})
self.assert_equal(rv.status_code, 200) assert rv.status_code == 200
self.assert_true('gin' in flask.request.form) assert 'gin' in flask.request.form
self.assert_true('vodka' in flask.request.args) assert 'vodka' in flask.request.args
class TestSubdomain(TestFlask): class TestSubdomain(TestFlask):
@ -241,8 +241,8 @@ class TestSubdomain(TestFlask):
url = flask.url_for('view', company_id='xxx') url = flask.url_for('view', company_id='xxx')
response = client.get(url) response = client.get(url)
self.assert_equal(200, response.status_code) assert 200 == response.status_code
self.assert_equal(b'xxx', response.data) assert b'xxx' == response.data
def test_nosubdomain(self, app, client): def test_nosubdomain(self, app, client):
@ -253,5 +253,5 @@ class TestSubdomain(TestFlask):
url = flask.url_for('view', company_id='xxx') url = flask.url_for('view', company_id='xxx')
response = client.get(url) response = client.get(url)
self.assert_equal(200, response.status_code) assert 200 == response.status_code
self.assert_equal(b'xxx', response.data) assert b'xxx' == response.data

32
tests/test_views.py

@ -9,6 +9,8 @@
:license: BSD, see LICENSE for more details. :license: BSD, see LICENSE for more details.
""" """
import pytest
import flask import flask
import flask.views import flask.views
import unittest import unittest
@ -20,11 +22,11 @@ class TestView(TestFlask):
def common_test(self, app): def common_test(self, app):
c = app.test_client() c = app.test_client()
self.assert_equal(c.get('/').data, b'GET') assert c.get('/').data == b'GET'
self.assert_equal(c.post('/').data, b'POST') assert c.post('/').data == b'POST'
self.assert_equal(c.put('/').status_code, 405) assert c.put('/').status_code == 405
meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow']) meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])
self.assert_equal(sorted(meths), ['GET', 'HEAD', 'OPTIONS', 'POST']) assert sorted(meths) == ['GET', 'HEAD', 'OPTIONS', 'POST']
def test_basic_view(self): def test_basic_view(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -87,7 +89,7 @@ class TestView(TestFlask):
c = app.test_client() c = app.test_client()
meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow']) meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])
self.assert_equal(sorted(meths), ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST']) assert sorted(meths) == ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST']
def test_view_decorators(self): def test_view_decorators(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -107,8 +109,8 @@ class TestView(TestFlask):
app.add_url_rule('/', view_func=Index.as_view('index')) app.add_url_rule('/', view_func=Index.as_view('index'))
c = app.test_client() c = app.test_client()
rv = c.get('/') rv = c.get('/')
self.assert_equal(rv.headers['X-Parachute'], 'awesome') assert rv.headers['X-Parachute'] == 'awesome'
self.assert_equal(rv.data, b'Awesome') assert rv.data == b'Awesome'
def test_implicit_head(self): def test_implicit_head(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -122,11 +124,11 @@ class TestView(TestFlask):
app.add_url_rule('/', view_func=Index.as_view('index')) app.add_url_rule('/', view_func=Index.as_view('index'))
c = app.test_client() c = app.test_client()
rv = c.get('/') rv = c.get('/')
self.assert_equal(rv.data, b'Blub') assert rv.data == b'Blub'
self.assert_equal(rv.headers['X-Method'], 'GET') assert rv.headers['X-Method'] == 'GET'
rv = c.head('/') rv = c.head('/')
self.assert_equal(rv.data, b'') assert rv.data == b''
self.assert_equal(rv.headers['X-Method'], 'HEAD') assert rv.headers['X-Method'] == 'HEAD'
def test_explicit_head(self): def test_explicit_head(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -140,10 +142,10 @@ class TestView(TestFlask):
app.add_url_rule('/', view_func=Index.as_view('index')) app.add_url_rule('/', view_func=Index.as_view('index'))
c = app.test_client() c = app.test_client()
rv = c.get('/') rv = c.get('/')
self.assert_equal(rv.data, b'GET') assert rv.data == b'GET'
rv = c.head('/') rv = c.head('/')
self.assert_equal(rv.data, b'') assert rv.data == b''
self.assert_equal(rv.headers['X-Method'], 'HEAD') assert rv.headers['X-Method'] == 'HEAD'
def test_endpoint_override(self): def test_endpoint_override(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -156,7 +158,7 @@ class TestView(TestFlask):
app.add_url_rule('/', view_func=Index.as_view('index')) app.add_url_rule('/', view_func=Index.as_view('index'))
with self.assert_raises(AssertionError): with pytest.raises(AssertionError):
app.add_url_rule('/', view_func=Index.as_view('index')) app.add_url_rule('/', view_func=Index.as_view('index'))
# But these tests should still pass. We just log a warning. # But these tests should still pass. We just log a warning.

Loading…
Cancel
Save