From 4ec1fbc9f52b4b3997a1978ab3390a5a1157ad6a Mon Sep 17 00:00:00 2001 From: Christian Stade-Schuldt Date: Wed, 24 May 2017 17:27:36 -0700 Subject: [PATCH] More DRYing up the test suite (#2325) --- tests/test_basic.py | 315 +++++++++++++++---------------------- tests/test_blueprints.py | 8 + tests/test_cli.py | 22 +++ tests/test_deprecations.py | 2 - tests/test_helpers.py | 28 +--- tests/test_regression.py | 4 +- tests/test_signals.py | 12 +- tests/test_templating.py | 8 +- tests/test_testing.py | 84 +++++----- tests/test_views.py | 38 ++--- 10 files changed, 234 insertions(+), 287 deletions(-) diff --git a/tests/test_basic.py b/tests/test_basic.py index 9d72f6d1..de56cb43 100644 --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -951,18 +951,16 @@ def test_http_error_subclass_handling(app, client): assert client.get('/3').data == b'apple' -def test_trapping_of_bad_request_key_errors(app): +def test_trapping_of_bad_request_key_errors(app, client): @app.route('/fail') def fail(): flask.request.form['missing_key'] - c = app.test_client() - assert c.get('/fail').status_code == 400 + assert client.get('/fail').status_code == 400 app.config['TRAP_BAD_REQUEST_ERRORS'] = True - c = app.test_client() with pytest.raises(KeyError) as e: - c.get("/fail") + client.get("/fail") assert e.errisinstance(BadRequest) @@ -988,17 +986,14 @@ def test_enctype_debug_helper(app, client): # 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 client as c: + with client: with pytest.raises(DebugFilesKeyError) as e: - c.post('/fail', data={'foo': 'index.txt'}) + client.post('/fail', data={'foo': 'index.txt'}) assert 'no file contents were transmitted' in str(e.value) assert 'This was submitted: "index.txt"' in str(e.value) -def test_response_types(): - app = flask.Flask(__name__) - app.testing = True - +def test_response_types(app, client): @app.route('/text') def from_text(): return u'Hällo Wörld' @@ -1040,39 +1035,37 @@ def test_response_types(): def from_wsgi(): return NotFound() - c = app.test_client() - - assert c.get('/text').data == u'Hällo Wörld'.encode('utf-8') - assert c.get('/bytes').data == u'Hällo Wörld'.encode('utf-8') + assert client.get('/text').data == u'Hällo Wörld'.encode('utf-8') + assert client.get('/bytes').data == u'Hällo Wörld'.encode('utf-8') - rv = c.get('/full_tuple') + rv = client.get('/full_tuple') assert rv.data == b'Meh' assert rv.headers['X-Foo'] == 'Testing' assert rv.status_code == 400 assert rv.mimetype == 'text/plain' - rv = c.get('/text_headers') + rv = client.get('/text_headers') assert rv.data == b'Hello' assert rv.headers['X-Foo'] == 'Test' assert rv.status_code == 200 assert rv.mimetype == 'text/plain' - rv = c.get('/text_status') + rv = client.get('/text_status') assert rv.data == b'Hi, status!' assert rv.status_code == 400 assert rv.mimetype == 'text/html' - rv = c.get('/response_headers') + rv = client.get('/response_headers') assert rv.data == b'Hello world' assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar'] assert rv.headers['X-Bar'] == 'Foo' assert rv.status_code == 404 - rv = c.get('/response_status') + rv = client.get('/response_status') assert rv.data == b'Hello world' assert rv.status_code == 500 - rv = c.get('/wsgi') + rv = client.get('/wsgi') assert b'Not Found' in rv.data assert rv.status_code == 404 @@ -1120,114 +1113,97 @@ def test_response_type_errors(): pytest.raises(TypeError, c.get, '/bad_wsgi') -def test_make_response(): - app = flask.Flask(__name__) - with app.test_request_context(): - rv = flask.make_response() - assert rv.status_code == 200 - assert rv.data == b'' - assert rv.mimetype == 'text/html' +def test_make_response(app, req_ctx): + rv = flask.make_response() + assert rv.status_code == 200 + assert rv.data == b'' + assert rv.mimetype == 'text/html' - rv = flask.make_response('Awesome') - assert rv.status_code == 200 - assert rv.data == b'Awesome' - assert rv.mimetype == 'text/html' + rv = flask.make_response('Awesome') + assert rv.status_code == 200 + assert rv.data == b'Awesome' + assert rv.mimetype == 'text/html' - rv = flask.make_response('W00t', 404) - assert rv.status_code == 404 - assert rv.data == b'W00t' - assert rv.mimetype == 'text/html' + rv = flask.make_response('W00t', 404) + assert rv.status_code == 404 + assert rv.data == b'W00t' + assert rv.mimetype == 'text/html' -def test_make_response_with_response_instance(): - app = flask.Flask(__name__) - with app.test_request_context(): - rv = flask.make_response( - flask.jsonify({'msg': 'W00t'}), 400) - assert rv.status_code == 400 - assert rv.data == b'{"msg":"W00t"}\n' - assert rv.mimetype == 'application/json' - - rv = flask.make_response( - flask.Response(''), 400) - assert rv.status_code == 400 - assert rv.data == b'' - assert rv.mimetype == 'text/html' - - rv = flask.make_response( - flask.Response('', headers={'Content-Type': 'text/html'}), - 400, [('X-Foo', 'bar')]) - assert rv.status_code == 400 - assert rv.headers['Content-Type'] == 'text/html' - assert rv.headers['X-Foo'] == 'bar' - - -def test_jsonify_no_prettyprint(): - app = flask.Flask(__name__) +def test_make_response_with_response_instance(app, req_ctx): + rv = flask.make_response( + flask.jsonify({'msg': 'W00t'}), 400) + assert rv.status_code == 400 + assert rv.data == b'{"msg":"W00t"}\n' + assert rv.mimetype == 'application/json' + + rv = flask.make_response( + flask.Response(''), 400) + assert rv.status_code == 400 + assert rv.data == b'' + assert rv.mimetype == 'text/html' + + rv = flask.make_response( + flask.Response('', headers={'Content-Type': 'text/html'}), + 400, [('X-Foo', 'bar')]) + assert rv.status_code == 400 + assert rv.headers['Content-Type'] == 'text/html' + assert rv.headers['X-Foo'] == 'bar' + + +def test_jsonify_no_prettyprint(app, req_ctx): app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False}) - with app.test_request_context(): - compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n' - uncompressed_msg = { - "msg": { - "submsg": "W00t" - }, - "msg2": "foobar" - } + compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n' + uncompressed_msg = { + "msg": { + "submsg": "W00t" + }, + "msg2": "foobar" + } - rv = flask.make_response( - flask.jsonify(uncompressed_msg), 200) - assert rv.data == compressed_msg + rv = flask.make_response( + flask.jsonify(uncompressed_msg), 200) + assert rv.data == compressed_msg -def test_jsonify_prettyprint(): - app = flask.Flask(__name__) +def test_jsonify_prettyprint(app, req_ctx): app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True}) - with app.test_request_context(): - compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"} - pretty_response = \ - b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n' + 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( - flask.jsonify(compressed_msg), 200) - assert rv.data == pretty_response + rv = flask.make_response( + flask.jsonify(compressed_msg), 200) + assert rv.data == pretty_response -def test_jsonify_mimetype(): - app = flask.Flask(__name__) +def test_jsonify_mimetype(app, req_ctx): app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'}) - with app.test_request_context(): - msg = { - "msg": {"submsg": "W00t"}, - } - rv = flask.make_response( - flask.jsonify(msg), 200) - assert rv.mimetype == 'application/vnd.api+json' - + msg = { + "msg": {"submsg": "W00t"}, + } + rv = flask.make_response( + flask.jsonify(msg), 200) + assert rv.mimetype == 'application/vnd.api+json' -def test_jsonify_args_and_kwargs_check(): - app = flask.Flask(__name__) - with app.test_request_context(): - with pytest.raises(TypeError) as e: - flask.jsonify('fake args', kwargs='fake') - assert 'behavior undefined' in str(e.value) +def test_jsonify_args_and_kwargs_check(app, req_ctx): + with pytest.raises(TypeError) as e: + flask.jsonify('fake args', kwargs='fake') + assert 'behavior undefined' in str(e.value) -def test_url_generation(): - app = flask.Flask(__name__) +def test_url_generation(app, req_ctx): @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' + 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' -def test_build_error_handler(): - app = flask.Flask(__name__) - +def test_build_error_handler(app): # Test base case, a URL which results in a BuildError. with app.test_request_context(): pytest.raises(BuildError, flask.url_for, 'spam') @@ -1254,9 +1230,7 @@ def test_build_error_handler(): assert flask.url_for('spam') == '/test_handler/' -def test_build_error_handler_reraise(): - app = flask.Flask(__name__) - +def test_build_error_handler_reraise(app): # Test a custom handler which reraises the BuildError def handler_raises_build_error(error, endpoint, values): raise error @@ -1267,9 +1241,7 @@ def test_build_error_handler_reraise(): pytest.raises(BuildError, flask.url_for, 'not.existing') -def test_url_for_passes_special_values_to_build_error_handler(): - app = flask.Flask(__name__) - +def test_url_for_passes_special_values_to_build_error_handler(app): @app.url_build_error_handlers.append def handler(error, endpoint, values): assert values == { @@ -1284,7 +1256,7 @@ def test_url_for_passes_special_values_to_build_error_handler(): flask.url_for('/') -def test_custom_converters(): +def test_custom_converters(app, client): from werkzeug.routing import BaseConverter class ListConverter(BaseConverter): @@ -1295,21 +1267,17 @@ def test_custom_converters(): 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' + assert client.get('/1,2,3').data == b'1|2|3' -def test_static_files(): - app = flask.Flask(__name__) - app.testing = True - rv = app.test_client().get('/static/index.html') +def test_static_files(app, client): + rv = client.get('/static/index.html') assert rv.status_code == 200 assert rv.data.strip() == b'

Hello World!

' with app.test_request_context(): @@ -1366,8 +1334,7 @@ def test_request_locals(): assert not flask.g -def test_test_app_proper_environ(): - app = flask.Flask(__name__) +def test_test_app_proper_environ(app, client): app.config.update( SERVER_NAME='localhost.localdomain:5000' ) @@ -1380,22 +1347,22 @@ def test_test_app_proper_environ(): def subdomain(): return 'Foo SubDomain' - rv = app.test_client().get('/') + rv = client.get('/') assert rv.data == b'Foo' - rv = app.test_client().get('/', 'http://localhost.localdomain:5000') + rv = client.get('/', 'http://localhost.localdomain:5000') assert rv.data == b'Foo' - rv = app.test_client().get('/', 'https://localhost.localdomain:5000') + rv = client.get('/', 'https://localhost.localdomain:5000') assert rv.data == b'Foo' app.config.update(SERVER_NAME='localhost.localdomain') - rv = app.test_client().get('/', 'https://localhost.localdomain') + rv = client.get('/', 'https://localhost.localdomain') assert rv.data == b'Foo' try: app.config.update(SERVER_NAME='localhost.localdomain:443') - rv = app.test_client().get('/', 'https://localhost.localdomain') + rv = client.get('/', 'https://localhost.localdomain') # Werkzeug 0.8 assert rv.status_code == 404 except ValueError as e: @@ -1408,7 +1375,7 @@ def test_test_app_proper_environ(): try: app.config.update(SERVER_NAME='localhost.localdomain') - rv = app.test_client().get('/', 'http://foo.localhost') + rv = client.get('/', 'http://foo.localhost') # Werkzeug 0.8 assert rv.status_code == 404 except ValueError as e: @@ -1419,26 +1386,24 @@ def test_test_app_proper_environ(): "server name from the WSGI environment ('foo.localhost')" ) - rv = app.test_client().get('/', 'http://foo.localhost.localdomain') + rv = client.get('/', 'http://foo.localhost.localdomain') assert rv.data == b'Foo SubDomain' -def test_exception_propagation(): +def test_exception_propagation(app, client): def apprunner(config_key): - app = flask.Flask(__name__) app.config['LOGGER_HANDLER_POLICY'] = 'never' @app.route('/') def index(): 1 // 0 - c = app.test_client() if config_key is not None: app.config[config_key] = True with pytest.raises(Exception): - c.get('/') + client.get('/') else: - assert c.get('/').status_code == 500 + assert client.get('/').status_code == 500 # we have to run this test in an isolated thread because if the # debug flag is set to true and an exception happens the context is @@ -1455,21 +1420,19 @@ def test_exception_propagation(): @pytest.mark.parametrize('use_reloader', [True, False]) @pytest.mark.parametrize('propagate_exceptions', [None, True, False]) def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger, - use_reloader, propagate_exceptions): + use_reloader, propagate_exceptions, app): rv = {} # Mocks werkzeug.serving.run_simple method def run_simple_mock(*args, **kwargs): rv['passthrough_errors'] = kwargs.get('passthrough_errors') - app = flask.Flask(__name__) monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock) app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader) -def test_max_content_length(): - app = flask.Flask(__name__) +def test_max_content_length(app, client): app.config['MAX_CONTENT_LENGTH'] = 64 @app.before_request @@ -1486,13 +1449,11 @@ def test_max_content_length(): def catcher(error): return '42' - c = app.test_client() - rv = c.post('/accept', data={'myfile': 'foo' * 100}) + rv = client.post('/accept', data={'myfile': 'foo' * 100}) assert rv.data == b'42' -def test_url_processors(): - app = flask.Flask(__name__) +def test_url_processors(app, client): @app.url_defaults def add_language_code(endpoint, values): @@ -1516,15 +1477,12 @@ def test_url_processors(): def something_else(): return flask.url_for('about', lang_code='en') - c = app.test_client() + assert client.get('/de/').data == b'/de/about' + assert client.get('/de/about').data == b'/foo' + assert client.get('/foo').data == b'/en/about' - assert c.get('/de/').data == b'/de/about' - assert c.get('/de/about').data == b'/foo' - assert c.get('/foo').data == b'/en/about' - -def test_inject_blueprint_url_defaults(): - app = flask.Flask(__name__) +def test_inject_blueprint_url_defaults(app): bp = flask.Blueprint('foo.bar.baz', __name__, template_folder='template') @@ -1549,21 +1507,16 @@ def test_inject_blueprint_url_defaults(): assert url == expected -def test_nonascii_pathinfo(): - app = flask.Flask(__name__) - app.testing = True - +def test_nonascii_pathinfo(app, client): @app.route(u'/киртест') def index(): return 'Hello World!' - c = app.test_client() - rv = c.get(u'/киртест') + rv = client.get(u'/киртест') assert rv.data == b'Hello World!' -def test_debug_mode_complains_after_first_request(): - app = flask.Flask(__name__) +def test_debug_mode_complains_after_first_request(app, client): app.debug = True @app.route('/') @@ -1571,7 +1524,7 @@ def test_debug_mode_complains_after_first_request(): return 'Awesome' assert not app.got_first_request - assert app.test_client().get('/').data == b'Awesome' + assert client.get('/').data == b'Awesome' with pytest.raises(AssertionError) as e: @app.route('/foo') def broken(): @@ -1584,39 +1537,34 @@ def test_debug_mode_complains_after_first_request(): def working(): return 'Meh' - assert app.test_client().get('/foo').data == b'Meh' + assert client.get('/foo').data == b'Meh' assert app.got_first_request -def test_before_first_request_functions(): +def test_before_first_request_functions(app, client): got = [] - app = flask.Flask(__name__) @app.before_first_request def foo(): got.append(42) - c = app.test_client() - c.get('/') + client.get('/') assert got == [42] - c.get('/') + client.get('/') assert got == [42] assert app.got_first_request -def test_before_first_request_functions_concurrent(): +def test_before_first_request_functions_concurrent(app, client): got = [] - app = flask.Flask(__name__) @app.before_first_request def foo(): time.sleep(0.2) got.append(42) - c = app.test_client() - def get_and_assert(): - c.get("/") + client.get("/") assert got == [42] t = Thread(target=get_and_assert) @@ -1626,32 +1574,30 @@ def test_before_first_request_functions_concurrent(): assert app.got_first_request -def test_routing_redirect_debugging(): - app = flask.Flask(__name__) +def test_routing_redirect_debugging(app, client): app.debug = True @app.route('/foo/', methods=['GET', 'POST']) def foo(): return 'success' - with app.test_client() as c: + with client: with pytest.raises(AssertionError) as e: - c.post('/foo', data={}) + client.post('/foo', data={}) assert 'http://localhost/foo/' in str(e) assert ('Make sure to directly send ' 'your POST-request to this URL') in str(e) - rv = c.get('/foo', data={}, follow_redirects=True) + rv = client.get('/foo', data={}, follow_redirects=True) assert rv.data == b'success' app.debug = False - with app.test_client() as c: - rv = c.post('/foo', data={}, follow_redirects=True) + with client: + rv = client.post('/foo', data={}, follow_redirects=True) assert rv.data == b'success' -def test_route_decorator_custom_endpoint(): - app = flask.Flask(__name__) +def test_route_decorator_custom_endpoint(app, client): app.debug = True @app.route('/foo/') @@ -1671,24 +1617,21 @@ def test_route_decorator_custom_endpoint(): assert flask.url_for('bar') == '/bar/' assert flask.url_for('123') == '/bar/123' - c = app.test_client() - assert c.get('/foo/').data == b'foo' - assert c.get('/bar/').data == b'bar' - assert c.get('/bar/123').data == b'123' + assert client.get('/foo/').data == b'foo' + assert client.get('/bar/').data == b'bar' + assert client.get('/bar/123').data == b'123' -def test_preserve_only_once(): - app = flask.Flask(__name__) +def test_preserve_only_once(app, client): app.debug = True @app.route('/fail') def fail_func(): 1 // 0 - c = app.test_client() for x in range(3): with pytest.raises(ZeroDivisionError): - c.get('/fail') + client.get('/fail') assert flask._request_ctx_stack.top is not None assert flask._app_ctx_stack.top is not None diff --git a/tests/test_blueprints.py b/tests/test_blueprints.py index 4e15b9e2..d57b3034 100644 --- a/tests/test_blueprints.py +++ b/tests/test_blueprints.py @@ -718,17 +718,21 @@ def test_template_global(app): rv = flask.render_template_string('{{ get_answer() }}') assert rv == '42' + def test_request_processing(app, client): bp = flask.Blueprint('bp', __name__) evts = [] + @bp.before_request def before_bp(): evts.append('before') + @bp.after_request def after_bp(response): response.data += b'|after' evts.append('after') return response + @bp.teardown_request def teardown_bp(exc): evts.append('teardown') @@ -745,6 +749,7 @@ def test_request_processing(app, client): assert rv.data == b'request|after' assert evts == ['before', 'after', 'teardown'] + def test_app_request_processing(app, client): bp = flask.Blueprint('bp', __name__) evts = [] @@ -752,14 +757,17 @@ def test_app_request_processing(app, client): @bp.before_app_first_request def before_first_request(): evts.append('first') + @bp.before_app_request def before_app(): evts.append('before') + @bp.after_app_request def after_app(response): response.data += b'|after' evts.append('after') return response + @bp.teardown_app_request def teardown_app(exc): evts.append('teardown') diff --git a/tests/test_cli.py b/tests/test_cli.py index 1c843d61..459d6ef9 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -40,22 +40,27 @@ def test_cli_name(test_apps): def test_find_best_app(test_apps): """Test if `find_best_app` behaves as expected with different combinations of input.""" script_info = ScriptInfo() + class Module: app = Flask('appname') + assert find_best_app(script_info, Module) == Module.app class Module: application = Flask('appname') + assert find_best_app(script_info, Module) == Module.application class Module: myapp = Flask('appname') + assert find_best_app(script_info, Module) == Module.myapp class Module: @staticmethod def create_app(): return Flask('appname') + assert isinstance(find_best_app(script_info, Module), Flask) assert find_best_app(script_info, Module).name == 'appname' @@ -63,6 +68,7 @@ def test_find_best_app(test_apps): @staticmethod def create_app(foo): return Flask('appname') + assert isinstance(find_best_app(script_info, Module), Flask) assert find_best_app(script_info, Module).name == 'appname' @@ -70,6 +76,7 @@ def test_find_best_app(test_apps): @staticmethod def create_app(foo=None, script_info=None): return Flask('appname') + assert isinstance(find_best_app(script_info, Module), Flask) assert find_best_app(script_info, Module).name == 'appname' @@ -77,36 +84,44 @@ def test_find_best_app(test_apps): @staticmethod def make_app(): return Flask('appname') + assert isinstance(find_best_app(script_info, Module), Flask) assert find_best_app(script_info, Module).name == 'appname' class Module: myapp = Flask('appname1') + @staticmethod def create_app(): return Flask('appname2') + assert find_best_app(script_info, Module) == Module.myapp class Module: myapp = Flask('appname1') + @staticmethod def create_app(): return Flask('appname2') + assert find_best_app(script_info, Module) == Module.myapp class Module: pass + pytest.raises(NoAppException, find_best_app, script_info, Module) class Module: myapp1 = Flask('appname1') myapp2 = Flask('appname2') + pytest.raises(NoAppException, find_best_app, script_info, Module) class Module: @staticmethod def create_app(foo, bar): return Flask('appname2') + pytest.raises(NoAppException, find_best_app, script_info, Module) @@ -163,10 +178,13 @@ def test_get_version(test_apps, capsys): """Test of get_version.""" from flask import __version__ as flask_ver from sys import version as py_ver + class MockCtx(object): resilient_parsing = False color = None + def exit(self): return + ctx = MockCtx() get_version(ctx, None, "test") out, err = capsys.readouterr() @@ -191,6 +209,7 @@ def test_scriptinfo(test_apps): def test_with_appcontext(runner): """Test of with_appcontext.""" + @click.command() @with_appcontext def testcmd(): @@ -205,6 +224,7 @@ def test_with_appcontext(runner): def test_appgroup(runner): """Test of with_appcontext.""" + @click.group(cls=AppGroup) def cli(): pass @@ -234,6 +254,7 @@ def test_appgroup(runner): def test_flaskgroup(runner): """Test FlaskGroup.""" + def create_app(info): return Flask("flaskgroup") @@ -252,6 +273,7 @@ def test_flaskgroup(runner): def test_print_exceptions(runner): """Print the stacktrace if the CLI.""" + def create_app(info): raise Exception("oh no") return Flask("flaskgroup") diff --git a/tests/test_deprecations.py b/tests/test_deprecations.py index 7383604e..6ab63dd4 100644 --- a/tests/test_deprecations.py +++ b/tests/test_deprecations.py @@ -17,7 +17,6 @@ import flask class TestRequestDeprecation(object): def test_request_json(self, recwarn, app, client): """Request.json is deprecated""" - app.testing = True @app.route('/', methods=['POST']) def index(): @@ -30,7 +29,6 @@ class TestRequestDeprecation(object): def test_request_module(self, recwarn, app, client): """Request.module is deprecated""" - app.testing = True @app.route('/') def index(): diff --git a/tests/test_helpers.py b/tests/test_helpers.py index 4259d2d9..a67fed0b 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -85,7 +85,6 @@ class TestJSON(object): assert rv.data == b'foo' def test_json_body_encoding(self, app, client): - app.testing = True @app.route('/') def index(): @@ -241,7 +240,6 @@ class TestJSON(object): return X(obj['_foo']) return obj - app.testing = True app.json_encoder = MyEncoder app.json_decoder = MyDecoder @@ -285,7 +283,6 @@ class TestJSON(object): def index(): return flask.json.dumps(flask.request.get_json()['x']) - app.testing = True app.register_blueprint(bp) rv = client.post('/bp', data=flask.json.dumps({ @@ -293,11 +290,10 @@ class TestJSON(object): }), content_type='application/json') assert rv.data == b'"<42>"' - def test_modified_url_encoding(self, app): + def test_modified_url_encoding(self, app, client): class ModifiedRequest(flask.Request): url_charset = 'euc-kr' - app.testing = True app.request_class = ModifiedRequest app.url_map.charset = 'euc-kr' @@ -305,7 +301,7 @@ class TestJSON(object): def index(): return flask.request.args['foo'] - rv = app.test_client().get(u'/?foo=정상처리'.encode('euc-kr')) + rv = client.get(u'/?foo=정상처리'.encode('euc-kr')) assert rv.status_code == 200 assert rv.data == u'정상처리'.encode('utf-8') @@ -313,7 +309,6 @@ class TestJSON(object): test_modified_url_encoding = None def test_json_key_sorting(self, app, client): - app.testing = True app.debug = True assert app.config['JSON_SORT_KEYS'] == True @@ -538,7 +533,6 @@ class TestSendfile(object): rv.close() def test_attachment(self, app, req_ctx): - app = flask.Flask(__name__) with open(os.path.join(app.root_path, 'static/index.html')) as f: rv = flask.send_file(f, as_attachment=True, @@ -619,7 +613,6 @@ class TestSendfile(object): rv.close() def test_send_from_directory(self, app, req_ctx): - app.testing = True app.root_path = os.path.join(os.path.dirname(__file__), 'test_apps', 'subdomaintestmodule') rv = flask.send_from_directory('static', 'hello.txt') @@ -628,7 +621,6 @@ class TestSendfile(object): rv.close() def test_send_from_directory_bad_request(self, app, req_ctx): - app.testing = True app.root_path = os.path.join(os.path.dirname(__file__), 'test_apps', 'subdomaintestmodule') @@ -645,8 +637,7 @@ class TestLogging(object): app.logger_name = __name__ + '/test_logger_cache' assert app.logger is not logger1 - def test_debug_log(self, capsys): - app = flask.Flask(__name__) + def test_debug_log(self, capsys, app, client): app.debug = True @app.route('/') @@ -659,8 +650,8 @@ class TestLogging(object): def exc(): 1 // 0 - with app.test_client() as c: - c.get('/') + with client: + client.get('/') out, err = capsys.readouterr() assert 'WARNING in test_helpers [' in err assert os.path.basename(__file__.rsplit('.', 1)[0] + '.py') in err @@ -668,7 +659,7 @@ class TestLogging(object): assert 'this is a debug statement' in err with pytest.raises(ZeroDivisionError): - c.get('/exc') + client.get('/exc') def test_debug_log_override(self, app): app.debug = True @@ -676,7 +667,7 @@ class TestLogging(object): app.logger.level = 10 assert app.logger.level == 10 - def test_exception_logging(self, app): + def test_exception_logging(self, app, client): out = StringIO() app.config['LOGGER_HANDLER_POLICY'] = 'never' app.logger_name = 'flask_tests/test_exception_logging' @@ -687,7 +678,7 @@ class TestLogging(object): def index(): 1 // 0 - rv = app.test_client().get('/') + rv = client.get('/') assert rv.status_code == 500 assert b'Internal Server Error' in rv.data @@ -808,7 +799,6 @@ class TestNoImports(object): class TestStreaming(object): def test_streaming_with_context(self, app, client): - app.testing = True @app.route('/') def index(): @@ -823,7 +813,6 @@ class TestStreaming(object): assert rv.data == b'Hello World!' def test_streaming_with_context_as_decorator(self, app, client): - app.testing = True @app.route('/') def index(): @@ -839,7 +828,6 @@ class TestStreaming(object): assert rv.data == b'Hello World!' def test_streaming_with_context_and_custom_close(self, app, client): - app.testing = True called = [] class Wrapper(object): diff --git a/tests/test_regression.py b/tests/test_regression.py index ca689069..d2c088f7 100644 --- a/tests/test_regression.py +++ b/tests/test_regression.py @@ -76,11 +76,9 @@ def test_safe_join_toplevel_pardir(): safe_join('/foo', '..') -def test_aborting(): +def test_aborting(app): class Foo(Exception): whatever = 42 - app = flask.Flask(__name__) - app.testing = True @app.errorhandler(Foo) def handle_foo(e): diff --git a/tests/test_signals.py b/tests/test_signals.py index b687b6e8..4ef935de 100644 --- a/tests/test_signals.py +++ b/tests/test_signals.py @@ -18,15 +18,13 @@ except ImportError: import flask - pytestmark = pytest.mark.skipif( blinker is None, reason='Signals require the blinker library.' ) -def test_template_rendered(): - app = flask.Flask(__name__) +def test_template_rendered(app, client): @app.route('/') def index(): return flask.render_template('simple_template.html', whiskey=42) @@ -38,7 +36,7 @@ def test_template_rendered(): flask.template_rendered.connect(record, app) try: - app.test_client().get('/') + client.get('/') assert len(recorded) == 1 template, context = recorded[0] assert template.name == 'simple_template.html' @@ -46,6 +44,7 @@ def test_template_rendered(): finally: flask.template_rendered.disconnect(record, app) + def test_before_render_template(): app = flask.Flask(__name__) @@ -70,6 +69,7 @@ def test_before_render_template(): finally: flask.before_render_template.disconnect(record, app) + def test_request_signals(): app = flask.Flask(__name__) calls = [] @@ -109,6 +109,7 @@ def test_request_signals(): 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 = [] @@ -128,6 +129,7 @@ def test_request_exception_signal(): finally: flask.got_request_exception.disconnect(record, app) + def test_appcontext_signals(): app = flask.Flask(__name__) recorded = [] @@ -154,6 +156,7 @@ def test_appcontext_signals(): 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' @@ -180,6 +183,7 @@ def test_flash_signal(): finally: flask.message_flashed.disconnect(record, app) + def test_appcontext_tearing_down_signal(): app = flask.Flask(__name__) recorded = [] diff --git a/tests/test_templating.py b/tests/test_templating.py index 6ba13ade..2763dfbd 100644 --- a/tests/test_templating.py +++ b/tests/test_templating.py @@ -16,7 +16,7 @@ import logging from jinja2 import TemplateNotFound -def test_context_processing(app): +def test_context_processing(app, client): @app.context_processor def context_processor(): return {'injected_value': 42} @@ -25,7 +25,7 @@ def test_context_processing(app): def index(): return flask.render_template('context_template.html', value=23) - rv = app.test_client().get('/') + rv = client.get('/') assert rv.data == b'

23|42' @@ -253,7 +253,7 @@ def test_add_template_test_with_name(app): assert app.jinja_env.tests['boolean'](False) -def test_template_test_with_template(app): +def test_template_test_with_template(app, client): @app.template_test() def boolean(value): return isinstance(value, bool) @@ -262,7 +262,7 @@ def test_template_test_with_template(app): 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 diff --git a/tests/test_testing.py b/tests/test_testing.py index 51d48f69..7ec0c993 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -38,14 +38,12 @@ def test_environ_defaults(app, client, app_ctx, req_ctx): ctx = app.test_request_context() assert ctx.request.url == 'http://localhost/' - with app.test_client() as c: - rv = c.get('/') + with client: + rv = client.get('/') assert rv.data == b'http://localhost/' def test_environ_base_default(app, client, app_ctx): - app.testing = True - @app.route('/') def index(): flask.g.user_agent = flask.request.headers["User-Agent"] @@ -89,39 +87,39 @@ def test_redirect_keep_session(app, client, app_ctx): def get_session(): return flask.session.get('data', '') - with client as c: - rv = c.get('/getsession') + with client: + rv = client.get('/getsession') assert rv.data == b'' - rv = c.get('/') + rv = client.get('/') assert rv.data == b'index' assert flask.session.get('data') == 'foo' - rv = c.post('/', data={}, follow_redirects=True) + rv = client.post('/', data={}, follow_redirects=True) assert rv.data == b'foo' # This support requires a new Werkzeug version - if not hasattr(c, 'redirect_client'): + if not hasattr(client, 'redirect_client'): assert flask.session.get('data') == 'foo' - rv = c.get('/getsession') + rv = client.get('/getsession') assert rv.data == b'foo' -def test_session_transactions(app): +def test_session_transactions(app, client): app.secret_key = 'testing' @app.route('/') def index(): return text_type(flask.session['foo']) - with app.test_client() as c: - with c.session_transaction() as sess: + with client: + with client.session_transaction() as sess: assert len(sess) == 0 sess['foo'] = [42] assert len(sess) == 1 - rv = c.get('/') + rv = client.get('/') assert rv.data == b'[42]' - with c.session_transaction() as sess: + with client.session_transaction() as sess: assert len(sess) == 1 assert sess['foo'] == [42] @@ -146,6 +144,7 @@ def test_session_transactions_keep_context(app, client, req_ctx): with client.session_transaction(): assert req is flask.request._get_current_object() + def test_session_transaction_needs_cookies(app): c = app.test_client(use_cookies=False) with pytest.raises(RuntimeError) as e: @@ -154,9 +153,9 @@ def test_session_transaction_needs_cookies(app): assert 'cookies' in str(e.value) -def test_test_client_context_binding(): - app = flask.Flask(__name__) +def test_test_client_context_binding(app, client): app.config['LOGGER_HANDLER_POLICY'] = 'never' + app.testing = False @app.route('/') def index(): @@ -167,13 +166,13 @@ def test_test_client_context_binding(): def other(): 1 // 0 - with app.test_client() as c: - resp = c.get('/') + with client: + resp = client.get('/') assert flask.g.value == 42 assert resp.data == b'Hello World!' assert resp.status_code == 200 - resp = c.get('/other') + resp = client.get('/other') assert not hasattr(flask.g, 'value') assert b'Internal Server Error' in resp.data assert resp.status_code == 500 @@ -187,58 +186,52 @@ def test_test_client_context_binding(): raise AssertionError('some kind of exception expected') -def test_reuse_client(): - app = flask.Flask(__name__) - c = app.test_client() +def test_reuse_client(client): + c = client with c: - assert c.get('/').status_code == 404 + assert client.get('/').status_code == 404 with c: - assert c.get('/').status_code == 404 + assert client.get('/').status_code == 404 -def test_test_client_calls_teardown_handlers(): - app = flask.Flask(__name__) +def test_test_client_calls_teardown_handlers(app, client): called = [] @app.teardown_request def remember(error): called.append(error) - with app.test_client() as c: + with client: assert called == [] - c.get('/') + client.get('/') assert called == [] assert called == [None] del called[:] - with app.test_client() as c: + with client: assert called == [] - c.get('/') + client.get('/') assert called == [] - c.get('/') + client.get('/') assert called == [None] assert called == [None, None] -def test_full_url_request(): - app = flask.Flask(__name__) - app.testing = True - +def test_full_url_request(app, client): @app.route('/action', methods=['POST']) def action(): return 'x' - with app.test_client() as c: - rv = c.post('http://domain.com/action?vodka=42', data={'gin': 43}) + with client: + rv = client.post('http://domain.com/action?vodka=42', data={'gin': 43}) assert rv.status_code == 200 assert 'gin' in flask.request.form assert 'vodka' in flask.request.args -def test_subdomain(): - app = flask.Flask(__name__) +def test_subdomain(app, client): app.config['SERVER_NAME'] = 'example.com' @app.route('/', subdomain='') @@ -248,15 +241,14 @@ def test_subdomain(): with app.test_request_context(): url = flask.url_for('view', company_id='xxx') - with app.test_client() as c: - response = c.get(url) + with client: + response = client.get(url) assert 200 == response.status_code assert b'xxx' == response.data -def test_nosubdomain(): - app = flask.Flask(__name__) +def test_nosubdomain(app, client): app.config['SERVER_NAME'] = 'example.com' @app.route('/') @@ -266,8 +258,8 @@ def test_nosubdomain(): with app.test_request_context(): url = flask.url_for('view', company_id='xxx') - with app.test_client() as c: - response = c.get(url) + with client: + response = client.get(url) assert 200 == response.status_code assert b'xxx' == response.data diff --git a/tests/test_views.py b/tests/test_views.py index bfa087fc..4176e542 100644 --- a/tests/test_views.py +++ b/tests/test_views.py @@ -72,7 +72,7 @@ def test_view_patching(app): common_test(app) -def test_view_inheritance(app): +def test_view_inheritance(app, client): class Index(flask.views.MethodView): def get(self): return 'GET' @@ -85,13 +85,12 @@ def test_view_inheritance(app): return 'DELETE' app.add_url_rule('/', view_func=BetterIndex.as_view('index')) - c = app.test_client() - meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow']) + meths = parse_set_header(client.open('/', method='OPTIONS').headers['Allow']) assert sorted(meths) == ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST'] -def test_view_decorators(app): +def test_view_decorators(app, client): def add_x_parachute(f): def new_function(*args, **kwargs): resp = flask.make_response(f(*args, **kwargs)) @@ -107,8 +106,7 @@ def test_view_decorators(app): return 'Awesome' app.add_url_rule('/', view_func=Index.as_view('index')) - c = app.test_client() - rv = c.get('/') + rv = client.get('/') assert rv.headers['X-Parachute'] == 'awesome' assert rv.data == b'Awesome' @@ -153,7 +151,7 @@ def test_view_provide_automatic_options_attr(): assert 'OPTIONS' in rv.allow -def test_implicit_head(app): +def test_implicit_head(app, client): class Index(flask.views.MethodView): def get(self): return flask.Response('Blub', headers={ @@ -161,16 +159,15 @@ def test_implicit_head(app): }) app.add_url_rule('/', view_func=Index.as_view('index')) - c = app.test_client() - rv = c.get('/') + rv = client.get('/') assert rv.data == b'Blub' assert rv.headers['X-Method'] == 'GET' - rv = c.head('/') + rv = client.head('/') assert rv.data == b'' assert rv.headers['X-Method'] == 'HEAD' -def test_explicit_head(app): +def test_explicit_head(app, client): class Index(flask.views.MethodView): def get(self): return 'GET' @@ -179,10 +176,9 @@ def test_explicit_head(app): return flask.Response('', headers={'X-Method': 'HEAD'}) app.add_url_rule('/', view_func=Index.as_view('index')) - c = app.test_client() - rv = c.get('/') + rv = client.get('/') assert rv.data == b'GET' - rv = c.head('/') + rv = client.head('/') assert rv.data == b'' assert rv.headers['X-Method'] == 'HEAD' @@ -205,7 +201,7 @@ def test_endpoint_override(app): common_test(app) -def test_multiple_inheritance(app): +def test_multiple_inheritance(app, client): class GetView(flask.views.MethodView): def get(self): return 'GET' @@ -219,13 +215,12 @@ def test_multiple_inheritance(app): app.add_url_rule('/', view_func=GetDeleteView.as_view('index')) - c = app.test_client() - assert c.get('/').data == b'GET' - assert c.delete('/').data == b'DELETE' + assert client.get('/').data == b'GET' + assert client.delete('/').data == b'DELETE' assert sorted(GetDeleteView.methods) == ['DELETE', 'GET'] -def test_remove_method_from_parent(app): +def test_remove_method_from_parent(app, client): class GetView(flask.views.MethodView): def get(self): return 'GET' @@ -239,7 +234,6 @@ def test_remove_method_from_parent(app): app.add_url_rule('/', view_func=View.as_view('index')) - c = app.test_client() - assert c.get('/').data == b'GET' - assert c.post('/').status_code == 405 + assert client.get('/').data == b'GET' + assert client.post('/').status_code == 405 assert sorted(View.methods) == ['GET']