From 5b0b9717da958fd6325c675d92be4f6667796112 Mon Sep 17 00:00:00 2001 From: Christian Stade-Schuldt Date: Tue, 23 May 2017 15:18:39 -0700 Subject: [PATCH] DRYing up the test suite using pytest fixtures (#2306) * add fixtures to conftest.py * use fixtures in test_appctx.py * use fixtures in test_blueprints.py * use fixtures in test_depreciations.py * use fixtures in test_regressions.py * use fixtures in test_reqctx.py * use fixtures in test_templating.py * use fixtures in test_user_error_handler.py * use fixtures in test_views.py * use fixtures in test_basics.py * use fixtures in test_helpers.py * use fixtures in test_testing.py * update conftest.py * make docstrings PEP-257 compliant * cleanup * switch dictonary format * use pytest parameterization for test_json_as_unicode --- tests/conftest.py | 52 ++- tests/test_appctx.py | 96 ++--- tests/test_basic.py | 487 +++++++++++------------- tests/test_blueprints.py | 280 ++++++++------ tests/test_deprecations.py | 13 +- tests/test_helpers.py | 615 +++++++++++++++---------------- tests/test_regression.py | 7 +- tests/test_reqctx.py | 51 +-- tests/test_templating.py | 210 ++++++----- tests/test_testing.py | 96 ++--- tests/test_user_error_handler.py | 22 +- tests/test_views.py | 44 ++- 12 files changed, 999 insertions(+), 974 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index eb130db6..40b1e88f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -13,6 +13,40 @@ import sys import pkgutil import pytest import textwrap +from flask import Flask as _Flask + + +class Flask(_Flask): + testing = True + secret_key = __name__ + + def make_response(self, rv): + if rv is None: + rv = '' + return super(Flask, self).make_response(rv) + + +@pytest.fixture +def app(): + app = Flask(__name__) + return app + + +@pytest.fixture +def app_ctx(app): + with app.app_context() as ctx: + yield ctx + + +@pytest.fixture +def req_ctx(app): + with app.test_request_context() as ctx: + yield ctx + + +@pytest.fixture +def client(app): + return app.test_client() @pytest.fixture @@ -63,12 +97,13 @@ def limit_loader(request, monkeypatch): def get_loader(*args, **kwargs): return LimitedLoader(old_get_loader(*args, **kwargs)) + monkeypatch.setattr(pkgutil, 'get_loader', get_loader) @pytest.fixture def modules_tmpdir(tmpdir, monkeypatch): - '''A tmpdir added to sys.path''' + """A tmpdir added to sys.path.""" rv = tmpdir.mkdir('modules_tmpdir') monkeypatch.syspath_prepend(str(rv)) return rv @@ -82,10 +117,10 @@ def modules_tmpdir_prefix(modules_tmpdir, monkeypatch): @pytest.fixture def site_packages(modules_tmpdir, monkeypatch): - '''Create a fake site-packages''' + """Create a fake site-packages.""" rv = modules_tmpdir \ - .mkdir('lib')\ - .mkdir('python{x[0]}.{x[1]}'.format(x=sys.version_info))\ + .mkdir('lib') \ + .mkdir('python{x[0]}.{x[1]}'.format(x=sys.version_info)) \ .mkdir('site-packages') monkeypatch.syspath_prepend(str(rv)) return rv @@ -93,8 +128,9 @@ def site_packages(modules_tmpdir, monkeypatch): @pytest.fixture def install_egg(modules_tmpdir, monkeypatch): - '''Generate egg from package name inside base and put the egg into - sys.path''' + """Generate egg from package name inside base and put the egg into + sys.path.""" + def inner(name, base=modules_tmpdir): if not isinstance(name, str): raise ValueError(name) @@ -118,6 +154,7 @@ def install_egg(modules_tmpdir, monkeypatch): egg_path, = modules_tmpdir.join('dist/').listdir() monkeypatch.syspath_prepend(str(egg_path)) return egg_path + return inner @@ -125,6 +162,7 @@ def install_egg(modules_tmpdir, monkeypatch): def purge_module(request): def inner(name): request.addfinalizer(lambda: sys.modules.pop(name, None)) + return inner @@ -132,4 +170,4 @@ def purge_module(request): def catch_deprecation_warnings(recwarn): yield gc.collect() - assert not recwarn.list + assert not recwarn.list, '\n'.join(str(w.message) for w in recwarn.list) diff --git a/tests/test_appctx.py b/tests/test_appctx.py index 13b61eee..7ef7b479 100644 --- a/tests/test_appctx.py +++ b/tests/test_appctx.py @@ -14,8 +14,7 @@ import pytest import flask -def test_basic_url_generation(): - app = flask.Flask(__name__) +def test_basic_url_generation(app): app.config['SERVER_NAME'] = 'localhost' app.config['PREFERRED_URL_SCHEME'] = 'https' @@ -27,31 +26,33 @@ def test_basic_url_generation(): rv = flask.url_for('index') assert rv == 'https://localhost/' -def test_url_generation_requires_server_name(): - app = flask.Flask(__name__) + +def test_url_generation_requires_server_name(app): with app.app_context(): with pytest.raises(RuntimeError): flask.url_for('index') + def test_url_generation_without_context_fails(): with pytest.raises(RuntimeError): flask.url_for('index') -def test_request_context_means_app_context(): - app = flask.Flask(__name__) + +def test_request_context_means_app_context(app): with app.test_request_context(): assert flask.current_app._get_current_object() == app assert flask._app_ctx_stack.top is None -def test_app_context_provides_current_app(): - app = flask.Flask(__name__) + +def test_app_context_provides_current_app(app): with app.app_context(): assert flask.current_app._get_current_object() == app assert flask._app_ctx_stack.top is None -def test_app_tearing_down(): + +def test_app_tearing_down(app): cleanup_stuff = [] - app = flask.Flask(__name__) + @app.teardown_appcontext def cleanup(exception): cleanup_stuff.append(exception) @@ -61,9 +62,10 @@ def test_app_tearing_down(): assert cleanup_stuff == [None] -def test_app_tearing_down_with_previous_exception(): + +def test_app_tearing_down_with_previous_exception(app): cleanup_stuff = [] - app = flask.Flask(__name__) + @app.teardown_appcontext def cleanup(exception): cleanup_stuff.append(exception) @@ -78,9 +80,10 @@ def test_app_tearing_down_with_previous_exception(): assert cleanup_stuff == [None] -def test_app_tearing_down_with_handled_exception(): + +def test_app_tearing_down_with_handled_exception(app): cleanup_stuff = [] - app = flask.Flask(__name__) + @app.teardown_appcontext def cleanup(exception): cleanup_stuff.append(exception) @@ -93,46 +96,49 @@ def test_app_tearing_down_with_handled_exception(): assert cleanup_stuff == [None] -def test_app_ctx_globals_methods(): - app = flask.Flask(__name__) - with app.app_context(): - # get - assert flask.g.get('foo') is None - assert flask.g.get('foo', 'bar') == 'bar' - # __contains__ - assert 'foo' not in flask.g - flask.g.foo = 'bar' - assert 'foo' in flask.g - # setdefault - flask.g.setdefault('bar', 'the cake is a lie') - flask.g.setdefault('bar', 'hello world') - assert flask.g.bar == 'the cake is a lie' - # pop - assert flask.g.pop('bar') == 'the cake is a lie' - with pytest.raises(KeyError): - flask.g.pop('bar') - assert flask.g.pop('bar', 'more cake') == 'more cake' - # __iter__ - assert list(flask.g) == ['foo'] - -def test_custom_app_ctx_globals_class(): + +def test_app_ctx_globals_methods(app, app_ctx): + # get + assert flask.g.get('foo') is None + assert flask.g.get('foo', 'bar') == 'bar' + # __contains__ + assert 'foo' not in flask.g + flask.g.foo = 'bar' + assert 'foo' in flask.g + # setdefault + flask.g.setdefault('bar', 'the cake is a lie') + flask.g.setdefault('bar', 'hello world') + assert flask.g.bar == 'the cake is a lie' + # pop + assert flask.g.pop('bar') == 'the cake is a lie' + with pytest.raises(KeyError): + flask.g.pop('bar') + assert flask.g.pop('bar', 'more cake') == 'more cake' + # __iter__ + assert list(flask.g) == ['foo'] + + +def test_custom_app_ctx_globals_class(app): class CustomRequestGlobals(object): def __init__(self): self.spam = 'eggs' - app = flask.Flask(__name__) + app.app_ctx_globals_class = CustomRequestGlobals with app.app_context(): assert flask.render_template_string('{{ g.spam }}') == 'eggs' -def test_context_refcounts(): + +def test_context_refcounts(app, client): called = [] - app = flask.Flask(__name__) + @app.teardown_request def teardown_req(error=None): called.append('request') + @app.teardown_appcontext def teardown_app(error=None): called.append('app') + @app.route('/') def index(): with flask._app_ctx_stack.top: @@ -141,16 +147,16 @@ def test_context_refcounts(): env = flask._request_ctx_stack.top.request.environ assert env['werkzeug.request'] is not None return u'' - c = app.test_client() - res = c.get('/') + + res = client.get('/') assert res.status_code == 200 assert res.data == b'' assert called == ['request', 'app'] -def test_clean_pop(): +def test_clean_pop(app): + app.testing = False called = [] - app = flask.Flask(__name__) @app.teardown_request def teardown_req(error=None): @@ -166,5 +172,5 @@ def test_clean_pop(): except ZeroDivisionError: pass - assert called == ['test_appctx', 'TEARDOWN'] + assert called == ['conftest', 'TEARDOWN'] assert not flask.current_app diff --git a/tests/test_basic.py b/tests/test_basic.py index 54f4c8e6..9d72f6d1 100644 --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -25,20 +25,17 @@ from werkzeug.routing import BuildError import werkzeug.serving -def test_options_work(): - app = flask.Flask(__name__) - +def test_options_work(app, client): @app.route('/', methods=['GET', 'POST']) def index(): return 'Hello World' - rv = app.test_client().open('/', method='OPTIONS') + + rv = client.open('/', method='OPTIONS') assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST'] assert rv.data == b'' -def test_options_on_multiple_rules(): - app = flask.Flask(__name__) - +def test_options_on_multiple_rules(app, client): @app.route('/', methods=['GET', 'POST']) def index(): return 'Hello World' @@ -46,7 +43,8 @@ def test_options_on_multiple_rules(): @app.route('/', methods=['PUT']) def index_put(): return 'Aha!' - rv = app.test_client().open('/', method='OPTIONS') + + rv = client.open('/', method='OPTIONS') assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'] @@ -55,6 +53,7 @@ def test_provide_automatic_options_attr(): def index(): return 'Hello World!' + index.provide_automatic_options = False app.route('/')(index) rv = app.test_client().open('/', method='OPTIONS') @@ -64,15 +63,14 @@ def test_provide_automatic_options_attr(): def index2(): return 'Hello World!' + index2.provide_automatic_options = True app.route('/', methods=['OPTIONS'])(index2) rv = app.test_client().open('/', method='OPTIONS') assert sorted(rv.allow) == ['OPTIONS'] -def test_provide_automatic_options_kwarg(): - app = flask.Flask(__name__) - +def test_provide_automatic_options_kwarg(app, client): def index(): return flask.request.method @@ -84,43 +82,39 @@ def test_provide_automatic_options_kwarg(): '/more', view_func=more, methods=['GET', 'POST'], provide_automatic_options=False ) + assert client.get('/').data == b'GET' - c = app.test_client() - assert c.get('/').data == b'GET' - - rv = c.post('/') + rv = client.post('/') assert rv.status_code == 405 assert sorted(rv.allow) == ['GET', 'HEAD'] # Older versions of Werkzeug.test.Client don't have an options method - if hasattr(c, 'options'): - rv = c.options('/') + if hasattr(client, 'options'): + rv = client.options('/') else: - rv = c.open('/', method='OPTIONS') + rv = client.open('/', method='OPTIONS') assert rv.status_code == 405 - rv = c.head('/') + rv = client.head('/') assert rv.status_code == 200 assert not rv.data # head truncates - assert c.post('/more').data == b'POST' - assert c.get('/more').data == b'GET' + assert client.post('/more').data == b'POST' + assert client.get('/more').data == b'GET' - rv = c.delete('/more') + rv = client.delete('/more') assert rv.status_code == 405 assert sorted(rv.allow) == ['GET', 'HEAD', 'POST'] - if hasattr(c, 'options'): - rv = c.options('/more') + if hasattr(client, 'options'): + rv = client.options('/more') else: - rv = c.open('/more', method='OPTIONS') + rv = client.open('/more', method='OPTIONS') assert rv.status_code == 405 -def test_request_dispatching(): - app = flask.Flask(__name__) - +def test_request_dispatching(app, client): @app.route('/') def index(): return flask.request.method @@ -129,32 +123,28 @@ def test_request_dispatching(): def more(): return flask.request.method - c = app.test_client() - assert c.get('/').data == b'GET' - rv = c.post('/') + assert client.get('/').data == b'GET' + rv = client.post('/') assert rv.status_code == 405 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS'] - rv = c.head('/') + rv = client.head('/') assert rv.status_code == 200 assert not rv.data # head truncates - assert c.post('/more').data == b'POST' - assert c.get('/more').data == b'GET' - rv = c.delete('/more') + assert client.post('/more').data == b'POST' + assert client.get('/more').data == b'GET' + rv = client.delete('/more') assert rv.status_code == 405 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST'] -def test_disallow_string_for_allowed_methods(): - app = flask.Flask(__name__) +def test_disallow_string_for_allowed_methods(app): with pytest.raises(TypeError): @app.route('/', methods='GET POST') def index(): return "Hey" -def test_url_mapping(): - app = flask.Flask(__name__) - +def test_url_mapping(app, client): random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383" def index(): @@ -166,34 +156,31 @@ def test_url_mapping(): def options(): return random_uuid4 - app.add_url_rule('/', 'index', index) app.add_url_rule('/more', 'more', more, methods=['GET', 'POST']) # Issue 1288: Test that automatic options are not added when non-uppercase 'options' in methods app.add_url_rule('/options', 'options', options, methods=['options']) - c = app.test_client() - assert c.get('/').data == b'GET' - rv = c.post('/') + assert client.get('/').data == b'GET' + rv = client.post('/') assert rv.status_code == 405 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS'] - rv = c.head('/') + rv = client.head('/') assert rv.status_code == 200 assert not rv.data # head truncates - assert c.post('/more').data == b'POST' - assert c.get('/more').data == b'GET' - rv = c.delete('/more') + assert client.post('/more').data == b'POST' + assert client.get('/more').data == b'GET' + rv = client.delete('/more') assert rv.status_code == 405 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST'] - rv = c.open('/options', method='OPTIONS') + rv = client.open('/options', method='OPTIONS') assert rv.status_code == 200 assert random_uuid4 in rv.data.decode("utf-8") -def test_werkzeug_routing(): +def test_werkzeug_routing(app, client): from werkzeug.routing import Submount, Rule - app = flask.Flask(__name__) app.url_map.add(Submount('/foo', [ Rule('/bar', endpoint='bar'), Rule('/', endpoint='index') @@ -204,17 +191,16 @@ def test_werkzeug_routing(): def index(): return 'index' + app.view_functions['bar'] = bar app.view_functions['index'] = index - c = app.test_client() - assert c.get('/foo/').data == b'index' - assert c.get('/foo/bar').data == b'bar' + assert client.get('/foo/').data == b'index' + assert client.get('/foo/bar').data == b'bar' -def test_endpoint_decorator(): +def test_endpoint_decorator(app, client): from werkzeug.routing import Submount, Rule - app = flask.Flask(__name__) app.url_map.add(Submount('/foo', [ Rule('/bar', endpoint='bar'), Rule('/', endpoint='index') @@ -228,13 +214,11 @@ def test_endpoint_decorator(): def index(): return 'index' - c = app.test_client() - assert c.get('/foo/').data == b'index' - assert c.get('/foo/bar').data == b'bar' + assert client.get('/foo/').data == b'index' + assert client.get('/foo/bar').data == b'bar' -def test_session(): - app = flask.Flask(__name__) +def test_session(app, client): app.secret_key = 'testkey' @app.route('/set', methods=['POST']) @@ -246,13 +230,11 @@ def test_session(): def get(): return flask.session['value'] - c = app.test_client() - assert c.post('/set', data={'value': '42'}).data == b'value set' - assert c.get('/get').data == b'42' + assert client.post('/set', data={'value': '42'}).data == b'value set' + assert client.get('/get').data == b'42' -def test_session_using_server_name(): - app = flask.Flask(__name__) +def test_session_using_server_name(app, client): app.config.update( SECRET_KEY='foo', SERVER_NAME='example.com' @@ -262,13 +244,13 @@ def test_session_using_server_name(): def index(): flask.session['testing'] = 42 return 'Hello World' - rv = app.test_client().get('/', 'http://example.com/') + + rv = client.get('/', 'http://example.com/') assert 'domain=.example.com' in rv.headers['set-cookie'].lower() assert 'httponly' in rv.headers['set-cookie'].lower() -def test_session_using_server_name_and_port(): - app = flask.Flask(__name__) +def test_session_using_server_name_and_port(app, client): app.config.update( SECRET_KEY='foo', SERVER_NAME='example.com:8080' @@ -278,13 +260,13 @@ def test_session_using_server_name_and_port(): def index(): flask.session['testing'] = 42 return 'Hello World' - rv = app.test_client().get('/', 'http://example.com:8080/') + + rv = client.get('/', 'http://example.com:8080/') assert 'domain=.example.com' in rv.headers['set-cookie'].lower() assert 'httponly' in rv.headers['set-cookie'].lower() -def test_session_using_server_name_port_and_path(): - app = flask.Flask(__name__) +def test_session_using_server_name_port_and_path(app, client): app.config.update( SECRET_KEY='foo', SERVER_NAME='example.com:8080', @@ -295,15 +277,15 @@ def test_session_using_server_name_port_and_path(): def index(): flask.session['testing'] = 42 return 'Hello World' - rv = app.test_client().get('/', 'http://example.com:8080/foo') + + rv = client.get('/', 'http://example.com:8080/foo') assert 'domain=example.com' in rv.headers['set-cookie'].lower() assert 'path=/foo' in rv.headers['set-cookie'].lower() assert 'httponly' in rv.headers['set-cookie'].lower() -def test_session_using_application_root(): +def test_session_using_application_root(app, client): class PrefixPathMiddleware(object): - def __init__(self, app, prefix): self.app = app self.prefix = prefix @@ -312,7 +294,6 @@ def test_session_using_application_root(): environ['SCRIPT_NAME'] = self.prefix return self.app(environ, start_response) - app = flask.Flask(__name__) app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar') app.config.update( SECRET_KEY='foo', @@ -323,12 +304,12 @@ def test_session_using_application_root(): def index(): flask.session['testing'] = 42 return 'Hello World' - rv = app.test_client().get('/', 'http://example.com:8080/') + + rv = client.get('/', 'http://example.com:8080/') assert 'path=/bar' in rv.headers['set-cookie'].lower() -def test_session_using_session_settings(): - app = flask.Flask(__name__) +def test_session_using_session_settings(app, client): app.config.update( SECRET_KEY='foo', SERVER_NAME='www.example.com:8080', @@ -343,7 +324,8 @@ def test_session_using_session_settings(): def index(): flask.session['testing'] = 42 return 'Hello World' - rv = app.test_client().get('/', 'http://www.example.com:8080/test/') + + rv = client.get('/', 'http://www.example.com:8080/test/') cookie = rv.headers['set-cookie'].lower() assert 'domain=.example.com' in cookie assert 'path=/' in cookie @@ -351,8 +333,7 @@ def test_session_using_session_settings(): assert 'httponly' not in cookie -def test_session_localhost_warning(recwarn): - app = flask.Flask(__name__) +def test_session_localhost_warning(recwarn, app, client): app.config.update( SECRET_KEY='testing', SERVER_NAME='localhost:5000', @@ -363,14 +344,13 @@ def test_session_localhost_warning(recwarn): flask.session['testing'] = 42 return 'testing' - rv = app.test_client().get('/', 'http://localhost:5000/') + rv = client.get('/', 'http://localhost:5000/') assert 'domain' not in rv.headers['set-cookie'].lower() w = recwarn.pop(UserWarning) assert '"localhost" is not a valid cookie domain' in str(w.message) -def test_session_ip_warning(recwarn): - app = flask.Flask(__name__) +def test_session_ip_warning(recwarn, app, client): app.config.update( SECRET_KEY='testing', SERVER_NAME='127.0.0.1:5000', @@ -381,7 +361,7 @@ def test_session_ip_warning(recwarn): flask.session['testing'] = 42 return 'testing' - rv = app.test_client().get('/', 'http://127.0.0.1:5000/') + rv = client.get('/', 'http://127.0.0.1:5000/') assert 'domain=127.0.0.1' in rv.headers['set-cookie'].lower() w = recwarn.pop(UserWarning) assert 'cookie domain is an IP' in str(w.message) @@ -393,15 +373,15 @@ def test_missing_session(): def expect_exception(f, *args, **kwargs): e = pytest.raises(RuntimeError, f, *args, **kwargs) assert e.value.args and 'session is unavailable' in e.value.args[0] + with app.test_request_context(): assert flask.session.get('missing_key') is None expect_exception(flask.session.__setitem__, 'foo', 42) expect_exception(flask.session.pop, 'foo') -def test_session_expiration(): +def test_session_expiration(app, client): permanent = True - app = flask.Flask(__name__) app.secret_key = 'testkey' @app.route('/') @@ -414,7 +394,6 @@ def test_session_expiration(): def test(): return text_type(flask.session.permanent) - client = app.test_client() rv = client.get('/') assert 'set-cookie' in rv.headers match = re.search(r'(?i)\bexpires=([^;]+)', rv.headers['set-cookie']) @@ -428,16 +407,14 @@ def test_session_expiration(): assert rv.data == b'True' permanent = False - rv = app.test_client().get('/') + rv = client.get('/') assert 'set-cookie' in rv.headers match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie']) assert match is None -def test_session_stored_last(): - app = flask.Flask(__name__) +def test_session_stored_last(app, client): app.secret_key = 'development-key' - app.testing = True @app.after_request def modify_session(response): @@ -448,15 +425,12 @@ def test_session_stored_last(): def dump_session_contents(): return repr(flask.session.get('foo')) - c = app.test_client() - assert c.get('/').data == b'None' - assert c.get('/').data == b'42' + assert client.get('/').data == b'None' + assert client.get('/').data == b'42' -def test_session_special_types(): - app = flask.Flask(__name__) +def test_session_special_types(app, client): app.secret_key = 'development-key' - app.testing = True now = datetime.utcnow().replace(microsecond=0) the_uuid = uuid.uuid4() @@ -473,9 +447,8 @@ def test_session_special_types(): def dump_session_contents(): return pickle.dumps(dict(flask.session)) - c = app.test_client() - c.get('/') - rv = pickle.loads(c.get('/').data) + client.get('/') + rv = pickle.loads(client.get('/').data) assert rv['m'] == flask.Markup('Hello!') assert type(rv['m']) == flask.Markup assert rv['dt'] == now @@ -485,9 +458,7 @@ def test_session_special_types(): assert rv['t'] == (1, 2, 3) -def test_session_cookie_setting(): - app = flask.Flask(__name__) - app.testing = True +def test_session_cookie_setting(app): app.secret_key = 'dev key' is_permanent = True @@ -529,8 +500,7 @@ def test_session_cookie_setting(): run_test(expect_header=False) -def test_session_vary_cookie(): - app = flask.Flask(__name__) +def test_session_vary_cookie(app, client): app.secret_key = 'testkey' @app.route('/set') @@ -554,10 +524,8 @@ def test_session_vary_cookie(): def no_vary_header(): return '' - c = app.test_client() - def expect(path, header=True): - rv = c.get(path) + rv = client.get(path) if header: assert rv.headers['Vary'] == 'Cookie' @@ -571,29 +539,25 @@ def test_session_vary_cookie(): expect('/no-vary-header', False) -def test_flashes(): - app = flask.Flask(__name__) +def test_flashes(app, req_ctx): app.secret_key = 'testkey' - with app.test_request_context(): - assert not flask.session.modified - flask.flash('Zap') - flask.session.modified = False - flask.flash('Zip') - assert flask.session.modified - assert list(flask.get_flashed_messages()) == ['Zap', 'Zip'] + assert not flask.session.modified + flask.flash('Zap') + flask.session.modified = False + flask.flash('Zip') + assert flask.session.modified + assert list(flask.get_flashed_messages()) == ['Zap', 'Zip'] -def test_extended_flashing(): +def test_extended_flashing(app): # Be sure app.testing=True below, else tests can fail silently. # # Specifically, if app.testing is not set to True, the AssertionErrors # in the view functions will cause a 500 response to the test client # instead of propagating exceptions. - app = flask.Flask(__name__) app.secret_key = 'testkey' - app.testing = True @app.route('/') def index(): @@ -651,29 +615,24 @@ def test_extended_flashing(): # Create new test client on each test to clean flashed messages. - c = app.test_client() - c.get('/') - c.get('/test/') - - c = app.test_client() - c.get('/') - c.get('/test_with_categories/') + client = app.test_client() + client.get('/') + client.get('/test_with_categories/') - c = app.test_client() - c.get('/') - c.get('/test_filter/') + client = app.test_client() + client.get('/') + client.get('/test_filter/') - c = app.test_client() - c.get('/') - c.get('/test_filters/') + client = app.test_client() + client.get('/') + client.get('/test_filters/') - c = app.test_client() - c.get('/') - c.get('/test_filters_without_returning_categories/') + client = app.test_client() + client.get('/') + client.get('/test_filters_without_returning_categories/') -def test_request_processing(): - app = flask.Flask(__name__) +def test_request_processing(app, client): evts = [] @app.before_request @@ -691,14 +650,14 @@ def test_request_processing(): assert 'before' in evts assert 'after' not in evts return 'request' + assert 'after' not in evts - rv = app.test_client().get('/').data + rv = client.get('/').data assert 'after' in evts assert rv == b'request|after' -def test_request_preprocessing_early_return(): - app = flask.Flask(__name__) +def test_request_preprocessing_early_return(app, client): evts = [] @app.before_request @@ -720,31 +679,28 @@ def test_request_preprocessing_early_return(): evts.append('index') return "damnit" - rv = app.test_client().get('/').data.strip() + rv = client.get('/').data.strip() assert rv == b'hello' assert evts == [1, 2] -def test_after_request_processing(): - app = flask.Flask(__name__) - app.testing = True - +def test_after_request_processing(app, client): @app.route('/') def index(): @flask.after_this_request def foo(response): response.headers['X-Foo'] = 'a header' return response + return 'Test' - c = app.test_client() - resp = c.get('/') + + resp = client.get('/') assert resp.status_code == 200 assert resp.headers['X-Foo'] == 'a header' -def test_teardown_request_handler(): +def test_teardown_request_handler(app, client): called = [] - app = flask.Flask(__name__) @app.teardown_request def teardown_request(exc): @@ -754,16 +710,15 @@ def test_teardown_request_handler(): @app.route('/') def root(): return "Response" - rv = app.test_client().get('/') + + rv = client.get('/') assert rv.status_code == 200 assert b'Response' in rv.data assert len(called) == 1 -def test_teardown_request_handler_debug_mode(): +def test_teardown_request_handler_debug_mode(app, client): called = [] - app = flask.Flask(__name__) - app.testing = True @app.teardown_request def teardown_request(exc): @@ -773,16 +728,17 @@ def test_teardown_request_handler_debug_mode(): @app.route('/') def root(): return "Response" - rv = app.test_client().get('/') + + rv = client.get('/') assert rv.status_code == 200 assert b'Response' in rv.data assert len(called) == 1 -def test_teardown_request_handler_error(): +def test_teardown_request_handler_error(app, client): called = [] - app = flask.Flask(__name__) app.config['LOGGER_HANDLER_POLICY'] = 'never' + app.testing = False @app.teardown_request def teardown_request1(exc): @@ -811,15 +767,15 @@ def test_teardown_request_handler_error(): @app.route('/') def fails(): 1 // 0 - rv = app.test_client().get('/') + + rv = client.get('/') assert rv.status_code == 500 assert b'Internal Server Error' in rv.data assert len(called) == 2 -def test_before_after_request_order(): +def test_before_after_request_order(app, client): called = [] - app = flask.Flask(__name__) @app.before_request def before1(): @@ -850,14 +806,15 @@ def test_before_after_request_order(): @app.route('/') def index(): return '42' - rv = app.test_client().get('/') + + rv = client.get('/') assert rv.data == b'42' assert called == [1, 2, 3, 4, 5, 6] -def test_error_handling(): - app = flask.Flask(__name__) +def test_error_handling(app, client): app.config['LOGGER_HANDLER_POLICY'] = 'never' + app.testing = False @app.errorhandler(404) def not_found(e): @@ -882,21 +839,21 @@ def test_error_handling(): @app.route('/forbidden') def error2(): flask.abort(403) - c = app.test_client() - rv = c.get('/') + + rv = client.get('/') assert rv.status_code == 404 assert rv.data == b'not found' - rv = c.get('/error') + rv = client.get('/error') assert rv.status_code == 500 assert b'internal server error' == rv.data - rv = c.get('/forbidden') + rv = client.get('/forbidden') assert rv.status_code == 403 assert b'forbidden' == rv.data -def test_error_handling_processing(): - app = flask.Flask(__name__) +def test_error_handling_processing(app, client): app.config['LOGGER_HANDLER_POLICY'] = 'never' + app.testing = False @app.errorhandler(500) def internal_server_error(e): @@ -911,32 +868,28 @@ def test_error_handling_processing(): resp.mimetype = 'text/x-special' return resp - with app.test_client() as c: - resp = c.get('/') - assert resp.mimetype == 'text/x-special' - assert resp.data == b'internal server error' + resp = client.get('/') + assert resp.mimetype == 'text/x-special' + assert resp.data == b'internal server error' -def test_baseexception_error_handling(): - app = flask.Flask(__name__) +def test_baseexception_error_handling(app, client): app.config['LOGGER_HANDLER_POLICY'] = 'never' + app.testing = False @app.route('/') def broken_func(): raise KeyboardInterrupt() - with app.test_client() as c: - with pytest.raises(KeyboardInterrupt): - c.get('/') + with pytest.raises(KeyboardInterrupt): + client.get('/') ctx = flask._request_ctx_stack.top assert ctx.preserved assert type(ctx._preserved_exc) is KeyboardInterrupt -def test_before_request_and_routing_errors(): - app = flask.Flask(__name__) - +def test_before_request_and_routing_errors(app, client): @app.before_request def attach_something(): flask.g.something = 'value' @@ -944,17 +897,16 @@ def test_before_request_and_routing_errors(): @app.errorhandler(404) def return_something(error): return flask.g.something, 404 - rv = app.test_client().get('/') + + rv = client.get('/') assert rv.status_code == 404 assert rv.data == b'value' -def test_user_error_handling(): +def test_user_error_handling(app, client): class MyException(Exception): pass - app = flask.Flask(__name__) - @app.errorhandler(MyException) def handle_my_exception(e): assert isinstance(e, MyException) @@ -964,16 +916,13 @@ def test_user_error_handling(): def index(): raise MyException() - c = app.test_client() - assert c.get('/').data == b'42' + assert client.get('/').data == b'42' -def test_http_error_subclass_handling(): +def test_http_error_subclass_handling(app, client): class ForbiddenSubclass(Forbidden): pass - app = flask.Flask(__name__) - @app.errorhandler(ForbiddenSubclass) def handle_forbidden_subclass(e): assert isinstance(e, ForbiddenSubclass) @@ -997,19 +946,16 @@ def test_http_error_subclass_handling(): def index3(): raise Forbidden() - c = app.test_client() - assert c.get('/1').data == b'banana' - assert c.get('/2').data == b'apple' - assert c.get('/3').data == b'apple' + assert client.get('/1').data == b'banana' + assert client.get('/2').data == b'apple' + assert client.get('/3').data == b'apple' -def test_trapping_of_bad_request_key_errors(): - app = flask.Flask(__name__) - app.testing = True - +def test_trapping_of_bad_request_key_errors(app): @app.route('/fail') def fail(): flask.request.form['missing_key'] + c = app.test_client() assert c.get('/fail').status_code == 400 @@ -1020,23 +966,19 @@ def test_trapping_of_bad_request_key_errors(): assert e.errisinstance(BadRequest) -def test_trapping_of_all_http_exceptions(): - app = flask.Flask(__name__) - app.testing = True +def test_trapping_of_all_http_exceptions(app, client): app.config['TRAP_HTTP_EXCEPTIONS'] = True @app.route('/fail') def fail(): flask.abort(404) - c = app.test_client() with pytest.raises(NotFound): - c.get('/fail') + client.get('/fail') -def test_enctype_debug_helper(): +def test_enctype_debug_helper(app, client): from flask.debughelpers import DebugFilesKeyError - app = flask.Flask(__name__) app.debug = True @app.route('/fail', methods=['POST']) @@ -1046,7 +988,7 @@ def test_enctype_debug_helper(): # with statement is important because we leave an exception on the # stack otherwise and we want to ensure that this is not the case # to not negatively affect other tests. - with app.test_client() as c: + with client as c: with pytest.raises(DebugFilesKeyError) as e: c.post('/fail', data={'foo': 'index.txt'}) assert 'no file contents were transmitted' in str(e.value) @@ -1230,7 +1172,7 @@ def test_jsonify_no_prettyprint(): "submsg": "W00t" }, "msg2": "foobar" - } + } rv = flask.make_response( flask.jsonify(uncompressed_msg), 200) @@ -1241,8 +1183,8 @@ def test_jsonify_prettyprint(): app = flask.Flask(__name__) app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True}) with app.test_request_context(): - compressed_msg = {"msg":{"submsg":"W00t"},"msg2":"foobar"} - pretty_response =\ + compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"} + pretty_response = \ b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n' rv = flask.make_response( @@ -1276,10 +1218,11 @@ def test_url_generation(): @app.route('/hello/', methods=['POST']) def hello(): pass + with app.test_request_context(): assert flask.url_for('hello', name='test x') == '/hello/test%20x' assert flask.url_for('hello', name='test x', _external=True) == \ - 'http://localhost/hello/test%20x' + 'http://localhost/hello/test%20x' def test_build_error_handler(): @@ -1305,6 +1248,7 @@ def test_build_error_handler(): def handler(error, endpoint, values): # Just a test. return '/test_handler/' + app.url_build_error_handlers.append(handler) with app.test_request_context(): assert flask.url_for('spam') == '/test_handler/' @@ -1316,6 +1260,7 @@ def test_build_error_handler_reraise(): # Test a custom handler which reraises the BuildError def handler_raises_build_error(error, endpoint, values): raise error + app.url_build_error_handlers.append(handler_raises_build_error) with app.test_request_context(): @@ -1343,19 +1288,20 @@ def test_custom_converters(): from werkzeug.routing import BaseConverter class ListConverter(BaseConverter): - def to_python(self, value): return value.split(',') def to_url(self, value): base_to_url = super(ListConverter, self).to_url return ','.join(base_to_url(x) for x in value) + app = flask.Flask(__name__) app.url_map.converters['list'] = ListConverter @app.route('/') def index(args): return '|'.join(args) + c = app.test_client() assert c.get('/1,2,3').data == b'1|2|3' @@ -1368,7 +1314,7 @@ def test_static_files(): assert rv.data.strip() == b'

Hello World!

' with app.test_request_context(): assert flask.url_for('static', filename='index.html') == \ - '/static/index.html' + '/static/index.html' rv.close() @@ -1403,8 +1349,8 @@ def test_static_route_with_host_matching(): assert rv.status_code == 200 rv.close() with app.test_request_context(): - rv = flask.url_for('static', filename='index.html', _external=True) - assert rv == 'http://example.com/static/index.html' + rv = flask.url_for('static', filename='index.html', _external=True) + assert rv == 'http://example.com/static/index.html' # Providing static_host without host_matching=True should error. with pytest.raises(Exception): flask.Flask(__name__, static_host='example.com') @@ -1485,6 +1431,7 @@ def test_exception_propagation(): @app.route('/') def index(): 1 // 0 + c = app.test_client() if config_key is not None: app.config[config_key] = True @@ -1550,7 +1497,7 @@ def test_url_processors(): @app.url_defaults def add_language_code(endpoint, values): if flask.g.lang_code is not None and \ - app.url_map.is_endpoint_expecting(endpoint, 'lang_code'): + app.url_map.is_endpoint_expecting(endpoint, 'lang_code'): values.setdefault('lang_code', flask.g.lang_code) @app.url_value_preprocessor @@ -1622,6 +1569,7 @@ def test_debug_mode_complains_after_first_request(): @app.route('/') def index(): return 'Awesome' + assert not app.got_first_request assert app.test_client().get('/').data == b'Awesome' with pytest.raises(AssertionError) as e: @@ -1635,6 +1583,7 @@ def test_debug_mode_complains_after_first_request(): @app.route('/foo') def working(): return 'Meh' + assert app.test_client().get('/foo').data == b'Meh' assert app.got_first_request @@ -1646,6 +1595,7 @@ def test_before_first_request_functions(): @app.before_first_request def foo(): got.append(42) + c = app.test_client() c.get('/') assert got == [42] @@ -1683,6 +1633,7 @@ def test_routing_redirect_debugging(): @app.route('/foo/', methods=['GET', 'POST']) def foo(): return 'success' + with app.test_client() as c: with pytest.raises(AssertionError) as e: c.post('/foo', data={}) @@ -1747,8 +1698,7 @@ def test_preserve_only_once(): assert flask._app_ctx_stack.top is None -def test_preserve_remembers_exception(): - app = flask.Flask(__name__) +def test_preserve_remembers_exception(app, client): app.debug = True errors = [] @@ -1764,51 +1714,40 @@ def test_preserve_remembers_exception(): def teardown_handler(exc): errors.append(exc) - c = app.test_client() - # After this failure we did not yet call the teardown handler with pytest.raises(ZeroDivisionError): - c.get('/fail') + client.get('/fail') assert errors == [] # But this request triggers it, and it's an error - c.get('/success') + client.get('/success') assert len(errors) == 2 assert isinstance(errors[0], ZeroDivisionError) # At this point another request does nothing. - c.get('/success') + client.get('/success') assert len(errors) == 3 assert errors[1] is None -def test_get_method_on_g(): - app = flask.Flask(__name__) - app.testing = True - - with app.app_context(): - assert flask.g.get('x') is None - assert flask.g.get('x', 11) == 11 - flask.g.x = 42 - assert flask.g.get('x') == 42 - assert flask.g.x == 42 - +def test_get_method_on_g(app_ctx): + assert flask.g.get('x') is None + assert flask.g.get('x', 11) == 11 + flask.g.x = 42 + assert flask.g.get('x') == 42 + assert flask.g.x == 42 -def test_g_iteration_protocol(): - app = flask.Flask(__name__) - app.testing = True - with app.app_context(): - flask.g.foo = 23 - flask.g.bar = 42 - assert 'foo' in flask.g - assert 'foos' not in flask.g - assert sorted(flask.g) == ['bar', 'foo'] +def test_g_iteration_protocol(app_ctx): + flask.g.foo = 23 + flask.g.bar = 42 + assert 'foo' in flask.g + assert 'foos' not in flask.g + assert sorted(flask.g) == ['bar', 'foo'] -def test_subdomain_basic_support(): - app = flask.Flask(__name__) - app.config['SERVER_NAME'] = 'localhost' +def test_subdomain_basic_support(app, client): + app.config['SERVER_NAME'] = 'localhost.localdomain' @app.route('/') def normal_index(): @@ -1818,57 +1757,49 @@ def test_subdomain_basic_support(): def test_index(): return 'test index' - c = app.test_client() - rv = c.get('/', 'http://localhost/') + rv = client.get('/', 'http://localhost.localdomain/') assert rv.data == b'normal index' - rv = c.get('/', 'http://test.localhost/') + rv = client.get('/', 'http://test.localhost.localdomain/') assert rv.data == b'test index' -def test_subdomain_matching(): - app = flask.Flask(__name__) - app.config['SERVER_NAME'] = 'localhost' +def test_subdomain_matching(app, client): + app.config['SERVER_NAME'] = 'localhost.localdomain' @app.route('/', subdomain='') def index(user): return 'index for %s' % user - c = app.test_client() - rv = c.get('/', 'http://mitsuhiko.localhost/') + rv = client.get('/', 'http://mitsuhiko.localhost.localdomain/') assert rv.data == b'index for mitsuhiko' -def test_subdomain_matching_with_ports(): - app = flask.Flask(__name__) - app.config['SERVER_NAME'] = 'localhost:3000' +def test_subdomain_matching_with_ports(app, client): + app.config['SERVER_NAME'] = 'localhost.localdomain:3000' @app.route('/', subdomain='') def index(user): return 'index for %s' % user - c = app.test_client() - rv = c.get('/', 'http://mitsuhiko.localhost:3000/') + rv = client.get('/', 'http://mitsuhiko.localhost.localdomain:3000/') assert rv.data == b'index for mitsuhiko' -def test_multi_route_rules(): - app = flask.Flask(__name__) - +def test_multi_route_rules(app, client): @app.route('/') @app.route('//') def index(test='a'): return test - rv = app.test_client().open('/') + rv = client.open('/') assert rv.data == b'a' - rv = app.test_client().open('/b/') + rv = client.open('/b/') assert rv.data == b'b' -def test_multi_route_class_views(): +def test_multi_route_class_views(app, client): class View(object): - def __init__(self, app): app.add_url_rule('/', 'index', self.index) app.add_url_rule('//', 'index', self.index) @@ -1876,35 +1807,32 @@ def test_multi_route_class_views(): def index(self, test='a'): return test - app = flask.Flask(__name__) _ = View(app) - rv = app.test_client().open('/') + rv = client.open('/') assert rv.data == b'a' - rv = app.test_client().open('/b/') + rv = client.open('/b/') assert rv.data == b'b' -def test_run_defaults(monkeypatch): +def test_run_defaults(monkeypatch, app): rv = {} # Mocks werkzeug.serving.run_simple method def run_simple_mock(*args, **kwargs): rv['result'] = 'running...' - app = flask.Flask(__name__) monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock) app.run() assert rv['result'] == 'running...' -def test_run_server_port(monkeypatch): +def test_run_server_port(monkeypatch, app): rv = {} # Mocks werkzeug.serving.run_simple method def run_simple_mock(hostname, port, application, *args, **kwargs): rv['result'] = 'running on %s:%s ...' % (hostname, port) - app = flask.Flask(__name__) monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock) hostname, port = 'localhost', 8000 app.run(hostname, port, debug=True) @@ -1912,17 +1840,16 @@ def test_run_server_port(monkeypatch): @pytest.mark.parametrize('host,port,expect_host,expect_port', ( - (None, None, 'pocoo.org', 8080), - ('localhost', None, 'localhost', 8080), - (None, 80, 'pocoo.org', 80), - ('localhost', 80, 'localhost', 80), + (None, None, 'pocoo.org', 8080), + ('localhost', None, 'localhost', 8080), + (None, 80, 'pocoo.org', 80), + ('localhost', 80, 'localhost', 80), )) -def test_run_from_config(monkeypatch, host, port, expect_host, expect_port): +def test_run_from_config(monkeypatch, host, port, expect_host, expect_port, app): def run_simple_mock(hostname, port, *args, **kwargs): assert hostname == expect_host assert port == expect_port monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock) - app = flask.Flask(__name__) app.config['SERVER_NAME'] = 'pocoo.org:8080' app.run(host, port) diff --git a/tests/test_blueprints.py b/tests/test_blueprints.py index 5c5119c0..434fca37 100644 --- a/tests/test_blueprints.py +++ b/tests/test_blueprints.py @@ -18,7 +18,7 @@ from werkzeug.http import parse_cache_control_header from jinja2 import TemplateNotFound -def test_blueprint_specific_error_handling(): +def test_blueprint_specific_error_handling(app, client): frontend = flask.Blueprint('frontend', __name__) backend = flask.Blueprint('backend', __name__) sideend = flask.Blueprint('sideend', __name__) @@ -43,7 +43,6 @@ def test_blueprint_specific_error_handling(): def sideend_no(): flask.abort(403) - app = flask.Flask(__name__) app.register_blueprint(frontend) app.register_blueprint(backend) app.register_blueprint(sideend) @@ -52,15 +51,15 @@ def test_blueprint_specific_error_handling(): def app_forbidden(e): return 'application itself says no', 403 - c = app.test_client() + assert client.get('/frontend-no').data == b'frontend says no' + assert client.get('/backend-no').data == b'backend says no' + assert client.get('/what-is-a-sideend').data == b'application itself says no' - 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(): +def test_blueprint_specific_user_error_handling(app, client): class MyDecoratorException(Exception): pass + class MyFunctionException(Exception): pass @@ -74,32 +73,30 @@ def test_blueprint_specific_user_error_handling(): 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 client.get('/decorator').data == b'boom' + assert client.get('/function').data == b'bam' - assert c.get('/decorator').data == b'boom' - assert c.get('/function').data == b'bam' -def test_blueprint_app_error_handling(): +def test_blueprint_app_error_handling(app, client): errors = flask.Blueprint('errors', __name__) @errors.app_errorhandler(403) def forbidden_handler(e): return 'you shall not pass', 403 - app = flask.Flask(__name__) - @app.route('/forbidden') def app_forbidden(): flask.abort(403) @@ -113,12 +110,11 @@ def test_blueprint_app_error_handling(): app.register_blueprint(errors) app.register_blueprint(forbidden_bp) - c = app.test_client() + assert client.get('/forbidden').data == b'you shall not pass' + assert client.get('/nope').data == b'you shall not pass' - assert c.get('/forbidden').data == b'you shall not pass' - assert c.get('/nope').data == b'you shall not pass' -def test_blueprint_url_definitions(): +def test_blueprint_url_definitions(app, client): bp = flask.Blueprint('test', __name__) @bp.route('/foo', defaults={'baz': 42}) @@ -129,17 +125,16 @@ def test_blueprint_url_definitions(): 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' + assert client.get('/1/foo').data == b'23/42' + assert client.get('/2/foo').data == b'19/42' + assert client.get('/1/bar').data == b'23' + assert client.get('/2/bar').data == b'19' -def test_blueprint_url_processors(): + +def test_blueprint_url_processors(app, client): bp = flask.Blueprint('frontend', __name__, url_prefix='/') @bp.url_defaults @@ -158,28 +153,26 @@ def test_blueprint_url_processors(): def about(): return flask.url_for('.index') - app = flask.Flask(__name__) app.register_blueprint(bp) - c = app.test_client() + assert client.get('/de/').data == b'/de/about' + assert client.get('/de/about').data == b'/de/' - assert c.get('/de/').data == b'/de/about' - assert c.get('/de/about').data == b'/de/' def test_templates_and_static(test_apps): from blueprintapp import app - c = app.test_client() + client = app.test_client() - rv = c.get('/') + rv = client.get('/') assert rv.data == b'Hello from the Frontend' - rv = c.get('/admin/') + rv = client.get('/admin/') assert rv.data == b'Hello from the Admin' - rv = c.get('/admin/index2') + rv = client.get('/admin/index2') assert rv.data == b'Hello from the Admin' - rv = c.get('/admin/static/test.txt') + rv = client.get('/admin/static/test.txt') assert rv.data.strip() == b'Admin File' rv.close() - rv = c.get('/admin/static/css/test.css') + rv = client.get('/admin/static/css/test.css') assert rv.data.strip() == b'/* nested file */' rv.close() @@ -190,7 +183,7 @@ def test_templates_and_static(test_apps): 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') + rv = client.get('/admin/static/css/test.css') cc = parse_cache_control_header(rv.headers['Cache-Control']) assert cc.max_age == expected_max_age rv.close() @@ -208,8 +201,10 @@ def test_templates_and_static(test_apps): with flask.Flask(__name__).test_request_context(): assert flask.render_template('nested/nested.txt') == 'I\'m nested' + def test_default_static_cache_timeout(): app = flask.Flask(__name__) + class MyBlueprint(flask.Blueprint): def get_send_file_max_age(self, filename): return 100 @@ -232,12 +227,14 @@ def test_default_static_cache_timeout(): finally: app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default + def test_templates_list(test_apps): from blueprintapp import app templates = sorted(app.jinja_env.list_templates()) assert templates == ['admin/index.html', 'frontend/index.html'] -def test_dotted_names(): + +def test_dotted_names(app, client): frontend = flask.Blueprint('myapp.frontend', __name__) backend = flask.Blueprint('myapp.backend', __name__) @@ -253,18 +250,15 @@ def test_dotted_names(): 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' + assert client.get('/fe').data.strip() == b'/be' + assert client.get('/fe2').data.strip() == b'/fe' + assert client.get('/be').data.strip() == b'/fe' -def test_dotted_names_from_app(): - app = flask.Flask(__name__) - app.testing = True + +def test_dotted_names_from_app(app, client): test = flask.Blueprint('test', __name__) @app.route('/') @@ -277,11 +271,11 @@ def test_dotted_names_from_app(): app.register_blueprint(test) - with app.test_client() as c: - rv = c.get('/') - assert rv.data == b'/test/' + rv = client.get('/') + assert rv.data == b'/test/' -def test_empty_url_defaults(): + +def test_empty_url_defaults(app, client): bp = flask.Blueprint('bp', __name__) @bp.route('/', defaults={'page': 1}) @@ -289,15 +283,13 @@ def test_empty_url_defaults(): 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' + assert client.get('/').data == b'1' + assert client.get('/page/2').data == b'2' -def test_route_decorator_custom_endpoint(): +def test_route_decorator_custom_endpoint(app, client): bp = flask.Blueprint('bp', __name__) @bp.route('/foo') @@ -316,21 +308,20 @@ def test_route_decorator_custom_endpoint(): def bar_foo(): return flask.request.endpoint - app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') @app.route('/') def index(): 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' + assert client.get('/').data == b'index' + assert client.get('/py/foo').data == b'bp.foo' + assert client.get('/py/bar').data == b'bp.bar' + assert client.get('/py/bar/123').data == b'bp.123' + assert client.get('/py/bar/foo').data == b'bp.bar_foo' + -def test_route_decorator_custom_endpoint_with_dots(): +def test_route_decorator_custom_endpoint_with_dots(app, client): bp = flask.Blueprint('bp', __name__) @bp.route('/foo') @@ -371,21 +362,18 @@ def test_route_decorator_custom_endpoint_with_dots(): 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' + assert client.get('/py/foo').data == b'bp.foo' # The rule's didn't actually made it through - rv = c.get('/py/bar') + rv = client.get('/py/bar') assert rv.status_code == 404 - rv = c.get('/py/bar/123') + rv = client.get('/py/bar/123') assert rv.status_code == 404 -def test_endpoint_decorator(): +def test_endpoint_decorator(app, client): from werkzeug.routing import Rule - app = flask.Flask(__name__) app.url_map.add(Rule('/foo', endpoint='bar')) bp = flask.Blueprint('bp', __name__) @@ -396,229 +384,282 @@ def test_endpoint_decorator(): app.register_blueprint(bp, url_prefix='/bp_prefix') - c = app.test_client() - assert c.get('/foo').data == b'bar' - assert c.get('/bp_prefix/bar').status_code == 404 + assert client.get('/foo').data == b'bar' + assert client.get('/bp_prefix/bar').status_code == 404 -def test_template_filter(): +def test_template_filter(app): 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(): + +def test_add_template_filter(app): 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(): + +def test_template_filter_with_name(app): 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(): + +def test_add_template_filter_with_name(app): 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(): + +def test_template_filter_with_template(app, client): 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('/') + + rv = client.get('/') assert rv.data == b'dcba' -def test_template_filter_after_route_with_template(): - app = flask.Flask(__name__) + +def test_template_filter_after_route_with_template(app, client): @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('/') + rv = client.get('/') assert rv.data == b'dcba' -def test_add_template_filter_with_template(): + +def test_add_template_filter_with_template(app, client): 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('/') + + rv = client.get('/') assert rv.data == b'dcba' -def test_template_filter_with_name_and_template(): + +def test_template_filter_with_name_and_template(app, client): 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('/') + + rv = client.get('/') assert rv.data == b'dcba' -def test_add_template_filter_with_name_and_template(): + +def test_add_template_filter_with_name_and_template(app, client): 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('/') + + rv = client.get('/') assert rv.data == b'dcba' -def test_template_test(): + +def test_template_test(app): 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(): + +def test_add_template_test(app): 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(): + +def test_template_test_with_name(app): 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(): + +def test_add_template_test_with_name(app): 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(): + +def test_template_test_with_template(app, client): 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('/') + + rv = client.get('/') assert b'Success!' in rv.data -def test_template_test_after_route_with_template(): - app = flask.Flask(__name__) + +def test_template_test_after_route_with_template(app, client): @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('/') + rv = client.get('/') assert b'Success!' in rv.data -def test_add_template_test_with_template(): + +def test_add_template_test_with_template(app, client): 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('/') + + rv = client.get('/') assert b'Success!' in rv.data -def test_template_test_with_name_and_template(): + +def test_template_test_with_name_and_template(app, client): 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('/') + + rv = client.get('/') assert b'Success!' in rv.data -def test_add_template_test_with_name_and_template(): + +def test_add_template_test_with_name_and_template(app, client): 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('/') + + rv = client.get('/') assert b'Success!' in rv.data + def test_context_processing(): app = flask.Flask(__name__) answer_bp = flask.Blueprint('answer_bp', __name__) @@ -661,12 +702,15 @@ def test_context_processing(): assert b'42' in answer_page_bytes assert b'43' in answer_page_bytes + def test_template_global(): app = flask.Flask(__name__) bp = flask.Blueprint('bp', __name__) + @bp.app_template_global() def get_answer(): return 42 + # Make sure the function is not in the jinja_env already assert 'get_answer' not in app.jinja_env.globals.keys() app.register_blueprint(bp) diff --git a/tests/test_deprecations.py b/tests/test_deprecations.py index 666f7d56..7383604e 100644 --- a/tests/test_deprecations.py +++ b/tests/test_deprecations.py @@ -15,10 +15,8 @@ import flask class TestRequestDeprecation(object): - - def test_request_json(self, recwarn): + def test_request_json(self, recwarn, app, client): """Request.json is deprecated""" - app = flask.Flask(__name__) app.testing = True @app.route('/', methods=['POST']) @@ -27,13 +25,11 @@ class TestRequestDeprecation(object): print(flask.request.json) return 'OK' - c = app.test_client() - c.post('/', data='{"spam": 42}', content_type='application/json') + client.post('/', data='{"spam": 42}', content_type='application/json') recwarn.pop(DeprecationWarning) - def test_request_module(self, recwarn): + def test_request_module(self, recwarn, app, client): """Request.module is deprecated""" - app = flask.Flask(__name__) app.testing = True @app.route('/') @@ -41,6 +37,5 @@ class TestRequestDeprecation(object): assert flask.request.module is None return 'OK' - c = app.test_client() - c.get('/') + client.get('/') recwarn.pop(DeprecationWarning) diff --git a/tests/test_helpers.py b/tests/test_helpers.py index 5af95f18..4259d2d9 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -35,240 +35,226 @@ def has_encoding(name): class TestJSON(object): - - def test_ignore_cached_json(self): - app = flask.Flask(__name__) + def test_ignore_cached_json(self, app): with app.test_request_context('/', method='POST', data='malformed', content_type='application/json'): assert flask.request.get_json(silent=True, cache=True) is None with pytest.raises(BadRequest): flask.request.get_json(silent=False, cache=False) - def test_post_empty_json_adds_exception_to_response_content_in_debug(self): - app = flask.Flask(__name__) + def test_post_empty_json_adds_exception_to_response_content_in_debug(self, app, client): app.config['DEBUG'] = True + @app.route('/json', methods=['POST']) def post_json(): flask.request.get_json() return None - c = app.test_client() - rv = c.post('/json', data=None, content_type='application/json') + + rv = client.post('/json', data=None, content_type='application/json') assert rv.status_code == 400 assert b'Failed to decode JSON object' in rv.data - def test_post_empty_json_wont_add_exception_to_response_if_no_debug(self): - app = flask.Flask(__name__) + def test_post_empty_json_wont_add_exception_to_response_if_no_debug(self, app, client): app.config['DEBUG'] = False + @app.route('/json', methods=['POST']) def post_json(): flask.request.get_json() return None - c = app.test_client() - rv = c.post('/json', data=None, content_type='application/json') + + rv = client.post('/json', data=None, content_type='application/json') assert rv.status_code == 400 assert b'Failed to decode JSON object' not in rv.data - def test_json_bad_requests(self): - app = flask.Flask(__name__) + def test_json_bad_requests(self, app, client): + @app.route('/json', methods=['POST']) def return_json(): return flask.jsonify(foo=text_type(flask.request.get_json())) - c = app.test_client() - rv = c.post('/json', data='malformed', content_type='application/json') + + rv = client.post('/json', data='malformed', content_type='application/json') assert rv.status_code == 400 - def test_json_custom_mimetypes(self): - app = flask.Flask(__name__) + def test_json_custom_mimetypes(self, app, client): + @app.route('/json', methods=['POST']) def return_json(): return flask.request.get_json() - c = app.test_client() - rv = c.post('/json', data='"foo"', content_type='application/x+json') + + rv = client.post('/json', data='"foo"', content_type='application/x+json') assert rv.data == b'foo' - def test_json_body_encoding(self): - app = flask.Flask(__name__) + def test_json_body_encoding(self, app, client): app.testing = True + @app.route('/') def index(): return flask.request.get_json() - c = app.test_client() - resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'), - content_type='application/json; charset=iso-8859-15') + resp = client.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'), + content_type='application/json; charset=iso-8859-15') assert resp.data == u'Hällo Wörld'.encode('utf-8') - def test_json_as_unicode(self): - app = flask.Flask(__name__) + @pytest.mark.parametrize('test_value,expected', [(True, '"\\u2603"'), (False, u'"\u2603"')]) + def test_json_as_unicode(self, test_value, expected, app, app_ctx): - app.config['JSON_AS_ASCII'] = True - with app.app_context(): - rv = flask.json.dumps(u'\N{SNOWMAN}') - assert rv == '"\\u2603"' + app.config['JSON_AS_ASCII'] = test_value + rv = flask.json.dumps(u'\N{SNOWMAN}') + assert rv == expected - app.config['JSON_AS_ASCII'] = False - with app.app_context(): - rv = flask.json.dumps(u'\N{SNOWMAN}') - assert rv == u'"\u2603"' - - def test_json_dump_to_file(self): - app = flask.Flask(__name__) + def test_json_dump_to_file(self, app, app_ctx): test_data = {'name': 'Flask'} out = StringIO() - with app.app_context(): - flask.json.dump(test_data, out) - out.seek(0) - rv = flask.json.load(out) - assert rv == test_data + flask.json.dump(test_data, out) + out.seek(0) + rv = flask.json.load(out) + assert rv == test_data @pytest.mark.parametrize('test_value', [0, -1, 1, 23, 3.14, 's', "longer string", True, False, None]) - def test_jsonify_basic_types(self, test_value): + def test_jsonify_basic_types(self, test_value, app, client): """Test jsonify with basic types.""" - app = flask.Flask(__name__) - c = app.test_client() url = '/jsonify_basic_types' app.add_url_rule(url, url, lambda x=test_value: flask.jsonify(x)) - rv = c.get(url) + rv = client.get(url) assert rv.mimetype == 'application/json' assert flask.json.loads(rv.data) == test_value - def test_jsonify_dicts(self): + def test_jsonify_dicts(self, app, client): """Test jsonify with dicts and kwargs unpacking.""" - d = dict( - a=0, b=23, c=3.14, d='t', e='Hi', f=True, g=False, - h=['test list', 10, False], - i={'test':'dict'} - ) - app = flask.Flask(__name__) + d = {'a': 0, 'b': 23, 'c': 3.14, 'd': 't', + 'e': 'Hi', 'f': True, 'g': False, + 'h': ['test list', 10, False], + 'i': {'test': 'dict'}} + @app.route('/kw') def return_kwargs(): return flask.jsonify(**d) + @app.route('/dict') def return_dict(): return flask.jsonify(d) - c = app.test_client() + for url in '/kw', '/dict': - rv = c.get(url) + rv = client.get(url) assert rv.mimetype == 'application/json' assert flask.json.loads(rv.data) == d - def test_jsonify_arrays(self): + def test_jsonify_arrays(self, app, client): """Test jsonify of lists and args unpacking.""" l = [ 0, 42, 3.14, 't', 'hello', True, False, ['test list', 2, False], - {'test':'dict'} + {'test': 'dict'} ] - app = flask.Flask(__name__) + @app.route('/args_unpack') def return_args_unpack(): return flask.jsonify(*l) + @app.route('/array') def return_array(): return flask.jsonify(l) - c = app.test_client() + for url in '/args_unpack', '/array': - rv = c.get(url) + rv = client.get(url) assert rv.mimetype == 'application/json' assert flask.json.loads(rv.data) == l - def test_jsonify_date_types(self): + def test_jsonify_date_types(self, app, client): """Test jsonify with datetime.date and datetime.datetime types.""" test_dates = ( datetime.datetime(1973, 3, 11, 6, 30, 45), datetime.date(1975, 1, 5) ) - app = flask.Flask(__name__) - c = app.test_client() for i, d in enumerate(test_dates): url = '/datetest{0}'.format(i) app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val)) - rv = c.get(url) + rv = client.get(url) assert rv.mimetype == 'application/json' assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple()) - def test_jsonify_uuid_types(self): + def test_jsonify_uuid_types(self, app, client): """Test jsonify with uuid.UUID types""" test_uuid = uuid.UUID(bytes=b'\xDE\xAD\xBE\xEF' * 4) - app = flask.Flask(__name__) url = '/uuid_test' app.add_url_rule(url, url, lambda: flask.jsonify(x=test_uuid)) - c = app.test_client() - rv = c.get(url) + rv = client.get(url) rv_x = flask.json.loads(rv.data)['x'] assert rv_x == str(test_uuid) rv_uuid = uuid.UUID(rv_x) assert rv_uuid == test_uuid - def test_json_attr(self): - app = flask.Flask(__name__) + def test_json_attr(self, app, client): + @app.route('/add', methods=['POST']) def add(): json = flask.request.get_json() return text_type(json['a'] + json['b']) - c = app.test_client() - rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}), - content_type='application/json') + + rv = client.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}), + content_type='application/json') assert rv.data == b'3' - def test_template_escaping(self): - app = flask.Flask(__name__) + def test_template_escaping(self, app, req_ctx): render = flask.render_template_string - with app.test_request_context(): - rv = flask.json.htmlsafe_dumps('') - assert rv == u'"\\u003c/script\\u003e"' - assert type(rv) == text_type - rv = render('{{ ""|tojson }}') - assert rv == '"\\u003c/script\\u003e"' - rv = render('{{ "<\0/script>"|tojson }}') - assert rv == '"\\u003c\\u0000/script\\u003e"' - rv = render('{{ "