Browse Source

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).
pull/1743/head
Reuven 9 years ago
parent
commit
4dc2ef19ea
  1. 50
      tests/test_basic.py
  2. 7
      tests/test_blueprints.py
  3. 46
      tests/test_config.py
  4. 6
      tests/test_reqctx.py
  5. 14
      tests/test_testing.py

50
tests/test_basic.py

@ -307,12 +307,8 @@ def test_missing_session():
app = flask.Flask(__name__) app = flask.Flask(__name__)
def expect_exception(f, *args, **kwargs): def expect_exception(f, *args, **kwargs):
try: e = pytest.raises(RuntimeError, f, *args, **kwargs)
f(*args, **kwargs) assert e.value.args and 'session is unavailable' in e.value.args[0]
except RuntimeError as e:
assert e.args and 'session is unavailable' in e.args[0]
else:
assert False, 'expected exception'
with app.test_request_context(): with app.test_request_context():
assert flask.session.get('missing_key') is None assert flask.session.get('missing_key') is None
expect_exception(flask.session.__setitem__, 'foo', 42) 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 app.config['TRAP_BAD_REQUEST_ERRORS'] = True
c = app.test_client() c = app.test_client()
try: with pytest.raises(KeyError) as e:
c.get('/fail') c.get("/fail")
except KeyError as e: assert e.errisinstance(BadRequest)
assert isinstance(e, BadRequest)
else:
assert False, 'Expected exception'
def test_trapping_of_all_http_exceptions(): 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 # stack otherwise and we want to ensure that this is not the case
# to not negatively affect other tests. # to not negatively affect other tests.
with app.test_client() as c: with app.test_client() as c:
try: with pytest.raises(DebugFilesKeyError) as e:
c.post('/fail', data={'foo': 'index.txt'}) c.post('/fail', data={'foo': 'index.txt'})
except DebugFilesKeyError as e: assert 'no file contents were transmitted' in str(e.value)
assert 'no file contents were transmitted' in str(e) assert 'This was submitted: "index.txt"' in str(e.value)
assert 'This was submitted: "index.txt"' in str(e)
else:
assert False, 'Expected exception'
def test_response_creation(): def test_response_creation():
@ -1203,12 +1193,8 @@ def test_exception_propagation():
c = app.test_client() c = app.test_client()
if config_key is not None: if config_key is not None:
app.config[config_key] = True app.config[config_key] = True
try: with pytest.raises(Exception):
c.get('/') c.get('/')
except Exception:
pass
else:
assert False, 'expected exception'
else: else:
assert c.get('/').status_code == 500 assert c.get('/').status_code == 500
@ -1345,14 +1331,11 @@ def test_debug_mode_complains_after_first_request():
return 'Awesome' return 'Awesome'
assert not app.got_first_request assert not app.got_first_request
assert app.test_client().get('/').data == b'Awesome' assert app.test_client().get('/').data == b'Awesome'
try: with pytest.raises(AssertionError) as e:
@app.route('/foo') @app.route('/foo')
def broken(): def broken():
return 'Meh' return 'Meh'
except AssertionError as e: assert 'A setup function was called' in str(e)
assert 'A setup function was called' in str(e)
else:
assert False, 'Expected exception'
app.debug = False app.debug = False
@ -1408,14 +1391,11 @@ def test_routing_redirect_debugging():
def foo(): def foo():
return 'success' return 'success'
with app.test_client() as c: with app.test_client() as c:
try: with pytest.raises(AssertionError) as e:
c.post('/foo', data={}) c.post('/foo', data={})
except AssertionError as e: assert 'http://localhost/foo/' in str(e)
assert 'http://localhost/foo/' in str(e) assert ('Make sure to directly send '
assert ('Make sure to directly send ' 'your POST-request to this URL') in str(e)
'your POST-request to this URL') in str(e)
else:
assert False, 'Expected exception'
rv = c.get('/foo', data={}, follow_redirects=True) rv = c.get('/foo', data={}, follow_redirects=True)
assert rv.data == b'success' assert rv.data == b'success'

7
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' assert flask.url_for('admin.static', filename='test.txt') == '/admin/static/test.txt'
with app.test_request_context(): with app.test_request_context():
try: with pytest.raises(TemplateNotFound) as e:
flask.render_template('missing.html') flask.render_template('missing.html')
except TemplateNotFound as e: assert e.value.name == 'missing.html'
assert e.name == 'missing.html'
else:
assert 0, 'expected exception'
with flask.Flask(__name__).test_request_context(): with flask.Flask(__name__).test_request_context():
assert flask.render_template('nested/nested.txt') == 'I\'m nested' assert flask.render_template('nested/nested.txt') == 'I\'m nested'

46
tests/test_config.py

