Skip to content
Myr

Use pytest.raises() instead of try/catch with asser 0

Before adoption: this commit came in with the history the project adopted, so no landing records it.

This is somehow more readable, and enable using the features of pytest's ExeptionInfo (such as errisinstance).

authored by Reuven · committed by Reuven · parent e7d5485 · Browse files · 5 files+39 added−84 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+39 added−84 removed

  • tests:+39 added−84 removed

5 files+39 added−84 removed

modified:tests/test_basic.py+15 added-35 removed
305 unmodified lines
306def test_missing_session():307 app = flask.Flask(__name__)308309 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]312 with app.test_request_context():313 assert flask.session.get('missing_key') is None314 expect_exception(flask.session.__setitem__, 'foo', 42)315 expect_exception(flask.session.pop, 'foo')
532 unmodified lines
848 assert c.get('/fail').status_code == 400849850 app.config['TRAP_BAD_REQUEST_ERRORS'] = True851 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)855856857def test_trapping_of_all_http_exceptions():858 app = flask.Flask(__name__)
21 unmodified lines
880 # with statement is important because we leave an exception on the881 # stack otherwise and we want to ensure that this is not the case882 # to not negatively affect other tests.883 with app.test_client() as c:891 try:884 with pytest.raises(DebugFilesKeyError) as e:885 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)886 assert 'no file contents were transmitted' in str(e.value)887 assert 'This was submitted: "index.txt"' in str(e.value)896 else:897 assert False, 'Expected exception'888889890def test_response_creation():891 app = flask.Flask(__name__)
300 unmodified lines
1192 1 // 01193 c = app.test_client()1194 if config_key is not None:1195 app.config[config_key] = True1206 try:1196 with pytest.raises(Exception):1197 c.get('/')1208 except Exception:1209 pass1210 else:1211 assert False, 'expected exception'1198 else:1199 assert c.get('/').status_code == 50012001201 # we have to run this test in an isolated thread because if the
128 unmodified lines
1330 def index():1331 return 'Awesome'1332 assert not app.got_first_request1333 assert app.test_client().get('/').data == b'Awesome'1348 try:1334 with pytest.raises(AssertionError) as e:1335 @app.route('/foo')1336 def broken():1337 return 'Meh'1352 except AssertionError as e:1353 assert 'A setup function was called' in str(e)1338 assert 'A setup function was called' in str(e)1354 else:1355 assert False, 'Expected exception'13391340 app.debug = False13411342 @app.route('/foo')
47 unmodified lines
1390 @app.route('/foo/', methods=['GET', 'POST'])1391 def foo():1392 return 'success'1393 with app.test_client() as c:1411 try:1394 with pytest.raises(AssertionError) as e:1395 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)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)1417 else:1418 assert False, 'Expected exception'13991400 rv = c.get('/foo', data={}, follow_redirects=True)1401 assert rv.data == b'success'1402
216 unmodified lines
modified:tests/test_blueprints.py+2 added-5 removed
172 unmodified lines
173 with app.test_request_context():174 assert flask.url_for('admin.static', filename='test.txt') == '/admin/static/test.txt'175176 with app.test_request_context():177 try:177 with pytest.raises(TemplateNotFound) as e:178 flask.render_template('missing.html')179 except TemplateNotFound as e:180 assert e.name == 'missing.html'179 assert e.value.name == 'missing.html'181 else:182 assert 0, 'expected exception'180181 with flask.Flask(__name__).test_request_context():182 assert flask.render_template('nested/nested.txt') == 'I\'m nested'183
391 unmodified lines
modified:tests/test_config.py+17 added-29 removed
87 unmodified lines
88 env = os.environ89 try:90 os.environ = {}91 app = flask.Flask(__name__)92 try:92 with pytest.raises(RuntimeError) as e:93 app.config.from_envvar('FOO_SETTINGS')94 except RuntimeError as e:95 assert "'FOO_SETTINGS' is not set" in str(e)94 assert "'FOO_SETTINGS' is not set" in str(e.value)96 else:97 assert 0, 'expected exception'95 assert not app.config.from_envvar('FOO_SETTINGS', silent=True)9697 os.environ = {'FOO_SETTINGS': __file__.rsplit('.', 1)[0] + '.py'}98 assert app.config.from_envvar('FOO_SETTINGS')
5 unmodified lines
104def test_config_from_envvar_missing():105 env = os.environ106 try:107 os.environ = {'FOO_SETTINGS': 'missing.cfg'}111 try:108 with pytest.raises(IOError) as e:109 app = flask.Flask(__name__)110 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'")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'")119 else:120 assert False, 'expected IOError'115 assert not app.config.from_envvar('FOO_SETTINGS', silent=True)116 finally:117 os.environ = env118119120def test_config_missing():121 app = flask.Flask(__name__)128 try:122 with pytest.raises(IOError) as e:123 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'")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'")135 else:136 assert 0, 'expected config'128 assert not app.config.from_pyfile('missing.cfg', silent=True)129130131def test_config_missing_json():132 app = flask.Flask(__name__)142 try:133 with pytest.raises(IOError) as e:134 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'")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'")149 else:150 assert 0, 'expected config'139 assert not app.config.from_json('missing.json', silent=True)140141142def test_custom_config_class():
47 unmodified lines
modified:tests/test_reqctx.py+1 added-5 removed
138 unmodified lines
139 ctx = app.test_request_context('/?name=World')140 ctx.push()141 assert index() == 'Hello World!'142 ctx.pop()143 try:143 with pytest.raises(RuntimeError):144 index()145 except RuntimeError:146 pass147 else:148 assert 0, 'expected runtime error'145146@pytest.mark.skipif(greenlet is None, reason='greenlet not installed')147def test_greenlet_context_copying():148 app = flask.Flask(__name__)
47 unmodified lines
modified:tests/test_testing.py+4 added-10 removed
98 unmodified lines
99 app = flask.Flask(__name__)100 app.testing = True101102 with app.test_client() as c:103 try:103 with pytest.raises(RuntimeError) as e:104 with c.session_transaction() as sess:105 pass106 except RuntimeError as e:107 assert 'Session backend did not open a session' in str(e)106 assert 'Session backend did not open a session' in str(e.value)108 else:109 assert False, 'Expected runtime error'107108def test_session_transactions_keep_context():109 app = flask.Flask(__name__)110 app.testing = True
9 unmodified lines
120def test_session_transaction_needs_cookies():121 app = flask.Flask(__name__)122 app.testing = True123 c = app.test_client(use_cookies=False)127 try:124 with pytest.raises(RuntimeError) as e:125 with c.session_transaction() as s:126 pass130 except RuntimeError as e:131 assert 'cookies' in str(e)127 assert 'cookies' in str(e.value)132 else:133 assert False, 'Expected runtime error'128129def test_test_client_context_binding():130 app = flask.Flask(__name__)131 app.config['LOGGER_HANDLER_POLICY'] = 'never'
105 unmodified lines