Skip to content

Commit 4dc2ef1

Browse files
committed
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).
1 parent e7d5485 commit 4dc2ef1

File tree

5 files changed

+39
-84
lines changed

5 files changed

+39
-84
lines changed

tests/test_basic.py

Lines changed: 15 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -307,12 +307,8 @@ def test_missing_session():
307307
app = flask.Flask(__name__)
308308

309309
def expect_exception(f, *args, **kwargs):
310-
try:
311-
f(*args, **kwargs)
312-
except RuntimeError as e:
313-
assert e.args and 'session is unavailable' in e.args[0]
314-
else:
315-
assert False, 'expected exception'
310+
e = pytest.raises(RuntimeError, f, *args, **kwargs)
311+
assert e.value.args and 'session is unavailable' in e.value.args[0]
316312
with app.test_request_context():
317313
assert flask.session.get('missing_key') is None
318314
expect_exception(flask.session.__setitem__, 'foo', 42)
@@ -853,12 +849,9 @@ def fail():
853849

854850
app.config['TRAP_BAD_REQUEST_ERRORS'] = True
855851
c = app.test_client()
856-
try:
857-
c.get('/fail')
858-
except KeyError as e:
859-
assert isinstance(e, BadRequest)
860-
else:
861-
assert False, 'Expected exception'
852+
with pytest.raises(KeyError) as e:
853+
c.get("/fail")
854+
assert e.errisinstance(BadRequest)
862855

863856

864857
def test_trapping_of_all_http_exceptions():
@@ -888,13 +881,10 @@ def index():
888881
# stack otherwise and we want to ensure that this is not the case
889882
# to not negatively affect other tests.
890883
with app.test_client() as c:
891-
try:
884+
with pytest.raises(DebugFilesKeyError) as e:
892885
c.post('/fail', data={'foo': 'index.txt'})
893-
except DebugFilesKeyError as e:
894-
assert 'no file contents were transmitted' in str(e)
895-
assert 'This was submitted: "index.txt"' in str(e)
896-
else:
897-
assert False, 'Expected exception'
886+
assert 'no file contents were transmitted' in str(e.value)
887+
assert 'This was submitted: "index.txt"' in str(e.value)
898888

899889

900890
def test_response_creation():
@@ -1203,12 +1193,8 @@ def index():
12031193
c = app.test_client()
12041194
if config_key is not None:
12051195
app.config[config_key] = True
1206-
try:
1196+
with pytest.raises(Exception):
12071197
c.get('/')
1208-
except Exception:
1209-
pass
1210-
else:
1211-
assert False, 'expected exception'
12121198
else:
12131199
assert c.get('/').status_code == 500
12141200

@@ -1345,14 +1331,11 @@ def index():
13451331
return 'Awesome'
13461332
assert not app.got_first_request
13471333
assert app.test_client().get('/').data == b'Awesome'
1348-
try:
1334+
with pytest.raises(AssertionError) as e:
13491335
@app.route('/foo')
13501336
def broken():
13511337
return 'Meh'
1352-
except AssertionError as e:
1353-
assert 'A setup function was called' in str(e)
1354-
else:
1355-
assert False, 'Expected exception'
1338+
assert 'A setup function was called' in str(e)
13561339

13571340
app.debug = False
13581341

@@ -1408,14 +1391,11 @@ def test_routing_redirect_debugging():
14081391
def foo():
14091392
return 'success'
14101393
with app.test_client() as c:
1411-
try:
1394+
with pytest.raises(AssertionError) as e:
14121395
c.post('/foo', data={})
1413-
except AssertionError as e:
1414-
assert 'http://localhost/foo/' in str(e)
1415-
assert ('Make sure to directly send '
1416-
'your POST-request to this URL') in str(e)
1417-
else:
1418-
assert False, 'Expected exception'
1396+
assert 'http://localhost/foo/' in str(e)
1397+
assert ('Make sure to directly send '
1398+
'your POST-request to this URL') in str(e)
14191399

14201400
rv = c.get('/foo', data={}, follow_redirects=True)
14211401
assert rv.data == b'success'

tests/test_blueprints.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -174,12 +174,9 @@ def test_templates_and_static(test_apps):
174174
assert flask.url_for('admin.static', filename='test.txt') == '/admin/static/test.txt'
175175

176176
with app.test_request_context():
177-
try:
177+
with pytest.raises(TemplateNotFound) as e:
178178
flask.render_template('missing.html')
179-
except TemplateNotFound as e:
180-
assert e.name == 'missing.html'
181-
else:
182-
assert 0, 'expected exception'
179+
assert e.value.name == 'missing.html'
183180

184181
with flask.Flask(__name__).test_request_context():
185182
assert flask.render_template('nested/nested.txt') == 'I\'m nested'

tests/test_config.py