@ -89,12 +89,9 @@ def test_config_from_envvar():
try: try:
os.environ = {} os.environ = {}
app = flask.Flask(__name__) app = flask.Flask(__name__)
try: with pytest.raises(RuntimeError) as e:
app.config.from_envvar('FOO_SETTINGS') app.config.from_envvar('FOO_SETTINGS')
except RuntimeError as e: assert "'FOO_SETTINGS' is not set" in str(e.value)
assert "'FOO_SETTINGS' is not set" in str(e)
else:
assert 0, 'expected exception'
assert not app.config.from_envvar('FOO_SETTINGS', silent=True) assert not app.config.from_envvar('FOO_SETTINGS', silent=True)
os.environ = {'FOO_SETTINGS': __file__.rsplit('.', 1)[0] + '.py'} os.environ = {'FOO_SETTINGS': __file__.rsplit('.', 1)[0] + '.py'}
@ -108,16 +105,13 @@ def test_config_from_envvar_missing():
env = os.environ env = os.environ
try: try:
os.environ = {'FOO_SETTINGS': 'missing.cfg'} os.environ = {'FOO_SETTINGS': 'missing.cfg'}
try: with pytest.raises(IOError) as e:
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.config.from_envvar('FOO_SETTINGS') app.config.from_envvar('FOO_SETTINGS')
except IOError as e: msg = str(e.value)
msg = str(e) assert msg.startswith('[Errno 2] Unable to load configuration '
assert msg.startswith('[Errno 2] Unable to load configuration ' 'file (No such file or directory):')
'file (No such file or directory):') assert msg.endswith("missing.cfg'")
assert msg.endswith("missing.cfg'")
else:
assert False, 'expected IOError'
assert not app.config.from_envvar('FOO_SETTINGS', silent=True) assert not app.config.from_envvar('FOO_SETTINGS', silent=True)
finally: finally:
os.environ = env os.environ = env
@ -125,29 +119,23 @@ def test_config_from_envvar_missing():
def test_config_missing(): def test_config_missing():
app = flask.Flask(__name__) app = flask.Flask(__name__)
try: with pytest.raises(IOError) as e:
app.config.from_pyfile('missing.cfg') app.config.from_pyfile('missing.cfg')
except IOError as e: msg = str(e.value)
msg = str(e) assert msg.startswith('[Errno 2] Unable to load configuration '
assert msg.startswith('[Errno 2] Unable to load configuration ' 'file (No such file or directory):')
'file (No such file or directory):') assert msg.endswith("missing.cfg'")
assert msg.endswith("missing.cfg'")
else:
assert 0, 'expected config'
assert not app.config.from_pyfile('missing.cfg', silent=True) assert not app.config.from_pyfile('missing.cfg', silent=True)
def test_config_missing_json(): def test_config_missing_json():
app = flask.Flask(__name__) app = flask.Flask(__name__)
try: with pytest.raises(IOError) as e:
app.config.from_json('missing.json') app.config.from_json('missing.json')
except IOError as e: msg = str(e.value)
msg = str(e) assert msg.startswith('[Errno 2] Unable to load configuration '
assert msg.startswith('[Errno 2] Unable to load configuration ' 'file (No such file or directory):')
'file (No such file or directory):') assert msg.endswith("missing.json'")
assert msg.endswith("missing.json'")
else:
assert 0, 'expected config'
assert not app.config.from_json('missing.json', silent=True) assert not app.config.from_json('missing.json', silent=True)

6
tests/test_reqctx.py

@ -140,12 +140,8 @@ def test_manual_context_binding():
ctx.push() ctx.push()
assert index() == 'Hello World!' assert index() == 'Hello World!'
ctx.pop() ctx.pop()
try: with pytest.raises(RuntimeError):
index() index()
except RuntimeError:
pass
else:
assert 0, 'expected runtime error'
@pytest.mark.skipif(greenlet is None, reason='greenlet not installed') @pytest.mark.skipif(greenlet is None, reason='greenlet not installed')
def test_greenlet_context_copying(): def test_greenlet_context_copying():

14
tests/test_testing.py

@ -100,13 +100,10 @@ def test_session_transactions_no_null_sessions():
app.testing = True app.testing = True
with app.test_client() as c: with app.test_client() as c:
try: with pytest.raises(RuntimeError) as e:
with c.session_transaction() as sess: with c.session_transaction() as sess:
pass pass
except RuntimeError as e: assert 'Session backend did not open a session' in str(e.value)
assert 'Session backend did not open a session' in str(e)
else:
assert False, 'Expected runtime error'
def test_session_transactions_keep_context(): def test_session_transactions_keep_context():
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -124,13 +121,10 @@ def test_session_transaction_needs_cookies():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.testing = True app.testing = True
c = app.test_client(use_cookies=False) c = app.test_client(use_cookies=False)
try: with pytest.raises(RuntimeError) as e:
with c.session_transaction() as s: with c.session_transaction() as s:
pass pass
except RuntimeError as e: assert 'cookies' in str(e.value)
assert 'cookies' in str(e)
else:
assert False, 'Expected runtime error'
def test_test_client_context_binding(): def test_test_client_context_binding():
app = flask.Flask(__name__) app = flask.Flask(__name__)

Loading…
Cancel
Save