diff --git a/tests/test_basic.py b/tests/test_basic.py index eff5419d..f5e32622 100644 --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -26,7 +26,7 @@ from werkzeug.http import parse_date from werkzeug.routing import BuildError -class TestBasicFunctionality(TestFlask): +class TestBasicFunctionality(object): def test_options_work(self): app = flask.Flask(__name__) @@ -1295,7 +1295,7 @@ class TestBasicFunctionality(TestFlask): assert sorted(flask.g) == ['bar', 'foo'] -class TestSubdomain(TestFlask): +class TestSubdomain(object): def test_basic_support(self): app = flask.Flask(__name__) diff --git a/tests/test_blueprints.py b/tests/test_blueprints.py index 6f2be559..f4c0b04c 100644 --- a/tests/test_blueprints.py +++ b/tests/test_blueprints.py @@ -19,567 +19,560 @@ from werkzeug.http import parse_cache_control_header from jinja2 import TemplateNotFound -class TestBlueprint(TestFlask): +def test_blueprint_specific_error_handling(): + frontend = flask.Blueprint('frontend', __name__) + backend = flask.Blueprint('backend', __name__) + sideend = flask.Blueprint('sideend', __name__) - def test_blueprint_specific_error_handling(self): - frontend = flask.Blueprint('frontend', __name__) - backend = flask.Blueprint('backend', __name__) - sideend = flask.Blueprint('sideend', __name__) + @frontend.errorhandler(403) + def frontend_forbidden(e): + return 'frontend says no', 403 - @frontend.errorhandler(403) - def frontend_forbidden(e): - return 'frontend says no', 403 + @frontend.route('/frontend-no') + def frontend_no(): + flask.abort(403) - @frontend.route('/frontend-no') - def frontend_no(): - flask.abort(403) + @backend.errorhandler(403) + def backend_forbidden(e): + return 'backend says no', 403 - @backend.errorhandler(403) - def backend_forbidden(e): - return 'backend says no', 403 + @backend.route('/backend-no') + def backend_no(): + flask.abort(403) - @backend.route('/backend-no') - def backend_no(): - flask.abort(403) + @sideend.route('/what-is-a-sideend') + def sideend_no(): + flask.abort(403) - @sideend.route('/what-is-a-sideend') - def sideend_no(): - flask.abort(403) + app = flask.Flask(__name__) + app.register_blueprint(frontend) + app.register_blueprint(backend) + app.register_blueprint(sideend) - app = flask.Flask(__name__) - app.register_blueprint(frontend) - app.register_blueprint(backend) - app.register_blueprint(sideend) + @app.errorhandler(403) + def app_forbidden(e): + return 'application itself says no', 403 + + c = app.test_client() + + assert c.get('/frontend-no').data == b'frontend says no' + assert c.get('/backend-no').data == b'backend says no' + assert c.get('/what-is-a-sideend').data == b'application itself says no' + +def test_blueprint_specific_user_error_handling(): + class MyDecoratorException(Exception): + pass + class MyFunctionException(Exception): + pass + + blue = flask.Blueprint('blue', __name__) + + @blue.errorhandler(MyDecoratorException) + def my_decorator_exception_handler(e): + assert isinstance(e, MyDecoratorException) + return 'boom' + + def my_function_exception_handler(e): + assert isinstance(e, MyFunctionException) + return 'bam' + blue.register_error_handler(MyFunctionException, my_function_exception_handler) + + @blue.route('/decorator') + def blue_deco_test(): + raise MyDecoratorException() + @blue.route('/function') + def blue_func_test(): + raise MyFunctionException() + + app = flask.Flask(__name__) + app.register_blueprint(blue) + + c = app.test_client() + + assert c.get('/decorator').data == b'boom' + assert c.get('/function').data == b'bam' + +def test_blueprint_url_definitions(): + bp = flask.Blueprint('test', __name__) + + @bp.route('/foo', defaults={'baz': 42}) + def foo(bar, baz): + return '%s/%d' % (bar, baz) + + @bp.route('/bar') + def bar(bar): + return text_type(bar) + + app = flask.Flask(__name__) + app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23}) + app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19}) + + c = app.test_client() + assert c.get('/1/foo').data == b'23/42' + assert c.get('/2/foo').data == b'19/42' + assert c.get('/1/bar').data == b'23' + assert c.get('/2/bar').data == b'19' + +def test_blueprint_url_processors(): + bp = flask.Blueprint('frontend', __name__, url_prefix='/') + + @bp.url_defaults + def add_language_code(endpoint, values): + values.setdefault('lang_code', flask.g.lang_code) + + @bp.url_value_preprocessor + def pull_lang_code(endpoint, values): + flask.g.lang_code = values.pop('lang_code') + + @bp.route('/') + def index(): + return flask.url_for('.about') + + @bp.route('/about') + def about(): + return flask.url_for('.index') + + app = flask.Flask(__name__) + app.register_blueprint(bp) + + c = app.test_client() + + assert c.get('/de/').data == b'/de/about' + assert c.get('/de/about').data == b'/de/' + +def test_templates_and_static(): + from blueprintapp import app + c = app.test_client() + + rv = c.get('/') + assert rv.data == b'Hello from the Frontend' + rv = c.get('/admin/') + assert rv.data == b'Hello from the Admin' + rv = c.get('/admin/index2') + assert rv.data == b'Hello from the Admin' + rv = c.get('/admin/static/test.txt') + assert rv.data.strip() == b'Admin File' + rv.close() + rv = c.get('/admin/static/css/test.css') + assert rv.data.strip() == b'/* nested file */' + rv.close() + + # try/finally, in case other tests use this app for Blueprint tests. + max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT'] + try: + expected_max_age = 3600 + if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == expected_max_age: + expected_max_age = 7200 + app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age + rv = c.get('/admin/static/css/test.css') + cc = parse_cache_control_header(rv.headers['Cache-Control']) + assert cc.max_age == expected_max_age + rv.close() + finally: + app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default - @app.errorhandler(403) - def app_forbidden(e): - return 'application itself says no', 403 + with app.test_request_context(): + assert flask.url_for('admin.static', filename='test.txt') == '/admin/static/test.txt' - c = app.test_client() + with app.test_request_context(): + try: + flask.render_template('missing.html') + except TemplateNotFound as e: + assert e.name == 'missing.html' + else: + assert 0, 'expected exception' - assert c.get('/frontend-no').data == b'frontend says no' - assert c.get('/backend-no').data == b'backend says no' - assert c.get('/what-is-a-sideend').data == b'application itself says no' + with flask.Flask(__name__).test_request_context(): + assert flask.render_template('nested/nested.txt') == 'I\'m nested' - def test_blueprint_specific_user_error_handling(self): - class MyDecoratorException(Exception): - pass - class MyFunctionException(Exception): - pass +def test_default_static_cache_timeout(): + app = flask.Flask(__name__) + class MyBlueprint(flask.Blueprint): + def get_send_file_max_age(self, filename): + return 100 - blue = flask.Blueprint('blue', __name__) + blueprint = MyBlueprint('blueprint', __name__, static_folder='static') + app.register_blueprint(blueprint) - @blue.errorhandler(MyDecoratorException) - def my_decorator_exception_handler(e): - assert isinstance(e, MyDecoratorException) - return 'boom' + # try/finally, in case other tests use this app for Blueprint tests. + max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT'] + try: + with app.test_request_context(): + unexpected_max_age = 3600 + if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == unexpected_max_age: + unexpected_max_age = 7200 + app.config['SEND_FILE_MAX_AGE_DEFAULT'] = unexpected_max_age + rv = blueprint.send_static_file('index.html') + cc = parse_cache_control_header(rv.headers['Cache-Control']) + assert cc.max_age == 100 + rv.close() + finally: + app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default - def my_function_exception_handler(e): - assert isinstance(e, MyFunctionException) - return 'bam' - blue.register_error_handler(MyFunctionException, my_function_exception_handler) +def test_templates_list(): + from blueprintapp import app + templates = sorted(app.jinja_env.list_templates()) + assert templates == ['admin/index.html', 'frontend/index.html'] - @blue.route('/decorator') - def blue_deco_test(): - raise MyDecoratorException() - @blue.route('/function') - def blue_func_test(): - raise MyFunctionException() +def test_dotted_names(): + frontend = flask.Blueprint('myapp.frontend', __name__) + backend = flask.Blueprint('myapp.backend', __name__) - app = flask.Flask(__name__) - app.register_blueprint(blue) + @frontend.route('/fe') + def frontend_index(): + return flask.url_for('myapp.backend.backend_index') - c = app.test_client() + @frontend.route('/fe2') + def frontend_page2(): + return flask.url_for('.frontend_index') - assert c.get('/decorator').data == b'boom' - assert c.get('/function').data == b'bam' + @backend.route('/be') + def backend_index(): + return flask.url_for('myapp.frontend.frontend_index') - def test_blueprint_url_definitions(self): - bp = flask.Blueprint('test', __name__) + app = flask.Flask(__name__) + app.register_blueprint(frontend) + app.register_blueprint(backend) - @bp.route('/foo', defaults={'baz': 42}) - def foo(bar, baz): - return '%s/%d' % (bar, baz) + c = app.test_client() + assert c.get('/fe').data.strip() == b'/be' + assert c.get('/fe2').data.strip() == b'/fe' + assert c.get('/be').data.strip() == b'/fe' - @bp.route('/bar') - def bar(bar): - return text_type(bar) +def test_dotted_names_from_app(): + app = flask.Flask(__name__) + app.testing = True + test = flask.Blueprint('test', __name__) - app = flask.Flask(__name__) - app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23}) - app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19}) + @app.route('/') + def app_index(): + return flask.url_for('test.index') - c = app.test_client() - assert c.get('/1/foo').data == b'23/42' - assert c.get('/2/foo').data == b'19/42' - assert c.get('/1/bar').data == b'23' - assert c.get('/2/bar').data == b'19' + @test.route('/test/') + def index(): + return flask.url_for('app_index') - def test_blueprint_url_processors(self): - bp = flask.Blueprint('frontend', __name__, url_prefix='/') + app.register_blueprint(test) - @bp.url_defaults - def add_language_code(endpoint, values): - values.setdefault('lang_code', flask.g.lang_code) + with app.test_client() as c: + rv = c.get('/') + assert rv.data == b'/test/' - @bp.url_value_preprocessor - def pull_lang_code(endpoint, values): - flask.g.lang_code = values.pop('lang_code') +def test_empty_url_defaults(): + bp = flask.Blueprint('bp', __name__) - @bp.route('/') - def index(): - return flask.url_for('.about') + @bp.route('/', defaults={'page': 1}) + @bp.route('/page/') + def something(page): + return str(page) - @bp.route('/about') - def about(): - return flask.url_for('.index') + app = flask.Flask(__name__) + app.register_blueprint(bp) - app = flask.Flask(__name__) - app.register_blueprint(bp) + c = app.test_client() + assert c.get('/').data == b'1' + assert c.get('/page/2').data == b'2' - c = app.test_client() +def test_route_decorator_custom_endpoint(): - assert c.get('/de/').data == b'/de/about' - assert c.get('/de/about').data == b'/de/' + bp = flask.Blueprint('bp', __name__) - def test_templates_and_static(self): - from blueprintapp import app - c = app.test_client() + @bp.route('/foo') + def foo(): + return flask.request.endpoint - rv = c.get('/') - assert rv.data == b'Hello from the Frontend' - rv = c.get('/admin/') - assert rv.data == b'Hello from the Admin' - rv = c.get('/admin/index2') - assert rv.data == b'Hello from the Admin' - rv = c.get('/admin/static/test.txt') - assert rv.data.strip() == b'Admin File' - rv.close() - rv = c.get('/admin/static/css/test.css') - assert rv.data.strip() == b'/* nested file */' - rv.close() + @bp.route('/bar', endpoint='bar') + def foo_bar(): + return flask.request.endpoint - # try/finally, in case other tests use this app for Blueprint tests. - max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT'] - try: - expected_max_age = 3600 - if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == expected_max_age: - expected_max_age = 7200 - app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age - rv = c.get('/admin/static/css/test.css') - cc = parse_cache_control_header(rv.headers['Cache-Control']) - assert cc.max_age == expected_max_age - rv.close() - finally: - app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default + @bp.route('/bar/123', endpoint='123') + def foo_bar_foo(): + return flask.request.endpoint - with app.test_request_context(): - assert flask.url_for('admin.static', filename='test.txt') == '/admin/static/test.txt' + @bp.route('/bar/foo') + def bar_foo(): + return flask.request.endpoint - with app.test_request_context(): - try: - flask.render_template('missing.html') - except TemplateNotFound as e: - assert e.name == 'missing.html' - else: - assert 0, 'expected exception' - - with flask.Flask(__name__).test_request_context(): - assert flask.render_template('nested/nested.txt') == 'I\'m nested' - - def test_default_static_cache_timeout(self): - app = flask.Flask(__name__) - class MyBlueprint(flask.Blueprint): - def get_send_file_max_age(self, filename): - return 100 - - blueprint = MyBlueprint('blueprint', __name__, static_folder='static') - app.register_blueprint(blueprint) - - # try/finally, in case other tests use this app for Blueprint tests. - max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT'] - try: - with app.test_request_context(): - unexpected_max_age = 3600 - if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == unexpected_max_age: - unexpected_max_age = 7200 - app.config['SEND_FILE_MAX_AGE_DEFAULT'] = unexpected_max_age - rv = blueprint.send_static_file('index.html') - cc = parse_cache_control_header(rv.headers['Cache-Control']) - assert cc.max_age == 100 - rv.close() - finally: - app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default - - def test_templates_list(self): - from blueprintapp import app - templates = sorted(app.jinja_env.list_templates()) - assert templates == ['admin/index.html', 'frontend/index.html'] - - def test_dotted_names(self): - frontend = flask.Blueprint('myapp.frontend', __name__) - backend = flask.Blueprint('myapp.backend', __name__) - - @frontend.route('/fe') - def frontend_index(): - return flask.url_for('myapp.backend.backend_index') - - @frontend.route('/fe2') - def frontend_page2(): - return flask.url_for('.frontend_index') - - @backend.route('/be') - def backend_index(): - return flask.url_for('myapp.frontend.frontend_index') - - app = flask.Flask(__name__) - app.register_blueprint(frontend) - app.register_blueprint(backend) - - c = app.test_client() - assert c.get('/fe').data.strip() == b'/be' - assert c.get('/fe2').data.strip() == b'/fe' - assert c.get('/be').data.strip() == b'/fe' - - def test_dotted_names_from_app(self): - app = flask.Flask(__name__) - app.testing = True - test = flask.Blueprint('test', __name__) - - @app.route('/') - def app_index(): - return flask.url_for('test.index') - - @test.route('/test/') - def index(): - return flask.url_for('app_index') - - app.register_blueprint(test) - - with app.test_client() as c: - rv = c.get('/') - assert rv.data == b'/test/' - - def test_empty_url_defaults(self): - bp = flask.Blueprint('bp', __name__) - - @bp.route('/', defaults={'page': 1}) - @bp.route('/page/') - def something(page): - return str(page) - - app = flask.Flask(__name__) - app.register_blueprint(bp) - - c = app.test_client() - assert c.get('/').data == b'1' - assert c.get('/page/2').data == b'2' - - def test_route_decorator_custom_endpoint(self): - - bp = flask.Blueprint('bp', __name__) - - @bp.route('/foo') - def foo(): - return flask.request.endpoint + app = flask.Flask(__name__) + app.register_blueprint(bp, url_prefix='/py') - @bp.route('/bar', endpoint='bar') - def foo_bar(): - return flask.request.endpoint + @app.route('/') + def index(): + return flask.request.endpoint - @bp.route('/bar/123', endpoint='123') - def foo_bar_foo(): - return flask.request.endpoint + c = app.test_client() + assert c.get('/').data == b'index' + assert c.get('/py/foo').data == b'bp.foo' + assert c.get('/py/bar').data == b'bp.bar' + assert c.get('/py/bar/123').data == b'bp.123' + assert c.get('/py/bar/foo').data == b'bp.bar_foo' - @bp.route('/bar/foo') - def bar_foo(): - return flask.request.endpoint +def test_route_decorator_custom_endpoint_with_dots(): + bp = flask.Blueprint('bp', __name__) - app = flask.Flask(__name__) - app.register_blueprint(bp, url_prefix='/py') + @bp.route('/foo') + def foo(): + return flask.request.endpoint - @app.route('/') - def index(): + try: + @bp.route('/bar', endpoint='bar.bar') + def foo_bar(): return flask.request.endpoint + except AssertionError: + pass + else: + raise AssertionError('expected AssertionError not raised') - c = app.test_client() - assert c.get('/').data == b'index' - assert c.get('/py/foo').data == b'bp.foo' - assert c.get('/py/bar').data == b'bp.bar' - assert c.get('/py/bar/123').data == b'bp.123' - assert c.get('/py/bar/foo').data == b'bp.bar_foo' - - def test_route_decorator_custom_endpoint_with_dots(self): - bp = flask.Blueprint('bp', __name__) - - @bp.route('/foo') - def foo(): + try: + @bp.route('/bar/123', endpoint='bar.123') + def foo_bar_foo(): return flask.request.endpoint - - try: - @bp.route('/bar', endpoint='bar.bar') - def foo_bar(): - return flask.request.endpoint - except AssertionError: - pass - else: - raise AssertionError('expected AssertionError not raised') - - try: - @bp.route('/bar/123', endpoint='bar.123') - def foo_bar_foo(): - return flask.request.endpoint - except AssertionError: - pass - else: - raise AssertionError('expected AssertionError not raised') - - def foo_foo_foo(): - pass - - pytest.raises( - AssertionError, - lambda: bp.add_url_rule( - '/bar/123', endpoint='bar.123', view_func=foo_foo_foo - ) - ) - - pytest.raises( - AssertionError, - bp.route('/bar/123', endpoint='bar.123'), - lambda: None + except AssertionError: + pass + else: + raise AssertionError('expected AssertionError not raised') + + def foo_foo_foo(): + pass + + pytest.raises( + AssertionError, + lambda: bp.add_url_rule( + '/bar/123', endpoint='bar.123', view_func=foo_foo_foo ) - - app = flask.Flask(__name__) - app.register_blueprint(bp, url_prefix='/py') - - c = app.test_client() - assert c.get('/py/foo').data == b'bp.foo' - # The rule's didn't actually made it through - rv = c.get('/py/bar') - assert rv.status_code == 404 - rv = c.get('/py/bar/123') - assert rv.status_code == 404 - - def test_template_filter(self): - bp = flask.Blueprint('bp', __name__) - @bp.app_template_filter() - def my_reverse(s): - return s[::-1] - app = flask.Flask(__name__) - app.register_blueprint(bp, url_prefix='/py') - assert 'my_reverse' in app.jinja_env.filters.keys() - assert app.jinja_env.filters['my_reverse'] == my_reverse - assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba' - - def test_add_template_filter(self): - bp = flask.Blueprint('bp', __name__) - def my_reverse(s): - return s[::-1] - bp.add_app_template_filter(my_reverse) - app = flask.Flask(__name__) - app.register_blueprint(bp, url_prefix='/py') - assert 'my_reverse' in app.jinja_env.filters.keys() - assert app.jinja_env.filters['my_reverse'] == my_reverse - assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba' - - def test_template_filter_with_name(self): - bp = flask.Blueprint('bp', __name__) - @bp.app_template_filter('strrev') - def my_reverse(s): - return s[::-1] - app = flask.Flask(__name__) - app.register_blueprint(bp, url_prefix='/py') - assert 'strrev' in app.jinja_env.filters.keys() - assert app.jinja_env.filters['strrev'] == my_reverse - assert app.jinja_env.filters['strrev']('abcd') == 'dcba' - - def test_add_template_filter_with_name(self): - bp = flask.Blueprint('bp', __name__) - def my_reverse(s): - return s[::-1] - bp.add_app_template_filter(my_reverse, 'strrev') - app = flask.Flask(__name__) - app.register_blueprint(bp, url_prefix='/py') - assert 'strrev' in app.jinja_env.filters.keys() - assert app.jinja_env.filters['strrev'] == my_reverse - assert app.jinja_env.filters['strrev']('abcd') == 'dcba' - - def test_template_filter_with_template(self): - bp = flask.Blueprint('bp', __name__) - @bp.app_template_filter() - def super_reverse(s): - return s[::-1] - app = flask.Flask(__name__) - app.register_blueprint(bp, url_prefix='/py') - @app.route('/') - def index(): - return flask.render_template('template_filter.html', value='abcd') - rv = app.test_client().get('/') - assert rv.data == b'dcba' - - def test_template_filter_after_route_with_template(self): - app = flask.Flask(__name__) - @app.route('/') - def index(): - return flask.render_template('template_filter.html', value='abcd') - bp = flask.Blueprint('bp', __name__) - @bp.app_template_filter() - def super_reverse(s): - return s[::-1] - app.register_blueprint(bp, url_prefix='/py') - rv = app.test_client().get('/') - assert rv.data == b'dcba' - - def test_add_template_filter_with_template(self): - bp = flask.Blueprint('bp', __name__) - def super_reverse(s): - return s[::-1] - bp.add_app_template_filter(super_reverse) - app = flask.Flask(__name__) - app.register_blueprint(bp, url_prefix='/py') - @app.route('/') - def index(): - return flask.render_template('template_filter.html', value='abcd') - rv = app.test_client().get('/') - assert rv.data == b'dcba' - - def test_template_filter_with_name_and_template(self): - bp = flask.Blueprint('bp', __name__) - @bp.app_template_filter('super_reverse') - def my_reverse(s): - return s[::-1] - app = flask.Flask(__name__) - app.register_blueprint(bp, url_prefix='/py') - @app.route('/') - def index(): - return flask.render_template('template_filter.html', value='abcd') - rv = app.test_client().get('/') - assert rv.data == b'dcba' - - def test_add_template_filter_with_name_and_template(self): - bp = flask.Blueprint('bp', __name__) - def my_reverse(s): - return s[::-1] - bp.add_app_template_filter(my_reverse, 'super_reverse') - app = flask.Flask(__name__) - app.register_blueprint(bp, url_prefix='/py') - @app.route('/') - def index(): - return flask.render_template('template_filter.html', value='abcd') - rv = app.test_client().get('/') - assert rv.data == b'dcba' - - def test_template_test(self): - bp = flask.Blueprint('bp', __name__) - @bp.app_template_test() - def is_boolean(value): - return isinstance(value, bool) - app = flask.Flask(__name__) - app.register_blueprint(bp, url_prefix='/py') - assert 'is_boolean' in app.jinja_env.tests.keys() - assert app.jinja_env.tests['is_boolean'] == is_boolean - assert app.jinja_env.tests['is_boolean'](False) - - def test_add_template_test(self): - bp = flask.Blueprint('bp', __name__) - def is_boolean(value): - return isinstance(value, bool) - bp.add_app_template_test(is_boolean) - app = flask.Flask(__name__) - app.register_blueprint(bp, url_prefix='/py') - assert 'is_boolean' in app.jinja_env.tests.keys() - assert app.jinja_env.tests['is_boolean'] == is_boolean - assert app.jinja_env.tests['is_boolean'](False) - - def test_template_test_with_name(self): - bp = flask.Blueprint('bp', __name__) - @bp.app_template_test('boolean') - def is_boolean(value): - return isinstance(value, bool) - app = flask.Flask(__name__) - app.register_blueprint(bp, url_prefix='/py') - assert 'boolean' in app.jinja_env.tests.keys() - assert app.jinja_env.tests['boolean'] == is_boolean - assert app.jinja_env.tests['boolean'](False) - - def test_add_template_test_with_name(self): - bp = flask.Blueprint('bp', __name__) - def is_boolean(value): - return isinstance(value, bool) - bp.add_app_template_test(is_boolean, 'boolean') - app = flask.Flask(__name__) - app.register_blueprint(bp, url_prefix='/py') - assert 'boolean' in app.jinja_env.tests.keys() - assert app.jinja_env.tests['boolean'] == is_boolean - assert app.jinja_env.tests['boolean'](False) - - def test_template_test_with_template(self): - bp = flask.Blueprint('bp', __name__) - @bp.app_template_test() - def boolean(value): - return isinstance(value, bool) - app = flask.Flask(__name__) - app.register_blueprint(bp, url_prefix='/py') - @app.route('/') - def index(): - return flask.render_template('template_test.html', value=False) - rv = app.test_client().get('/') - assert b'Success!' in rv.data - - def test_template_test_after_route_with_template(self): - app = flask.Flask(__name__) - @app.route('/') - def index(): - return flask.render_template('template_test.html', value=False) - bp = flask.Blueprint('bp', __name__) - @bp.app_template_test() - def boolean(value): - return isinstance(value, bool) - app.register_blueprint(bp, url_prefix='/py') - rv = app.test_client().get('/') - assert b'Success!' in rv.data - - def test_add_template_test_with_template(self): - bp = flask.Blueprint('bp', __name__) - def boolean(value): - return isinstance(value, bool) - bp.add_app_template_test(boolean) - app = flask.Flask(__name__) - app.register_blueprint(bp, url_prefix='/py') - @app.route('/') - def index(): - return flask.render_template('template_test.html', value=False) - rv = app.test_client().get('/') - assert b'Success!' in rv.data - - def test_template_test_with_name_and_template(self): - bp = flask.Blueprint('bp', __name__) - @bp.app_template_test('boolean') - def is_boolean(value): - return isinstance(value, bool) - app = flask.Flask(__name__) - app.register_blueprint(bp, url_prefix='/py') - @app.route('/') - def index(): - return flask.render_template('template_test.html', value=False) - rv = app.test_client().get('/') - assert b'Success!' in rv.data - - def test_add_template_test_with_name_and_template(self): - bp = flask.Blueprint('bp', __name__) - def is_boolean(value): - return isinstance(value, bool) - bp.add_app_template_test(is_boolean, 'boolean') - app = flask.Flask(__name__) - app.register_blueprint(bp, url_prefix='/py') - @app.route('/') - def index(): - return flask.render_template('template_test.html', value=False) - rv = app.test_client().get('/') - assert b'Success!' in rv.data - -def suite(): - suite = unittest.TestSuite() - suite.addTest(unittest.makeSuite(TestBlueprint)) - return suite + ) + + pytest.raises( + AssertionError, + bp.route('/bar/123', endpoint='bar.123'), + lambda: None + ) + + app = flask.Flask(__name__) + app.register_blueprint(bp, url_prefix='/py') + + c = app.test_client() + assert c.get('/py/foo').data == b'bp.foo' + # The rule's didn't actually made it through + rv = c.get('/py/bar') + assert rv.status_code == 404 + rv = c.get('/py/bar/123') + assert rv.status_code == 404 + +def test_template_filter(): + bp = flask.Blueprint('bp', __name__) + @bp.app_template_filter() + def my_reverse(s): + return s[::-1] + app = flask.Flask(__name__) + app.register_blueprint(bp, url_prefix='/py') + assert 'my_reverse' in app.jinja_env.filters.keys() + assert app.jinja_env.filters['my_reverse'] == my_reverse + assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba' + +def test_add_template_filter(): + bp = flask.Blueprint('bp', __name__) + def my_reverse(s): + return s[::-1] + bp.add_app_template_filter(my_reverse) + app = flask.Flask(__name__) + app.register_blueprint(bp, url_prefix='/py') + assert 'my_reverse' in app.jinja_env.filters.keys() + assert app.jinja_env.filters['my_reverse'] == my_reverse + assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba' + +def test_template_filter_with_name(): + bp = flask.Blueprint('bp', __name__) + @bp.app_template_filter('strrev') + def my_reverse(s): + return s[::-1] + app = flask.Flask(__name__) + app.register_blueprint(bp, url_prefix='/py') + assert 'strrev' in app.jinja_env.filters.keys() + assert app.jinja_env.filters['strrev'] == my_reverse + assert app.jinja_env.filters['strrev']('abcd') == 'dcba' + +def test_add_template_filter_with_name(): + bp = flask.Blueprint('bp', __name__) + def my_reverse(s): + return s[::-1] + bp.add_app_template_filter(my_reverse, 'strrev') + app = flask.Flask(__name__) + app.register_blueprint(bp, url_prefix='/py') + assert 'strrev' in app.jinja_env.filters.keys() + assert app.jinja_env.filters['strrev'] == my_reverse + assert app.jinja_env.filters['strrev']('abcd') == 'dcba' + +def test_template_filter_with_template(): + bp = flask.Blueprint('bp', __name__) + @bp.app_template_filter() + def super_reverse(s): + return s[::-1] + app = flask.Flask(__name__) + app.register_blueprint(bp, url_prefix='/py') + @app.route('/') + def index(): + return flask.render_template('template_filter.html', value='abcd') + rv = app.test_client().get('/') + assert rv.data == b'dcba' + +def test_template_filter_after_route_with_template(): + app = flask.Flask(__name__) + @app.route('/') + def index(): + return flask.render_template('template_filter.html', value='abcd') + bp = flask.Blueprint('bp', __name__) + @bp.app_template_filter() + def super_reverse(s): + return s[::-1] + app.register_blueprint(bp, url_prefix='/py') + rv = app.test_client().get('/') + assert rv.data == b'dcba' + +def test_add_template_filter_with_template(): + bp = flask.Blueprint('bp', __name__) + def super_reverse(s): + return s[::-1] + bp.add_app_template_filter(super_reverse) + app = flask.Flask(__name__) + app.register_blueprint(bp, url_prefix='/py') + @app.route('/') + def index(): + return flask.render_template('template_filter.html', value='abcd') + rv = app.test_client().get('/') + assert rv.data == b'dcba' + +def test_template_filter_with_name_and_template(): + bp = flask.Blueprint('bp', __name__) + @bp.app_template_filter('super_reverse') + def my_reverse(s): + return s[::-1] + app = flask.Flask(__name__) + app.register_blueprint(bp, url_prefix='/py') + @app.route('/') + def index(): + return flask.render_template('template_filter.html', value='abcd') + rv = app.test_client().get('/') + assert rv.data == b'dcba' + +def test_add_template_filter_with_name_and_template(): + bp = flask.Blueprint('bp', __name__) + def my_reverse(s): + return s[::-1] + bp.add_app_template_filter(my_reverse, 'super_reverse') + app = flask.Flask(__name__) + app.register_blueprint(bp, url_prefix='/py') + @app.route('/') + def index(): + return flask.render_template('template_filter.html', value='abcd') + rv = app.test_client().get('/') + assert rv.data == b'dcba' + +def test_template_test(): + bp = flask.Blueprint('bp', __name__) + @bp.app_template_test() + def is_boolean(value): + return isinstance(value, bool) + app = flask.Flask(__name__) + app.register_blueprint(bp, url_prefix='/py') + assert 'is_boolean' in app.jinja_env.tests.keys() + assert app.jinja_env.tests['is_boolean'] == is_boolean + assert app.jinja_env.tests['is_boolean'](False) + +def test_add_template_test(): + bp = flask.Blueprint('bp', __name__) + def is_boolean(value): + return isinstance(value, bool) + bp.add_app_template_test(is_boolean) + app = flask.Flask(__name__) + app.register_blueprint(bp, url_prefix='/py') + assert 'is_boolean' in app.jinja_env.tests.keys() + assert app.jinja_env.tests['is_boolean'] == is_boolean + assert app.jinja_env.tests['is_boolean'](False) + +def test_template_test_with_name(): + bp = flask.Blueprint('bp', __name__) + @bp.app_template_test('boolean') + def is_boolean(value): + return isinstance(value, bool) + app = flask.Flask(__name__) + app.register_blueprint(bp, url_prefix='/py') + assert 'boolean' in app.jinja_env.tests.keys() + assert app.jinja_env.tests['boolean'] == is_boolean + assert app.jinja_env.tests['boolean'](False) + +def test_add_template_test_with_name(): + bp = flask.Blueprint('bp', __name__) + def is_boolean(value): + return isinstance(value, bool) + bp.add_app_template_test(is_boolean, 'boolean') + app = flask.Flask(__name__) + app.register_blueprint(bp, url_prefix='/py') + assert 'boolean' in app.jinja_env.tests.keys() + assert app.jinja_env.tests['boolean'] == is_boolean + assert app.jinja_env.tests['boolean'](False) + +def test_template_test_with_template(): + bp = flask.Blueprint('bp', __name__) + @bp.app_template_test() + def boolean(value): + return isinstance(value, bool) + app = flask.Flask(__name__) + app.register_blueprint(bp, url_prefix='/py') + @app.route('/') + def index(): + return flask.render_template('template_test.html', value=False) + rv = app.test_client().get('/') + assert b'Success!' in rv.data + +def test_template_test_after_route_with_template(): + app = flask.Flask(__name__) + @app.route('/') + def index(): + return flask.render_template('template_test.html', value=False) + bp = flask.Blueprint('bp', __name__) + @bp.app_template_test() + def boolean(value): + return isinstance(value, bool) + app.register_blueprint(bp, url_prefix='/py') + rv = app.test_client().get('/') + assert b'Success!' in rv.data + +def test_add_template_test_with_template(): + bp = flask.Blueprint('bp', __name__) + def boolean(value): + return isinstance(value, bool) + bp.add_app_template_test(boolean) + app = flask.Flask(__name__) + app.register_blueprint(bp, url_prefix='/py') + @app.route('/') + def index(): + return flask.render_template('template_test.html', value=False) + rv = app.test_client().get('/') + assert b'Success!' in rv.data + +def test_template_test_with_name_and_template(): + bp = flask.Blueprint('bp', __name__) + @bp.app_template_test('boolean') + def is_boolean(value): + return isinstance(value, bool) + app = flask.Flask(__name__) + app.register_blueprint(bp, url_prefix='/py') + @app.route('/') + def index(): + return flask.render_template('template_test.html', value=False) + rv = app.test_client().get('/') + assert b'Success!' in rv.data + +def test_add_template_test_with_name_and_template(): + bp = flask.Blueprint('bp', __name__) + def is_boolean(value): + return isinstance(value, bool) + bp.add_app_template_test(is_boolean, 'boolean') + app = flask.Flask(__name__) + app.register_blueprint(bp, url_prefix='/py') + @app.route('/') + def index(): + return flask.render_template('template_test.html', value=False) + rv = app.test_client().get('/') + assert b'Success!' in rv.data diff --git a/tests/test_config.py b/tests/test_config.py index 2faaa0c8..9ce26b0f 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -27,7 +27,7 @@ TEST_KEY = 'foo' SECRET_KEY = 'devkey' -class TestConfig(TestFlask): +class TestConfig(object): def common_object_test(self, app): assert app.secret_key == 'devkey' @@ -181,7 +181,7 @@ class TestConfig(TestFlask): assert 'bar stuff 2' == bar_options['STUFF_2'] -class TestInstance(TestFlask): +class TestInstance(object): def test_explicit_instance_paths(self, apps_tmpdir): with pytest.raises(ValueError) as excinfo: flask.Flask(__name__, instance_path='instance') diff --git a/tests/test_deprecations.py b/tests/test_deprecations.py index 81fba63b..f8935d08 100644 --- a/tests/test_deprecations.py +++ b/tests/test_deprecations.py @@ -3,7 +3,7 @@ tests.deprecations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Tests deprecation support. + Tests deprecation support. Not used currently. :copyright: (c) 2014 by Armin Ronacher. :license: BSD, see LICENSE for more details. @@ -12,13 +12,3 @@ import flask import unittest from tests import TestFlask, catch_warnings - - -class TestDeprecations(TestFlask): - """not used currently""" - - -def suite(): - suite = unittest.TestSuite() - suite.addTest(unittest.makeSuite(TestDeprecations)) - return suite diff --git a/tests/test_examples.py b/tests/test_examples.py deleted file mode 100644 index e4f66325..00000000 --- a/tests/test_examples.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -""" - tests.examples - ~~~~~~~~~~~~~~~~~~~~~~~~ - - Tests the examples. - - :copyright: (c) 2014 by Armin Ronacher. - :license: BSD, see LICENSE for more details. -""" -import os -import unittest -from tests import add_to_path - - -def setup_path(): - example_path = os.path.join(os.path.dirname(__file__), - os.pardir, os.pardir, 'examples') - add_to_path(os.path.join(example_path, 'flaskr')) - add_to_path(os.path.join(example_path, 'minitwit')) - - -def suite(): - setup_path() - suite = unittest.TestSuite() - try: - from minitwit_tests import TestMiniTwit - except ImportError: - pass - else: - suite.addTest(unittest.makeSuite(TestMiniTwit)) - try: - from flaskr_tests import TestFlaskr - except ImportError: - pass - else: - suite.addTest(unittest.makeSuite(TestFlaskr)) - return suite diff --git a/tests/test_helpers.py b/tests/test_helpers.py index d1091729..652378a1 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -29,7 +29,7 @@ def has_encoding(name): return False -class TestJSON(TestFlask): +class TestJSON(object): def test_json_bad_requests(self): app = flask.Flask(__name__) @@ -241,7 +241,7 @@ class TestJSON(TestFlask): except AssertionError: assert lines == sorted_by_str -class TestSendfile(TestFlask): +class TestSendfile(object): def test_send_file_regular(self): app = flask.Flask(__name__) @@ -423,7 +423,7 @@ class TestSendfile(TestFlask): rv.close() -class TestLogging(TestFlask): +class TestLogging(object): def test_logger_cache(self): app = flask.Flask(__name__) @@ -566,7 +566,7 @@ class TestLogging(TestFlask): assert flask.url_for('myview', _method='POST') == '/myview/create' -class TestNoImports(TestFlask): +class TestNoImports(object): """Test Flasks are created without import. Avoiding ``__import__`` helps create Flask instances where there are errors @@ -584,7 +584,7 @@ class TestNoImports(TestFlask): assert False, 'Flask(import_name) is importing import_name.' -class TestStreaming(TestFlask): +class TestStreaming(object): def test_streaming_with_context(self): app = flask.Flask(__name__) @@ -641,14 +641,3 @@ class TestStreaming(TestFlask): rv = c.get('/?name=World') assert rv.data == b'Hello World!' assert called == [42] - - -def suite(): - suite = unittest.TestSuite() - if flask.json_available: - suite.addTest(unittest.makeSuite(TestJSON)) - suite.addTest(unittest.makeSuite(TestSendfile)) - suite.addTest(unittest.makeSuite(TestLogging)) - suite.addTest(unittest.makeSuite(TestNoImports)) - suite.addTest(unittest.makeSuite(TestStreaming)) - return suite diff --git a/tests/test_regression.py b/tests/test_regression.py index e9616101..1671f2fa 100644 --- a/tests/test_regression.py +++ b/tests/test_regression.py @@ -54,7 +54,7 @@ class _NoLeakAsserter(object): @pytest.mark.skipif(os.environ.get('RUN_FLASK_MEMORY_TESTS') != '1', reason='Turned off due to envvar.') -class TestMemory(TestFlask): +class TestMemory(object): def assert_no_leak(self): return _NoLeakAsserter(self) @@ -88,7 +88,7 @@ class TestMemory(TestFlask): safe_join('/foo', '..') -class TestException(TestFlask): +class TestException(object): def test_aborting(self): class Foo(Exception): diff --git a/tests/test_reqctx.py b/tests/test_reqctx.py index ae3791b9..5bffbc19 100644 --- a/tests/test_reqctx.py +++ b/tests/test_reqctx.py @@ -20,177 +20,166 @@ except ImportError: from tests import TestFlask -class TestRequestContext(TestFlask): +def test_teardown_on_pop(): + buffer = [] + app = flask.Flask(__name__) + @app.teardown_request + def end_of_request(exception): + buffer.append(exception) + + ctx = app.test_request_context() + ctx.push() + assert buffer == [] + ctx.pop() + assert buffer == [None] + +def test_teardown_with_previous_exception(): + buffer = [] + app = flask.Flask(__name__) + @app.teardown_request + def end_of_request(exception): + buffer.append(exception) + + try: + raise Exception('dummy') + except Exception: + pass + + with app.test_request_context(): + assert buffer == [] + assert buffer == [None] - def test_teardown_on_pop(self): - buffer = [] - app = flask.Flask(__name__) - @app.teardown_request - def end_of_request(exception): - buffer.append(exception) +def test_proper_test_request_context(): + app = flask.Flask(__name__) + app.config.update( + SERVER_NAME='localhost.localdomain:5000' + ) - ctx = app.test_request_context() - ctx.push() - assert buffer == [] - ctx.pop() - assert buffer == [None] - - def test_teardown_with_previous_exception(self): - buffer = [] - app = flask.Flask(__name__) - @app.teardown_request - def end_of_request(exception): - buffer.append(exception) - - try: - raise Exception('dummy') - except Exception: - pass + @app.route('/') + def index(): + return None - with app.test_request_context(): - assert buffer == [] - assert buffer == [None] + @app.route('/', subdomain='foo') + def sub(): + return None - def test_proper_test_request_context(self): - app = flask.Flask(__name__) - app.config.update( - SERVER_NAME='localhost.localdomain:5000' - ) + with app.test_request_context('/'): + assert flask.url_for('index', _external=True) == \ + 'http://localhost.localdomain:5000/' - @app.route('/') - def index(): - return None - - @app.route('/', subdomain='foo') - def sub(): - return None - - with app.test_request_context('/'): - assert flask.url_for('index', _external=True) == \ - 'http://localhost.localdomain:5000/' - - with app.test_request_context('/'): - assert flask.url_for('sub', _external=True) == \ - 'http://foo.localhost.localdomain:5000/' - - try: - with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}): - pass - except ValueError as e: - assert str(e) == ( - "the server name provided " - "('localhost.localdomain:5000') does not match the " - "server name from the WSGI environment ('localhost')" - ) - - app.config.update(SERVER_NAME='localhost') - with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}): - pass + with app.test_request_context('/'): + assert flask.url_for('sub', _external=True) == \ + 'http://foo.localhost.localdomain:5000/' - app.config.update(SERVER_NAME='localhost:80') - with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}): + try: + with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}): pass + except ValueError as e: + assert str(e) == ( + "the server name provided " + "('localhost.localdomain:5000') does not match the " + "server name from the WSGI environment ('localhost')" + ) - def test_context_binding(self): - app = flask.Flask(__name__) - @app.route('/') - def index(): - return 'Hello %s!' % flask.request.args['name'] - @app.route('/meh') - def meh(): - return flask.request.url - - with app.test_request_context('/?name=World'): - assert index() == 'Hello World!' - with app.test_request_context('/meh'): - assert meh() == 'http://localhost/meh' - assert flask._request_ctx_stack.top is None - - def test_context_test(self): - app = flask.Flask(__name__) - assert not flask.request - assert not flask.has_request_context() - ctx = app.test_request_context() - ctx.push() - try: - assert flask.request - assert flask.has_request_context() - finally: - ctx.pop() - - def test_manual_context_binding(self): - app = flask.Flask(__name__) - @app.route('/') - def index(): - return 'Hello %s!' % flask.request.args['name'] - - ctx = app.test_request_context('/?name=World') - ctx.push() + app.config.update(SERVER_NAME='localhost') + with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}): + pass + + app.config.update(SERVER_NAME='localhost:80') + with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}): + pass + +def test_context_binding(): + app = flask.Flask(__name__) + @app.route('/') + def index(): + return 'Hello %s!' % flask.request.args['name'] + @app.route('/meh') + def meh(): + return flask.request.url + + with app.test_request_context('/?name=World'): assert index() == 'Hello World!' + with app.test_request_context('/meh'): + assert meh() == 'http://localhost/meh' + assert flask._request_ctx_stack.top is None + +def test_context_test(): + app = flask.Flask(__name__) + assert not flask.request + assert not flask.has_request_context() + ctx = app.test_request_context() + ctx.push() + try: + assert flask.request + assert flask.has_request_context() + finally: ctx.pop() - try: - index() - except RuntimeError: - pass - else: - assert 0, 'expected runtime error' - - def test_greenlet_context_copying(self): - app = flask.Flask(__name__) - greenlets = [] - - @app.route('/') - def index(): - reqctx = flask._request_ctx_stack.top.copy() - def g(): - assert not flask.request - assert not flask.current_app - with reqctx: - assert flask.request - assert flask.current_app == app - assert flask.request.path == '/' - assert flask.request.args['foo'] == 'bar' - assert not flask.request - return 42 - greenlets.append(greenlet(g)) - return 'Hello World!' - - rv = app.test_client().get('/?foo=bar') - assert rv.data == b'Hello World!' - - result = greenlets[0].run() - assert result == 42 - - def test_greenlet_context_copying_api(self): - app = flask.Flask(__name__) - greenlets = [] - - @app.route('/') - def index(): - reqctx = flask._request_ctx_stack.top.copy() - @flask.copy_current_request_context - def g(): + +def test_manual_context_binding(): + app = flask.Flask(__name__) + @app.route('/') + def index(): + return 'Hello %s!' % flask.request.args['name'] + + ctx = app.test_request_context('/?name=World') + ctx.push() + assert index() == 'Hello World!' + ctx.pop() + try: + index() + except RuntimeError: + pass + else: + assert 0, 'expected runtime error' + +@pytest.mark.skipif(greenlet is None, reason='greenlet not installed') +def test_greenlet_context_copying(): + app = flask.Flask(__name__) + greenlets = [] + + @app.route('/') + def index(): + reqctx = flask._request_ctx_stack.top.copy() + def g(): + assert not flask.request + assert not flask.current_app + with reqctx: assert flask.request assert flask.current_app == app assert flask.request.path == '/' assert flask.request.args['foo'] == 'bar' - return 42 - greenlets.append(greenlet(g)) - return 'Hello World!' - - rv = app.test_client().get('/?foo=bar') - assert rv.data == b'Hello World!' - - result = greenlets[0].run() - assert result == 42 - - # Disable test if we don't have greenlets available - if greenlet is None: - test_greenlet_context_copying = None - test_greenlet_context_copying_api = None - - -def suite(): - suite = unittest.TestSuite() - suite.addTest(unittest.makeSuite(TestRequestContext)) - return suite + assert not flask.request + return 42 + greenlets.append(greenlet(g)) + return 'Hello World!' + + rv = app.test_client().get('/?foo=bar') + assert rv.data == b'Hello World!' + + result = greenlets[0].run() + assert result == 42 + +@pytest.mark.skipif(greenlet is None, reason='greenlet not installed') +def test_greenlet_context_copying_api(): + app = flask.Flask(__name__) + greenlets = [] + + @app.route('/') + def index(): + reqctx = flask._request_ctx_stack.top.copy() + @flask.copy_current_request_context + def g(): + assert flask.request + assert flask.current_app == app + assert flask.request.path == '/' + assert flask.request.args['foo'] == 'bar' + return 42 + greenlets.append(greenlet(g)) + return 'Hello World!' + + rv = app.test_client().get('/?foo=bar') + assert rv.data == b'Hello World!' + + result = greenlets[0].run() + assert result == 42 diff --git a/tests/test_signals.py b/tests/test_signals.py index c88042d0..c76896fb 100644 --- a/tests/test_signals.py +++ b/tests/test_signals.py @@ -25,136 +25,134 @@ pytestmark = pytest.mark.skipif( reason='Signals require the blinker library.' ) -class TestSignals(TestFlask): - - def test_template_rendered(self): - app = flask.Flask(__name__) - - @app.route('/') - def index(): - return flask.render_template('simple_template.html', whiskey=42) - - recorded = [] - - def record(sender, template, context): - recorded.append((template, context)) - - flask.template_rendered.connect(record, app) - try: - app.test_client().get('/') - assert len(recorded) == 1 - template, context = recorded[0] - assert template.name == 'simple_template.html' - assert context['whiskey'] == 42 - finally: - flask.template_rendered.disconnect(record, app) - - def test_request_signals(self): - app = flask.Flask(__name__) - calls = [] - - def before_request_signal(sender): - calls.append('before-signal') - - def after_request_signal(sender, response): - assert response.data == b'stuff' - calls.append('after-signal') - - @app.before_request - def before_request_handler(): - calls.append('before-handler') - - @app.after_request - def after_request_handler(response): - calls.append('after-handler') - response.data = 'stuff' - return response - - @app.route('/') - def index(): - calls.append('handler') - return 'ignored anyway' - - flask.request_started.connect(before_request_signal, app) - flask.request_finished.connect(after_request_signal, app) - - try: - rv = app.test_client().get('/') - assert rv.data == b'stuff' - - assert calls == ['before-signal', 'before-handler', 'handler', - 'after-handler', 'after-signal'] - finally: - flask.request_started.disconnect(before_request_signal, app) - flask.request_finished.disconnect(after_request_signal, app) - - def test_request_exception_signal(self): - app = flask.Flask(__name__) - recorded = [] - - @app.route('/') - def index(): - 1 // 0 - - def record(sender, exception): - recorded.append(exception) - - flask.got_request_exception.connect(record, app) - try: - assert app.test_client().get('/').status_code == 500 +def test_template_rendered(): + app = flask.Flask(__name__) + + @app.route('/') + def index(): + return flask.render_template('simple_template.html', whiskey=42) + + recorded = [] + + def record(sender, template, context): + recorded.append((template, context)) + + flask.template_rendered.connect(record, app) + try: + app.test_client().get('/') + assert len(recorded) == 1 + template, context = recorded[0] + assert template.name == 'simple_template.html' + assert context['whiskey'] == 42 + finally: + flask.template_rendered.disconnect(record, app) + +def test_request_signals(): + app = flask.Flask(__name__) + calls = [] + + def before_request_signal(sender): + calls.append('before-signal') + + def after_request_signal(sender, response): + assert response.data == b'stuff' + calls.append('after-signal') + + @app.before_request + def before_request_handler(): + calls.append('before-handler') + + @app.after_request + def after_request_handler(response): + calls.append('after-handler') + response.data = 'stuff' + return response + + @app.route('/') + def index(): + calls.append('handler') + return 'ignored anyway' + + flask.request_started.connect(before_request_signal, app) + flask.request_finished.connect(after_request_signal, app) + + try: + rv = app.test_client().get('/') + assert rv.data == b'stuff' + + assert calls == ['before-signal', 'before-handler', 'handler', + 'after-handler', 'after-signal'] + finally: + flask.request_started.disconnect(before_request_signal, app) + flask.request_finished.disconnect(after_request_signal, app) + +def test_request_exception_signal(): + app = flask.Flask(__name__) + recorded = [] + + @app.route('/') + def index(): + 1 // 0 + + def record(sender, exception): + recorded.append(exception) + + flask.got_request_exception.connect(record, app) + try: + assert app.test_client().get('/').status_code == 500 + assert len(recorded) == 1 + assert isinstance(recorded[0], ZeroDivisionError) + finally: + flask.got_request_exception.disconnect(record, app) + +def test_appcontext_signals(): + app = flask.Flask(__name__) + recorded = [] + + def record_push(sender, **kwargs): + recorded.append('push') + + def record_pop(sender, **kwargs): + recorded.append('pop') + + @app.route('/') + def index(): + return 'Hello' + + flask.appcontext_pushed.connect(record_push, app) + flask.appcontext_popped.connect(record_pop, app) + try: + with app.test_client() as c: + rv = c.get('/') + assert rv.data == b'Hello' + assert recorded == ['push'] + assert recorded == ['push', 'pop'] + finally: + flask.appcontext_pushed.disconnect(record_push, app) + flask.appcontext_popped.disconnect(record_pop, app) + +def test_flash_signal(): + app = flask.Flask(__name__) + app.config['SECRET_KEY'] = 'secret' + + @app.route('/') + def index(): + flask.flash('This is a flash message', category='notice') + return flask.redirect('/other') + + recorded = [] + + def record(sender, message, category): + recorded.append((message, category)) + + flask.message_flashed.connect(record, app) + try: + client = app.test_client() + with client.session_transaction(): + client.get('/') assert len(recorded) == 1 - assert isinstance(recorded[0], ZeroDivisionError) - finally: - flask.got_request_exception.disconnect(record, app) - - def test_appcontext_signals(self): - app = flask.Flask(__name__) - recorded = [] - - def record_push(sender, **kwargs): - recorded.append('push') - - def record_pop(sender, **kwargs): - recorded.append('pop') - - @app.route('/') - def index(): - return 'Hello' - - flask.appcontext_pushed.connect(record_push, app) - flask.appcontext_popped.connect(record_pop, app) - try: - with app.test_client() as c: - rv = c.get('/') - assert rv.data == b'Hello' - assert recorded == ['push'] - assert recorded == ['push', 'pop'] - finally: - flask.appcontext_pushed.disconnect(record_push, app) - flask.appcontext_popped.disconnect(record_pop, app) - - def test_flash_signal(self): - app = flask.Flask(__name__) - app.config['SECRET_KEY'] = 'secret' - - @app.route('/') - def index(): - flask.flash('This is a flash message', category='notice') - return flask.redirect('/other') - - recorded = [] - - def record(sender, message, category): - recorded.append((message, category)) - - flask.message_flashed.connect(record, app) - try: - client = app.test_client() - with client.session_transaction(): - client.get('/') - assert len(recorded) == 1 - message, category = recorded[0] - assert message == 'This is a flash message' - assert category == 'notice' - finally: - flask.message_flashed.disconnect(record, app) + message, category = recorded[0] + assert message == 'This is a flash message' + assert category == 'notice' + finally: + flask.message_flashed.disconnect(record, app) diff --git a/tests/test_testing.py b/tests/test_testing.py index 058aee3d..deabd6bb 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -16,7 +16,7 @@ from tests import TestFlask from flask._compat import text_type -class TestTestTools(TestFlask): +class TestTestTools(object): def test_environ_defaults_from_config(self): app = flask.Flask(__name__) @@ -213,7 +213,7 @@ class TestTestTools(TestFlask): assert 'vodka' in flask.request.args -class TestSubdomain(TestFlask): +class TestSubdomain(object): @pytest.fixture def app(self, request):