From 4dc2ef19eaa4ced5cb2f4a2a1673e65459c355d2 Mon Sep 17 00:00:00 2001 From: Reuven Date: Fri, 4 Mar 2016 13:30:40 +0200 Subject: [PATCH] Use pytest.raises() instead of try/catch with asser 0 This is somehow more readable, and enable using the features of pytest's ExeptionInfo (such as errisinstance). --- tests/test_basic.py | 50 ++++++++++++---------------------------- tests/test_blueprints.py | 7 ++---- tests/test_config.py | 46 ++++++++++++++---------------------- tests/test_reqctx.py | 6 +---- tests/test_testing.py | 14 ++++------- 5 files changed, 39 insertions(+), 84 deletions(-) diff --git a/tests/test_basic.py b/tests/test_basic.py index d7cc7a3f..3daca9cd 100644 --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -307,12 +307,8 @@ def test_missing_session(): app = flask.Flask(__name__) def expect_exception(f, *args, **kwargs): - try: - f(*args, **kwargs) - except RuntimeError as e: - assert e.args and 'session is unavailable' in e.args[0] - else: - assert False, 'expected exception' + 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) @@ -853,12 +849,9 @@ def test_trapping_of_bad_request_key_errors(): app.config['TRAP_BAD_REQUEST_ERRORS'] = True c = app.test_client() - try: - c.get('/fail') - except KeyError as e: - assert isinstance(e, BadRequest) - else: - assert False, 'Expected exception' + with pytest.raises(KeyError) as e: + c.get("/fail") + assert e.errisinstance(BadRequest) def test_trapping_of_all_http_exceptions(): @@ -888,13 +881,10 @@ def test_enctype_debug_helper(): # 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: - try: + with pytest.raises(DebugFilesKeyError) as e: c.post('/fail', data={'foo': 'index.txt'}) - except DebugFilesKeyError as e: - assert 'no file contents were transmitted' in str(e) - assert 'This was submitted: "index.txt"' in str(e) - else: - assert False, 'Expected exception' + assert 'no file contents were transmitted' in str(e.value) + assert 'This was submitted: "index.txt"' in str(e.value) def test_response_creation(): @@ -1203,12 +1193,8 @@ def test_exception_propagation(): c = app.test_client() if config_key is not None: app.config[config_key] = True - try: + with pytest.raises(Exception): c.get('/') - except Exception: - pass - else: - assert False, 'expected exception' else: assert c.get('/').status_code == 500 @@ -1345,14 +1331,11 @@ def test_debug_mode_complains_after_first_request(): return 'Awesome' assert not app.got_first_request assert app.test_client().get('/').data == b'Awesome' - try: + with pytest.raises(AssertionError) as e: @app.route('/foo') def broken(): return 'Meh' - except AssertionError as e: - assert 'A setup function was called' in str(e) - else: - assert False, 'Expected exception' + assert 'A setup function was called' in str(e) app.debug = False @@ -1408,14 +1391,11 @@ def test_routing_redirect_debugging(): def foo(): return 'success' with app.test_client() as c: - try: + with pytest.raises(AssertionError) as e: c.post('/foo', data={}) - except AssertionError as e: - assert 'http://localhost/foo/' in str(e) - assert ('Make sure to directly send ' - 'your POST-request to this URL') in str(e) - else: - assert False, 'Expected exception' + 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) assert rv.data == b'success' diff --git a/tests/test_blueprints.py b/tests/test_blueprints.py index 7e22bc7f..a3309037 100644 --- a/tests/test_blueprints.py +++ b/tests/test_blueprints.py @@ -174,12 +174,9 @@ def test_templates_and_static(test_apps): assert flask.url_for('admin.static', filename='test.txt') == '/admin/static/test.txt' with app.test_request_context(): - try: + with pytest.raises(TemplateNotFound) as e: flask.render_template('missing.html') - except TemplateNotFound as e: - assert e.name == 'missing.html' - else: - assert 0, 'expected exception' + assert e.value.name == 'missing.html' with flask.Flask(__name__).test_request_context(): assert flask.render_template('nested/nested.txt') == 'I\'m nested' diff --git a/tests/test_config.py b/tests/test_config.py index 7a17b607..333a5cff 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -89,12 +89,9 @@ def test_config_from_envvar(): try: os.environ = {} app = flask.Flask(__name__) - try: + with pytest.raises(RuntimeError) as e: app.config.from_envvar('FOO_SETTINGS') - except RuntimeError as e: - assert "'FOO_SETTINGS' is not set" in str(e) - else: - assert 0, 'expected exception' + assert "'FOO_SETTINGS' is not set" in str(e.value) assert not app.config.from_envvar('FOO_SETTINGS', silent=True) os.environ = {'FOO_SETTINGS': __file__.rsplit('.', 1)[0] + '.py'} @@ -108,16 +105,13 @@ def test_config_from_envvar_missing(): env = os.environ try: os.environ = {'FOO_SETTINGS': 'missing.cfg'} - try: + with pytest.raises(IOError) as e: app = flask.Flask(__name__) app.config.from_envvar('FOO_SETTINGS') - except IOError as e: - msg = str(e) - assert msg.startswith('[Errno 2] Unable to load configuration ' - 'file (No such file or directory):') - assert msg.endswith("missing.cfg'") - else: - assert False, 'expected IOError' + msg = str(e.value) + assert msg.startswith('[Errno 2] Unable to load configuration ' + 'file (No such file or directory):') + assert msg.endswith("missing.cfg'") assert not app.config.from_envvar('FOO_SETTINGS', silent=True) finally: os.environ = env @@ -125,29 +119,23 @@ def test_config_from_envvar_missing(): def test_config_missing(): app = flask.Flask(__name__) - try: + with pytest.raises(IOError) as e: app.config.from_pyfile('missing.cfg') - except IOError as e: - msg = str(e) - assert msg.startswith('[Errno 2] Unable to load configuration ' - 'file (No such file or directory):') - assert msg.endswith("missing.cfg'") - else: - assert 0, 'expected config' + msg = str(e.value) + assert msg.startswith('[Errno 2] Unable to load configuration ' + 'file (No such file or directory):') + assert msg.endswith("missing.cfg'") assert not app.config.from_pyfile('missing.cfg', silent=True) def test_config_missing_json(): app = flask.Flask(__name__) - try: + with pytest.raises(IOError) as e: app.config.from_json('missing.json') - except IOError as e: - msg = str(e) - assert msg.startswith('[Errno 2] Unable to load configuration ' - 'file (No such file or directory):') - assert msg.endswith("missing.json'") - else: - assert 0, 'expected config' + msg = str(e.value) + assert msg.startswith('[Errno 2] Unable to load configuration ' + 'file (No such file or directory):') + assert msg.endswith("missing.json'") assert not app.config.from_json('missing.json', silent=True) diff --git a/tests/test_reqctx.py b/tests/test_reqctx.py index 558958dc..4b2b1f87 100644 --- a/tests/test_reqctx.py +++ b/tests/test_reqctx.py @@ -140,12 +140,8 @@ def test_manual_context_binding(): ctx.push() assert index() == 'Hello World!' ctx.pop() - try: + with pytest.raises(RuntimeError): index() - except RuntimeError: - pass - else: - assert 0, 'expected runtime error' @pytest.mark.skipif(greenlet is None, reason='greenlet not installed') def test_greenlet_context_copying(): diff --git a/tests/test_testing.py b/tests/test_testing.py index a9e06fab..7bb99e79 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -100,13 +100,10 @@ def test_session_transactions_no_null_sessions(): app.testing = True with app.test_client() as c: - try: + with pytest.raises(RuntimeError) as e: with c.session_transaction() as sess: pass - except RuntimeError as e: - assert 'Session backend did not open a session' in str(e) - else: - assert False, 'Expected runtime error' + assert 'Session backend did not open a session' in str(e.value) def test_session_transactions_keep_context(): app = flask.Flask(__name__) @@ -124,13 +121,10 @@ def test_session_transaction_needs_cookies(): app = flask.Flask(__name__) app.testing = True c = app.test_client(use_cookies=False) - try: + with pytest.raises(RuntimeError) as e: with c.session_transaction() as s: pass - except RuntimeError as e: - assert 'cookies' in str(e) - else: - assert False, 'Expected runtime error' + assert 'cookies' in str(e.value) def test_test_client_context_binding(): app = flask.Flask(__name__)