Lines changed: 17 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -89,12 +89,9 @@ def test_config_from_envvar():
8989
try:
9090
os.environ = {}
9191
app = flask.Flask(__name__)
92-
try:
92+
with pytest.raises(RuntimeError) as e:
9393
app.config.from_envvar('FOO_SETTINGS')
94-
except RuntimeError as e:
95-
assert "'FOO_SETTINGS' is not set" in str(e)
96-
else:
97-
assert 0, 'expected exception'
94+
assert "'FOO_SETTINGS' is not set" in str(e.value)
9895
assert not app.config.from_envvar('FOO_SETTINGS', silent=True)
9996

10097
os.environ = {'FOO_SETTINGS': __file__.rsplit('.', 1)[0] + '.py'}
@@ -108,46 +105,37 @@ def test_config_from_envvar_missing():
108105
env = os.environ
109106
try:
110107
os.environ = {'FOO_SETTINGS': 'missing.cfg'}
111-
try:
108+
with pytest.raises(IOError) as e:
112109
app = flask.Flask(__name__)
113110
app.config.from_envvar('FOO_SETTINGS')
114-
except IOError as e:
115-
msg = str(e)
116-
assert msg.startswith('[Errno 2] Unable to load configuration '
117-
'file (No such file or directory):')
118-
assert msg.endswith("missing.cfg'")
119-
else:
120-
assert False, 'expected IOError'
111+
msg = str(e.value)
112+
assert msg.startswith('[Errno 2] Unable to load configuration '
113+
'file (No such file or directory):')
114+
assert msg.endswith("missing.cfg'")
121115
assert not app.config.from_envvar('FOO_SETTINGS', silent=True)
122116
finally:
123117
os.environ = env
124118

125119

126120
def test_config_missing():
127121
app = flask.Flask(__name__)
128-
try:
122+
with pytest.raises(IOError) as e:
129123
app.config.from_pyfile('missing.cfg')
130-
except IOError as e:
131-
msg = str(e)
132-
assert msg.startswith('[Errno 2] Unable to load configuration '
133-
'file (No such file or directory):')
134-
assert msg.endswith("missing.cfg'")
135-
else:
136-
assert 0, 'expected config'
124+
msg = str(e.value)
125+
assert msg.startswith('[Errno 2] Unable to load configuration '
126+
'file (No such file or directory):')
127+
assert msg.endswith("missing.cfg'")
137128
assert not app.config.from_pyfile('missing.cfg', silent=True)
138129

139130

140131
def test_config_missing_json():
141132
app = flask.Flask(__name__)
142-
try:
133+
with pytest.raises(IOError) as e:
143134
app.config.from_json('missing.json')
144-
except IOError as e:
145-
msg = str(e)
146-
assert msg.startswith('[Errno 2] Unable to load configuration '
147-
'file (No such file or directory):')
148-
assert msg.endswith("missing.json'")
149-
else:
150-
assert 0, 'expected config'
135+
msg = str(e.value)
136+
assert msg.startswith('[Errno 2] Unable to load configuration '
137+
'file (No such file or directory):')
138+
assert msg.endswith("missing.json'")
151139
assert not app.config.from_json('missing.json', silent=True)
152140

153141

tests/test_reqctx.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -140,12 +140,8 @@ def index():
140140
ctx.push()
141141
assert index() == 'Hello World!'
142142
ctx.pop()
143-
try:
143+
with pytest.raises(RuntimeError):
144144
index()
145-
except RuntimeError:
146-
pass
147-
else:
148-
assert 0, 'expected runtime error'
149145

150146
@pytest.mark.skipif(greenlet is None, reason='greenlet not installed')
151147
def test_greenlet_context_copying():

tests/test_testing.py

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -100,13 +100,10 @@ def test_session_transactions_no_null_sessions():
100100
app.testing = True
101101

102102
with app.test_client() as c:
103-
try:
103+
with pytest.raises(RuntimeError) as e:
104104
with c.session_transaction() as sess:
105105
pass
106-
except RuntimeError as e:
107-
assert 'Session backend did not open a session' in str(e)
108-
else:
109-
assert False, 'Expected runtime error'
106+
assert 'Session backend did not open a session' in str(e.value)
110107

111108
def test_session_transactions_keep_context():
112109
app = flask.Flask(__name__)
@@ -124,13 +121,10 @@ def test_session_transaction_needs_cookies():
124121
app = flask.Flask(__name__)
125122
app.testing = True
126123
c = app.test_client(use_cookies=False)
127-
try:
124+
with pytest.raises(RuntimeError) as e:
128125
with c.session_transaction() as s:
129126
pass
130-
except RuntimeError as e:
131-
assert 'cookies' in str(e)
132-
else:
133-
assert False, 'Expected runtime error'
127+
assert 'cookies' in str(e.value)
134128

135129
def test_test_client_context_binding():
136130
app = flask.Flask(__name__)

0 commit comments

Comments
 (0)