More DRYing up the test suite (#2325)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Christian Stade-Schuldt · committed by David Lord · parent 50c6df7 · Browse files · 10 files·+230 added−283 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+230 added−283 removed
- tests:+230 added−283 removed
Provenance
- Commit
4ec1fbc- Tree
5e907b7- Author
Christian Stade-Schuldt <tafkasorg@yahoo.de>- Committer
David Lord <davidism@gmail.com>- Parent
50c6df7
10 files changed+230 added−283 removed
modified:tests/test_basic.py+125 added-182 removed
949 unmodified lines950 assert client.get('/2').data == b'apple'951 assert client.get('/3').data == b'apple'952 953 954-def test_trapping_of_bad_request_key_errors(app):954+def test_trapping_of_bad_request_key_errors(app, client):955 @app.route('/fail')956 def fail():957 flask.request.form['missing_key']958 959- c = app.test_client()960- assert c.get('/fail').status_code == 400959+ assert client.get('/fail').status_code == 400960 961 app.config['TRAP_BAD_REQUEST_ERRORS'] = True963- c = app.test_client()962 with pytest.raises(KeyError) as e:965- c.get("/fail")963+ client.get("/fail")964 assert e.errisinstance(BadRequest)965 966 967 def test_trapping_of_all_http_exceptions(app, client):17 unmodified lines985 986 # with statement is important because we leave an exception on the987 # stack otherwise and we want to ensure that this is not the case988 # to not negatively affect other tests.991- with client as c:989+ with client:990 with pytest.raises(DebugFilesKeyError) as e:993- c.post('/fail', data={'foo': 'index.txt'})991+ client.post('/fail', data={'foo': 'index.txt'})992 assert 'no file contents were transmitted' in str(e.value)993 assert 'This was submitted: "index.txt"' in str(e.value)994 995 998-def test_response_types():999- app = flask.Flask(__name__)1000- app.testing = True1001-996+def test_response_types(app, client):997 @app.route('/text')998 def from_text():999 return u'Hällo Wörld'1000 33 unmodified lines1034 @app.route('/wsgi')1035 def from_wsgi():1036 return NotFound()1037 1043- c = app.test_client()1038+ assert client.get('/text').data == u'Hällo Wörld'.encode('utf-8')1039+ assert client.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')1040 1045- assert c.get('/text').data == u'Hällo Wörld'.encode('utf-8')1046- assert c.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')1047-1048- rv = c.get('/full_tuple')1041+ rv = client.get('/full_tuple')1042 assert rv.data == b'Meh'1043 assert rv.headers['X-Foo'] == 'Testing'1044 assert rv.status_code == 4001045 assert rv.mimetype == 'text/plain'1046 1054- rv = c.get('/text_headers')1047+ rv = client.get('/text_headers')1048 assert rv.data == b'Hello'1049 assert rv.headers['X-Foo'] == 'Test'1050 assert rv.status_code == 2001051 assert rv.mimetype == 'text/plain'1052 1060- rv = c.get('/text_status')1053+ rv = client.get('/text_status')1054 assert rv.data == b'Hi, status!'1055 assert rv.status_code == 4001056 assert rv.mimetype == 'text/html'1057 1065- rv = c.get('/response_headers')1058+ rv = client.get('/response_headers')1059 assert rv.data == b'Hello world'1060 assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar']1061 assert rv.headers['X-Bar'] == 'Foo'1062 assert rv.status_code == 4041063 1071- rv = c.get('/response_status')1064+ rv = client.get('/response_status')1065 assert rv.data == b'Hello world'1066 assert rv.status_code == 5001067 1075- rv = c.get('/wsgi')1068+ rv = client.get('/wsgi')1069 assert b'Not Found' in rv.data1070 assert rv.status_code == 4041071 1072 39 unmodified lines1112 1113 pytest.raises(TypeError, c.get, '/bad_wsgi')1114 1115 1123-def test_make_response():1124- app = flask.Flask(__name__)1125- with app.test_request_context():1126- rv = flask.make_response()1127- assert rv.status_code == 2001128- assert rv.data == b''1129- assert rv.mimetype == 'text/html'1116+def test_make_response(app, req_ctx):1117+ rv = flask.make_response()1118+ assert rv.status_code == 2001119+ assert rv.data == b''1120+ assert rv.mimetype == 'text/html'1121 1131- rv = flask.make_response('Awesome')1132- assert rv.status_code == 2001133- assert rv.data == b'Awesome'1134- assert rv.mimetype == 'text/html'1122+ rv = flask.make_response('Awesome')1123+ assert rv.status_code == 2001124+ assert rv.data == b'Awesome'1125+ assert rv.mimetype == 'text/html'1126 1136- rv = flask.make_response('W00t', 404)1137- assert rv.status_code == 4041138- assert rv.data == b'W00t'1139- assert rv.mimetype == 'text/html'1127+ rv = flask.make_response('W00t', 404)1128+ assert rv.status_code == 4041129+ assert rv.data == b'W00t'1130+ assert rv.mimetype == 'text/html'1131 1132 1142-def test_make_response_with_response_instance():1143- app = flask.Flask(__name__)1144- with app.test_request_context():1145- rv = flask.make_response(1146- flask.jsonify({'msg': 'W00t'}), 400)1147- assert rv.status_code == 4001148- assert rv.data == b'{"msg":"W00t"}\n'1149- assert rv.mimetype == 'application/json'1133+def test_make_response_with_response_instance(app, req_ctx):1134+ rv = flask.make_response(1135+ flask.jsonify({'msg': 'W00t'}), 400)1136+ assert rv.status_code == 4001137+ assert rv.data == b'{"msg":"W00t"}\n'1138+ assert rv.mimetype == 'application/json'1139 1151- rv = flask.make_response(1152- flask.Response(''), 400)1153- assert rv.status_code == 4001154- assert rv.data == b''1155- assert rv.mimetype == 'text/html'1140+ rv = flask.make_response(1141+ flask.Response(''), 400)1142+ assert rv.status_code == 4001143+ assert rv.data == b''1144+ assert rv.mimetype == 'text/html'1145 1157- rv = flask.make_response(1158- flask.Response('', headers={'Content-Type': 'text/html'}),1159- 400, [('X-Foo', 'bar')])1160- assert rv.status_code == 4001161- assert rv.headers['Content-Type'] == 'text/html'1162- assert rv.headers['X-Foo'] == 'bar'1146+ rv = flask.make_response(1147+ flask.Response('', headers={'Content-Type': 'text/html'}),1148+ 400, [('X-Foo', 'bar')])1149+ assert rv.status_code == 4001150+ assert rv.headers['Content-Type'] == 'text/html'1151+ assert rv.headers['X-Foo'] == 'bar'1152 1153 1165-def test_jsonify_no_prettyprint():1166- app = flask.Flask(__name__)1154+def test_jsonify_no_prettyprint(app, req_ctx):1155 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1168- with app.test_request_context():1169- compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1170- uncompressed_msg = {1171- "msg": {1172- "submsg": "W00t"1173- },1174- "msg2": "foobar"1175- }1156+ compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1157+ uncompressed_msg = {1158+ "msg": {1159+ "submsg": "W00t"1160+ },1161+ "msg2": "foobar"1162+ }1163 1177- rv = flask.make_response(1178- flask.jsonify(uncompressed_msg), 200)1179- assert rv.data == compressed_msg1164+ rv = flask.make_response(1165+ flask.jsonify(uncompressed_msg), 200)1166+ assert rv.data == compressed_msg1167 1168 1182-def test_jsonify_prettyprint():1183- app = flask.Flask(__name__)1169+def test_jsonify_prettyprint(app, req_ctx):1170 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1185- with app.test_request_context():1186- compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1187- pretty_response = \1188- b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'1171+ compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1172+ pretty_response = \1173+ b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'1174 1190- rv = flask.make_response(1191- flask.jsonify(compressed_msg), 200)1192- assert rv.data == pretty_response1175+ rv = flask.make_response(1176+ flask.jsonify(compressed_msg), 200)1177+ assert rv.data == pretty_response1178 1179 1195-def test_jsonify_mimetype():1196- app = flask.Flask(__name__)1180+def test_jsonify_mimetype(app, req_ctx):1181 app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'})1198- with app.test_request_context():1199- msg = {1200- "msg": {"submsg": "W00t"},1201- }1202- rv = flask.make_response(1203- flask.jsonify(msg), 200)1204- assert rv.mimetype == 'application/vnd.api+json'1182+ msg = {1183+ "msg": {"submsg": "W00t"},1184+ }1185+ rv = flask.make_response(1186+ flask.jsonify(msg), 200)1187+ assert rv.mimetype == 'application/vnd.api+json'1188 1189 1207-def test_jsonify_args_and_kwargs_check():1208- app = flask.Flask(__name__)1209- with app.test_request_context():1210- with pytest.raises(TypeError) as e:1211- flask.jsonify('fake args', kwargs='fake')1212- assert 'behavior undefined' in str(e.value)1190+def test_jsonify_args_and_kwargs_check(app, req_ctx):1191+ with pytest.raises(TypeError) as e:1192+ flask.jsonify('fake args', kwargs='fake')1193+ assert 'behavior undefined' in str(e.value)1194 1195 1215-def test_url_generation():1216- app = flask.Flask(__name__)1217-1196+def test_url_generation(app, req_ctx):1197 @app.route('/hello/<name>', methods=['POST'])1198 def hello():1199 pass1200 1222- with app.test_request_context():1223- assert flask.url_for('hello', name='test x') == '/hello/test%20x'1224- assert flask.url_for('hello', name='test x', _external=True) == \1225- 'http://localhost/hello/test%20x'1201+ assert flask.url_for('hello', name='test x') == '/hello/test%20x'1202+ assert flask.url_for('hello', name='test x', _external=True) == \1203+ 'http://localhost/hello/test%20x'1204 1205 1228-def test_build_error_handler():1229- app = flask.Flask(__name__)1230-1206+def test_build_error_handler(app):1207 # Test base case, a URL which results in a BuildError.1208 with app.test_request_context():1209 pytest.raises(BuildError, flask.url_for, 'spam')1210 18 unmodified lines1229 with app.test_request_context():1230 assert flask.url_for('spam') == '/test_handler/'1231 1232 1257-def test_build_error_handler_reraise():1258- app = flask.Flask(__name__)1259-1233+def test_build_error_handler_reraise(app):1234 # Test a custom handler which reraises the BuildError1235 def handler_raises_build_error(error, endpoint, values):1236 raise error1237 2 unmodified lines1240 with app.test_request_context():1241 pytest.raises(BuildError, flask.url_for, 'not.existing')1242 1243 1270-def test_url_for_passes_special_values_to_build_error_handler():1271- app = flask.Flask(__name__)1272-1244+def test_url_for_passes_special_values_to_build_error_handler(app):1245 @app.url_build_error_handlers.append1246 def handler(error, endpoint, values):1247 assert values == {1248 '_external': False,6 unmodified lines1255 with app.test_request_context():1256 flask.url_for('/')1257 1258 1287-def test_custom_converters():1259+def test_custom_converters(app, client):1260 from werkzeug.routing import BaseConverter1261 1262 class ListConverter(BaseConverter):1263 def to_python(self, value):2 unmodified lines1266 def to_url(self, value):1267 base_to_url = super(ListConverter, self).to_url1268 return ','.join(base_to_url(x) for x in value)1269 1298- app = flask.Flask(__name__)1270 app.url_map.converters['list'] = ListConverter1271 1272 @app.route('/<list:args>')1273 def index(args):1274 return '|'.join(args)1275 1305- c = app.test_client()1306- assert c.get('/1,2,3').data == b'1|2|3'1276+ assert client.get('/1,2,3').data == b'1|2|3'1277 1278 1309-def test_static_files():1310- app = flask.Flask(__name__)1311- app.testing = True1312- rv = app.test_client().get('/static/index.html')1279+def test_static_files(app, client):1280+ rv = client.get('/static/index.html')1281 assert rv.status_code == 2001282 assert rv.data.strip() == b'<h1>Hello World!</h1>'1283 with app.test_request_context():1284 assert flask.url_for('static', filename='index.html') == \48 unmodified lines1333 assert repr(flask.g) == '<LocalProxy unbound>'1334 assert not flask.g1335 1336 1369-def test_test_app_proper_environ():1370- app = flask.Flask(__name__)1337+def test_test_app_proper_environ(app, client):1338 app.config.update(1339 SERVER_NAME='localhost.localdomain:5000'1340 )1341 4 unmodified lines1346 @app.route('/', subdomain='foo')1347 def subdomain():1348 return 'Foo SubDomain'1349 1383- rv = app.test_client().get('/')1350+ rv = client.get('/')1351 assert rv.data == b'Foo'1352 1386- rv = app.test_client().get('/', 'http://localhost.localdomain:5000')1353+ rv = client.get('/', 'http://localhost.localdomain:5000')1354 assert rv.data == b'Foo'1355 1389- rv = app.test_client().get('/', 'https://localhost.localdomain:5000')1356+ rv = client.get('/', 'https://localhost.localdomain:5000')1357 assert rv.data == b'Foo'1358 1359 app.config.update(SERVER_NAME='localhost.localdomain')1393- rv = app.test_client().get('/', 'https://localhost.localdomain')1360+ rv = client.get('/', 'https://localhost.localdomain')1361 assert rv.data == b'Foo'1362 1363 try:1364 app.config.update(SERVER_NAME='localhost.localdomain:443')1398- rv = app.test_client().get('/', 'https://localhost.localdomain')1365+ rv = client.get('/', 'https://localhost.localdomain')1366 # Werkzeug 0.81367 assert rv.status_code == 4041368 except ValueError as e:1369 # Werkzeug 0.74 unmodified lines1374 )1375 1376 try:1377 app.config.update(SERVER_NAME='localhost.localdomain')1411- rv = app.test_client().get('/', 'http://foo.localhost')1378+ rv = client.get('/', 'http://foo.localhost')1379 # Werkzeug 0.81380 assert rv.status_code == 4041381 except ValueError as e:1382 # Werkzeug 0.72 unmodified lines1385 "('localhost.localdomain') does not match the "1386 "server name from the WSGI environment ('foo.localhost')"1387 )1388 1422- rv = app.test_client().get('/', 'http://foo.localhost.localdomain')1389+ rv = client.get('/', 'http://foo.localhost.localdomain')1390 assert rv.data == b'Foo SubDomain'1391 1392 1426-def test_exception_propagation():1393+def test_exception_propagation(app, client):1394 def apprunner(config_key):1428- app = flask.Flask(__name__)1395 app.config['LOGGER_HANDLER_POLICY'] = 'never'1396 1397 @app.route('/')1398 def index():1399 1 // 01400 1435- c = app.test_client()1401 if config_key is not None:1402 app.config[config_key] = True1403 with pytest.raises(Exception):1439- c.get('/')1404+ client.get('/')1405 else:1441- assert c.get('/').status_code == 5001406+ assert client.get('/').status_code == 5001407 1408 # we have to run this test in an isolated thread because if the1409 # debug flag is set to true and an exception happens the context is1410 # not torn down. This causes other tests that run after this fail8 unmodified lines1419 @pytest.mark.parametrize('use_debugger', [True, False])1420 @pytest.mark.parametrize('use_reloader', [True, False])1421 @pytest.mark.parametrize('propagate_exceptions', [None, True, False])1422 def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1458- use_reloader, propagate_exceptions):1423+ use_reloader, propagate_exceptions, app):1424 rv = {}1425 1426 # Mocks werkzeug.serving.run_simple method1427 def run_simple_mock(*args, **kwargs):1428 rv['passthrough_errors'] = kwargs.get('passthrough_errors')1429 1465- app = flask.Flask(__name__)1430 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1431 app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1432 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)1433 1434 1471-def test_max_content_length():1472- app = flask.Flask(__name__)1435+def test_max_content_length(app, client):1436 app.config['MAX_CONTENT_LENGTH'] = 641437 1438 @app.before_request1439 def always_first():8 unmodified lines1448 @app.errorhandler(413)1449 def catcher(error):1450 return '42'1451 1489- c = app.test_client()1490- rv = c.post('/accept', data={'myfile': 'foo' * 100})1452+ rv = client.post('/accept', data={'myfile': 'foo' * 100})1453 assert rv.data == b'42'1454 1455 1494-def test_url_processors():1495- app = flask.Flask(__name__)1456+def test_url_processors(app, client):1457 1458 @app.url_defaults1459 def add_language_code(endpoint, values):1460 if flask.g.lang_code is not None and \15 unmodified lines1476 @app.route('/foo')1477 def something_else():1478 return flask.url_for('about', lang_code='en')1479 1519- c = app.test_client()1480+ assert client.get('/de/').data == b'/de/about'1481+ assert client.get('/de/about').data == b'/foo'1482+ assert client.get('/foo').data == b'/en/about'1483 1521- assert c.get('/de/').data == b'/de/about'1522- assert c.get('/de/about').data == b'/foo'1523- assert c.get('/foo').data == b'/en/about'1484 1525-1526-def test_inject_blueprint_url_defaults():1485+def test_inject_blueprint_url_defaults(app):1527- app = flask.Flask(__name__)1486 bp = flask.Blueprint('foo.bar.baz', __name__,1487 template_folder='template')1488 1489 @bp.url_defaults16 unmodified lines1506 expected = '/login'1507 assert url == expected1508 1509 1552-def test_nonascii_pathinfo():1553- app = flask.Flask(__name__)1554- app.testing = True1555-1510+def test_nonascii_pathinfo(app, client):1511 @app.route(u'/киртест')1512 def index():1513 return 'Hello World!'1514 1560- c = app.test_client()1561- rv = c.get(u'/киртест')1515+ rv = client.get(u'/киртест')1516 assert rv.data == b'Hello World!'1517 1518 1565-def test_debug_mode_complains_after_first_request():1566- app = flask.Flask(__name__)1519+def test_debug_mode_complains_after_first_request(app, client):1520 app.debug = True1521 1522 @app.route('/')1523 def index():1524 return 'Awesome'1525 1526 assert not app.got_first_request1574- assert app.test_client().get('/').data == b'Awesome'1527+ assert client.get('/').data == b'Awesome'1528 with pytest.raises(AssertionError) as e:1529 @app.route('/foo')1530 def broken():1531 return 'Meh'4 unmodified lines1536 @app.route('/foo')1537 def working():1538 return 'Meh'1539 1587- assert app.test_client().get('/foo').data == b'Meh'1540+ assert client.get('/foo').data == b'Meh'1541 assert app.got_first_request1542 1543 1591-def test_before_first_request_functions():1544+def test_before_first_request_functions(app, client):1545 got = []1593- app = flask.Flask(__name__)1546 1547 @app.before_first_request1548 def foo():1549 got.append(42)1550 1599- c = app.test_client()1600- c.get('/')1551+ client.get('/')1552 assert got == [42]1602- c.get('/')1553+ client.get('/')1554 assert got == [42]1555 assert app.got_first_request1556 1557 1607-def test_before_first_request_functions_concurrent():1558+def test_before_first_request_functions_concurrent(app, client):1559 got = []1609- app = flask.Flask(__name__)1560 1561 @app.before_first_request1562 def foo():1563 time.sleep(0.2)1564 got.append(42)1565 1616- c = app.test_client()1617-1566 def get_and_assert():1619- c.get("/")1567+ client.get("/")1568 assert got == [42]1569 1570 t = Thread(target=get_and_assert)1571 t.start()1 unmodified line1573 t.join()1574 assert app.got_first_request1575 1576 1629-def test_routing_redirect_debugging():1630- app = flask.Flask(__name__)1577+def test_routing_redirect_debugging(app, client):1578 app.debug = True1579 1580 @app.route('/foo/', methods=['GET', 'POST'])1581 def foo():1582 return 'success'1583 1637- with app.test_client() as c:1584+ with client:1585 with pytest.raises(AssertionError) as e:1639- c.post('/foo', data={})1586+ client.post('/foo', data={})1587 assert 'http://localhost/foo/' in str(e)1588 assert ('Make sure to directly send '1589 'your POST-request to this URL') in str(e)1590 1644- rv = c.get('/foo', data={}, follow_redirects=True)1591+ rv = client.get('/foo', data={}, follow_redirects=True)1592 assert rv.data == b'success'1593 1594 app.debug = False1648- with app.test_client() as c:1649- rv = c.post('/foo', data={}, follow_redirects=True)1595+ with client:1596+ rv = client.post('/foo', data={}, follow_redirects=True)1597 assert rv.data == b'success'1598 1599 1653-def test_route_decorator_custom_endpoint():1654- app = flask.Flask(__name__)1600+def test_route_decorator_custom_endpoint(app, client):1601 app.debug = True1602 1603 @app.route('/foo/')1604 def foo():11 unmodified lines1616 assert flask.url_for('foo') == '/foo/'1617 assert flask.url_for('bar') == '/bar/'1618 assert flask.url_for('123') == '/bar/123'1619 1674- c = app.test_client()1675- assert c.get('/foo/').data == b'foo'1676- assert c.get('/bar/').data == b'bar'1677- assert c.get('/bar/123').data == b'123'1620+ assert client.get('/foo/').data == b'foo'1621+ assert client.get('/bar/').data == b'bar'1622+ assert client.get('/bar/123').data == b'123'1623 1624 1680-def test_preserve_only_once():1681- app = flask.Flask(__name__)1625+def test_preserve_only_once(app, client):1626 app.debug = True1627 1628 @app.route('/fail')1629 def fail_func():1630 1 // 01631 1688- c = app.test_client()1632 for x in range(3):1633 with pytest.raises(ZeroDivisionError):1691- c.get('/fail')1634+ client.get('/fail')1635 1636 assert flask._request_ctx_stack.top is not None1637 assert flask._app_ctx_stack.top is not None1638 # implicit appctx disappears too160 unmodified linesmodified:tests/test_blueprints.py+8 added
716 unmodified lines717 with app.app_context():718 rv = flask.render_template_string('{{ get_answer() }}')719 assert rv == '42'720 721+722 def test_request_processing(app, client):723 bp = flask.Blueprint('bp', __name__)724 evts = []725+726 @bp.before_request727 def before_bp():728 evts.append('before')729+730 @bp.after_request731 def after_bp(response):732 response.data += b'|after'733 evts.append('after')734 return response735+736 @bp.teardown_request737 def teardown_bp(exc):738 evts.append('teardown')739 8 unmodified lines748 rv = client.get('/bp')749 assert rv.data == b'request|after'750 assert evts == ['before', 'after', 'teardown']751 752+753 def test_app_request_processing(app, client):754 bp = flask.Blueprint('bp', __name__)755 evts = []756 757 @bp.before_app_first_request758 def before_first_request():759 evts.append('first')760+761 @bp.before_app_request762 def before_app():763 evts.append('before')764+765 @bp.after_app_request766 def after_app(response):767 response.data += b'|after'768 evts.append('after')769 return response770+771 @bp.teardown_app_request772 def teardown_app(exc):773 evts.append('teardown')774 46 unmodified linesmodified:tests/test_cli.py+22 added
38 unmodified lines39 40 def test_find_best_app(test_apps):41 """Test if `find_best_app` behaves as expected with different combinations of input."""42 script_info = ScriptInfo()43+44 class Module:45 app = Flask('appname')46+47 assert find_best_app(script_info, Module) == Module.app48 49 class Module:50 application = Flask('appname')51+52 assert find_best_app(script_info, Module) == Module.application53 54 class Module:55 myapp = Flask('appname')56+57 assert find_best_app(script_info, Module) == Module.myapp58 59 class Module:60 @staticmethod61 def create_app():62 return Flask('appname')63+64 assert isinstance(find_best_app(script_info, Module), Flask)65 assert find_best_app(script_info, Module).name == 'appname'66 67 class Module:68 @staticmethod69 def create_app(foo):70 return Flask('appname')71+72 assert isinstance(find_best_app(script_info, Module), Flask)73 assert find_best_app(script_info, Module).name == 'appname'74 75 class Module:76 @staticmethod77 def create_app(foo=None, script_info=None):78 return Flask('appname')79+80 assert isinstance(find_best_app(script_info, Module), Flask)81 assert find_best_app(script_info, Module).name == 'appname'82 83 class Module:84 @staticmethod85 def make_app():86 return Flask('appname')87+88 assert isinstance(find_best_app(script_info, Module), Flask)89 assert find_best_app(script_info, Module).name == 'appname'90 91 class Module:92 myapp = Flask('appname1')93+94 @staticmethod95 def create_app():96 return Flask('appname2')97+98 assert find_best_app(script_info, Module) == Module.myapp99 100 class Module:101 myapp = Flask('appname1')102+103 @staticmethod104 def create_app():105 return Flask('appname2')106+107 assert find_best_app(script_info, Module) == Module.myapp108 109 class Module:110 pass111+112 pytest.raises(NoAppException, find_best_app, script_info, Module)113 114 class Module:115 myapp1 = Flask('appname1')116 myapp2 = Flask('appname2')117+118 pytest.raises(NoAppException, find_best_app, script_info, Module)119 120 class Module:121 @staticmethod122 def create_app(foo, bar):123 return Flask('appname2')124+125 pytest.raises(NoAppException, find_best_app, script_info, Module)126 127 128 def test_prepare_exec_for_file(test_apps):48 unmodified lines177 def test_get_version(test_apps, capsys):178 """Test of get_version."""179 from flask import __version__ as flask_ver180 from sys import version as py_ver181+182 class MockCtx(object):183 resilient_parsing = False184 color = None185+186 def exit(self): return187+188 ctx = MockCtx()189 get_version(ctx, None, "test")190 out, err = capsys.readouterr()191 assert flask_ver in out16 unmodified lines208 209 210 def test_with_appcontext(runner):211 """Test of with_appcontext."""212+213 @click.command()214 @with_appcontext215 def testcmd():216 click.echo(current_app.name)6 unmodified lines223 224 225 def test_appgroup(runner):226 """Test of with_appcontext."""227+228 @click.group(cls=AppGroup)229 def cli():230 pass231 21 unmodified lines253 254 255 def test_flaskgroup(runner):256 """Test FlaskGroup."""257+258 def create_app(info):259 return Flask("flaskgroup")260 261 @click.group(cls=FlaskGroup, create_app=create_app)10 unmodified lines272 273 274 def test_print_exceptions(runner):275 """Print the stacktrace if the CLI."""276+277 def create_app(info):278 raise Exception("oh no")279 return Flask("flaskgroup")280 66 unmodified linesmodified:tests/test_deprecations.py-2 removed
15 unmodified lines16 17 class TestRequestDeprecation(object):18 def test_request_json(self, recwarn, app, client):19 """Request.json is deprecated"""20- app.testing = True20 21 @app.route('/', methods=['POST'])22 def index():23 assert flask.request.json == {'spam': 42}4 unmodified lines28 recwarn.pop(DeprecationWarning)29 30 def test_request_module(self, recwarn, app, client):31 """Request.module is deprecated"""33- app.testing = True32 33 @app.route('/')34 def index():35 assert flask.request.module is None4 unmodified linesmodified:tests/test_helpers.py+8 added-20 removed
83 unmodified lines84 rv = client.post('/json', data='"foo"', content_type='application/x+json')85 assert rv.data == b'foo'86 87 def test_json_body_encoding(self, app, client):88- app.testing = True88 89 @app.route('/')90 def index():91 return flask.request.get_json()147 unmodified lines239 if len(obj) == 1 and '_foo' in obj:240 return X(obj['_foo'])241 return obj242 244- app.testing = True243 app.json_encoder = MyEncoder244 app.json_decoder = MyDecoder245 246 @app.route('/', methods=['POST'])35 unmodified lines282 @bp.route('/bp', methods=['POST'])283 def index():284 return flask.json.dumps(flask.request.get_json()['x'])285 288- app.testing = True286 app.register_blueprint(bp)287 288 rv = client.post('/bp', data=flask.json.dumps({289 'x': {'_foo': 42}290 }), content_type='application/json')291 assert rv.data == b'"<42>"'292 296- def test_modified_url_encoding(self, app):293+ def test_modified_url_encoding(self, app, client):294 class ModifiedRequest(flask.Request):295 url_charset = 'euc-kr'296 300- app.testing = True297 app.request_class = ModifiedRequest298 app.url_map.charset = 'euc-kr'299 300 @app.route('/')301 def index():302 return flask.request.args['foo']303 308- rv = app.test_client().get(u'/?foo=정상처리'.encode('euc-kr'))304+ rv = client.get(u'/?foo=정상처리'.encode('euc-kr'))305 assert rv.status_code == 200306 assert rv.data == u'정상처리'.encode('utf-8')307 308 if not has_encoding('euc-kr'):309 test_modified_url_encoding = None310 311 def test_json_key_sorting(self, app, client):316- app.testing = True312 app.debug = True313 314 assert app.config['JSON_SORT_KEYS'] == True315 d = dict.fromkeys(range(20), 'foo')216 unmodified lines532 assert rv.status_code == 200533 rv.close()534 535 def test_attachment(self, app, req_ctx):541- app = flask.Flask(__name__)536 537 with open(os.path.join(app.root_path, 'static/index.html')) as f:538 rv = flask.send_file(f, as_attachment=True,539 attachment_filename='index.html')72 unmodified lines612 assert cc.max_age == 10613 rv.close()614 615 def test_send_from_directory(self, app, req_ctx):622- app.testing = True616 app.root_path = os.path.join(os.path.dirname(__file__),617 'test_apps', 'subdomaintestmodule')618 rv = flask.send_from_directory('static', 'hello.txt')619 rv.direct_passthrough = False620 assert rv.data.strip() == b'Hello Subdomain'621 rv.close()622 623 def test_send_from_directory_bad_request(self, app, req_ctx):631- app.testing = True624 app.root_path = os.path.join(os.path.dirname(__file__),625 'test_apps', 'subdomaintestmodule')626 627 with pytest.raises(BadRequest):8 unmodified lines636 assert logger1.name == __name__637 app.logger_name = __name__ + '/test_logger_cache'638 assert app.logger is not logger1639 648- def test_debug_log(self, capsys):649- app = flask.Flask(__name__)640+ def test_debug_log(self, capsys, app, client):641 app.debug = True642 643 @app.route('/')644 def index():4 unmodified lines649 @app.route('/exc')650 def exc():651 1 // 0652 662- with app.test_client() as c:663- c.get('/')653+ with client:654+ client.get('/')655 out, err = capsys.readouterr()656 assert 'WARNING in test_helpers [' in err657 assert os.path.basename(__file__.rsplit('.', 1)[0] + '.py') in err658 assert 'the standard library is dead' in err659 assert 'this is a debug statement' in err660 661 with pytest.raises(ZeroDivisionError):671- c.get('/exc')662+ client.get('/exc')663 664 def test_debug_log_override(self, app):665 app.debug = True666 app.logger_name = 'flask_tests/test_debug_log_override'667 app.logger.level = 10668 assert app.logger.level == 10669 679- def test_exception_logging(self, app):670+ def test_exception_logging(self, app, client):671 out = StringIO()672 app.config['LOGGER_HANDLER_POLICY'] = 'never'673 app.logger_name = 'flask_tests/test_exception_logging'674 app.logger.addHandler(StreamHandler(out))2 unmodified lines677 @app.route('/')678 def index():679 1 // 0680 690- rv = app.test_client().get('/')681+ rv = client.get('/')682 assert rv.status_code == 500683 assert b'Internal Server Error' in rv.data684 685 err = out.getvalue()112 unmodified lines798 799 800 class TestStreaming(object):801 def test_streaming_with_context(self, app, client):811- app.testing = True802 803 @app.route('/')804 def index():805 def generate():6 unmodified lines812 rv = client.get('/?name=World')813 assert rv.data == b'Hello World!'814 815 def test_streaming_with_context_as_decorator(self, app, client):826- app.testing = True816 817 @app.route('/')818 def index():819 @flask.stream_with_context7 unmodified lines827 rv = client.get('/?name=World')828 assert rv.data == b'Hello World!'829 830 def test_streaming_with_context_and_custom_close(self, app, client):842- app.testing = True831 called = []832 833 class Wrapper(object):834 def __init__(self, gen):96 unmodified linesmodified:tests/test_regression.py+1 added-3 removed
74 unmodified lines75 with pytest.raises(NotFound):76 safe_join('/foo', '..')77 78 79-def test_aborting():79+def test_aborting(app):80 class Foo(Exception):81 whatever = 4282- app = flask.Flask(__name__)83- app.testing = True82 83 @app.errorhandler(Foo)84 def handle_foo(e):85 return str(e.whatever)14 unmodified linesmodified:tests/test_signals.py+8 added-4 removed
16 unmodified lines17 blinker = None18 19 import flask20 21-21 pytestmark = pytest.mark.skipif(22 blinker is None,23 reason='Signals require the blinker library.'24 )25 27-def test_template_rendered():28- app = flask.Flask(__name__)26 27+def test_template_rendered(app, client):28 @app.route('/')29 def index():30 return flask.render_template('simple_template.html', whiskey=42)31 3 unmodified lines35 recorded.append((template, context))36 37 flask.template_rendered.connect(record, app)38 try:41- app.test_client().get('/')39+ client.get('/')40 assert len(recorded) == 141 template, context = recorded[0]42 assert template.name == 'simple_template.html'43 assert context['whiskey'] == 4244 finally:45 flask.template_rendered.disconnect(record, app)46 47+48 def test_before_render_template():49 app = flask.Flask(__name__)50 51 @app.route('/')16 unmodified lines68 assert rv.data == b'<h1>43</h1>'69 finally:70 flask.before_render_template.disconnect(record, app)71 72+73 def test_request_signals():74 app = flask.Flask(__name__)75 calls = []76 31 unmodified lines108 finally:109 flask.request_started.disconnect(before_request_signal, app)110 flask.request_finished.disconnect(after_request_signal, app)111 112+113 def test_request_exception_signal():114 app = flask.Flask(__name__)115 recorded = []116 11 unmodified lines128 assert isinstance(recorded[0], ZeroDivisionError)129 finally:130 flask.got_request_exception.disconnect(record, app)131 132+133 def test_appcontext_signals():134 app = flask.Flask(__name__)135 recorded = []136 18 unmodified lines155 finally:156 flask.appcontext_pushed.disconnect(record_push, app)157 flask.appcontext_popped.disconnect(record_pop, app)158 159+160 def test_flash_signal():161 app = flask.Flask(__name__)162 app.config['SECRET_KEY'] = 'secret'163 18 unmodified lines182 assert category == 'notice'183 finally:184 flask.message_flashed.disconnect(record, app)185 186+187 def test_appcontext_tearing_down_signal():188 app = flask.Flask(__name__)189 recorded = []190 16 unmodified linesmodified:tests/test_templating.py+4 added-4 removed
14 unmodified lines15 import logging16 from jinja2 import TemplateNotFound17 18 19-def test_context_processing(app):19+def test_context_processing(app, client):20 @app.context_processor21 def context_processor():22 return {'injected_value': 42}23 24 @app.route('/')25 def index():26 return flask.render_template('context_template.html', value=23)27 28- rv = app.test_client().get('/')28+ rv = client.get('/')29 assert rv.data == b'<p>23|42'30 31 32 def test_original_win(app, client):219 unmodified lines252 assert app.jinja_env.tests['boolean'] == is_boolean253 assert app.jinja_env.tests['boolean'](False)254 255 256-def test_template_test_with_template(app):256+def test_template_test_with_template(app, client):257 @app.template_test()258 def boolean(value):259 return isinstance(value, bool)260 261 @app.route('/')262 def index():263 return flask.render_template('template_test.html', value=False)264 265- rv = app.test_client().get('/')265+ rv = client.get('/')266 assert b'Success!' in rv.data267 268 269 def test_add_template_test_with_template(app, client):165 unmodified linesmodified:tests/test_testing.py+38 added-46 removed
36 unmodified lines37 return flask.request.url38 39 ctx = app.test_request_context()40 assert ctx.request.url == 'http://localhost/'41- with app.test_client() as c:42- rv = c.get('/')41+ with client:42+ rv = client.get('/')43 assert rv.data == b'http://localhost/'44 45 46 def test_environ_base_default(app, client, app_ctx):47- app.testing = True48-47 @app.route('/')48 def index():49 flask.g.user_agent = flask.request.headers["User-Agent"]50 return flask.request.remote_addr35 unmodified lines86 @app.route('/getsession')87 def get_session():88 return flask.session.get('data', '<missing>')89 92- with client as c:93- rv = c.get('/getsession')90+ with client:91+ rv = client.get('/getsession')92 assert rv.data == b'<missing>'93 96- rv = c.get('/')94+ rv = client.get('/')95 assert rv.data == b'index'96 assert flask.session.get('data') == 'foo'99- rv = c.post('/', data={}, follow_redirects=True)97+ rv = client.post('/', data={}, follow_redirects=True)98 assert rv.data == b'foo'99 100 # This support requires a new Werkzeug version103- if not hasattr(c, 'redirect_client'):101+ if not hasattr(client, 'redirect_client'):102 assert flask.session.get('data') == 'foo'103 106- rv = c.get('/getsession')104+ rv = client.get('/getsession')105 assert rv.data == b'foo'106 107 110-def test_session_transactions(app):108+def test_session_transactions(app, client):109 app.secret_key = 'testing'110 111 @app.route('/')112 def index():113 return text_type(flask.session['foo'])114 117- with app.test_client() as c:118- with c.session_transaction() as sess:115+ with client:116+ with client.session_transaction() as sess:117 assert len(sess) == 0118 sess['foo'] = [42]119 assert len(sess) == 1122- rv = c.get('/')120+ rv = client.get('/')121 assert rv.data == b'[42]'124- with c.session_transaction() as sess:122+ with client.session_transaction() as sess:123 assert len(sess) == 1124 assert sess['foo'] == [42]125 126 16 unmodified lines143 assert req is not None144 with client.session_transaction():145 assert req is flask.request._get_current_object()146 147+148 def test_session_transaction_needs_cookies(app):149 c = app.test_client(use_cookies=False)150 with pytest.raises(RuntimeError) as e:151 with c.session_transaction() as s:152 pass153 assert 'cookies' in str(e.value)154 155 157-def test_test_client_context_binding():158- app = flask.Flask(__name__)156+def test_test_client_context_binding(app, client):157 app.config['LOGGER_HANDLER_POLICY'] = 'never'158+ app.testing = False159 160 @app.route('/')161 def index():162 flask.g.value = 422 unmodified lines165 @app.route('/other')166 def other():167 1 // 0168 170- with app.test_client() as c:171- resp = c.get('/')169+ with client:170+ resp = client.get('/')171 assert flask.g.value == 42172 assert resp.data == b'Hello World!'173 assert resp.status_code == 200174 176- resp = c.get('/other')175+ resp = client.get('/other')176 assert not hasattr(flask.g, 'value')177 assert b'Internal Server Error' in resp.data178 assert resp.status_code == 500179 flask.g.value = 235 unmodified lines185 else:186 raise AssertionError('some kind of exception expected')187 188 190-def test_reuse_client():191- app = flask.Flask(__name__)192- c = app.test_client()189+def test_reuse_client(client):190+ c = client191 192 with c:195- assert c.get('/').status_code == 404193+ assert client.get('/').status_code == 404194 195 with c:198- assert c.get('/').status_code == 404196+ assert client.get('/').status_code == 404197 198 201-def test_test_client_calls_teardown_handlers():202- app = flask.Flask(__name__)199+def test_test_client_calls_teardown_handlers(app, client):200 called = []201 202 @app.teardown_request203 def remember(error):204 called.append(error)205 209- with app.test_client() as c:206+ with client:207 assert called == []211- c.get('/')208+ client.get('/')209 assert called == []210 assert called == [None]211 212 del called[:]216- with app.test_client() as c:213+ with client:214 assert called == []218- c.get('/')215+ client.get('/')216 assert called == []220- c.get('/')217+ client.get('/')218 assert called == [None]219 assert called == [None, None]220 221 225-def test_full_url_request():226- app = flask.Flask(__name__)227- app.testing = True228-222+def test_full_url_request(app, client):223 @app.route('/action', methods=['POST'])224 def action():225 return 'x'226 233- with app.test_client() as c:234- rv = c.post('http://domain.com/action?vodka=42', data={'gin': 43})227+ with client:228+ rv = client.post('http://domain.com/action?vodka=42', data={'gin': 43})229 assert rv.status_code == 200230 assert 'gin' in flask.request.form231 assert 'vodka' in flask.request.args232 233 240-def test_subdomain():241- app = flask.Flask(__name__)234+def test_subdomain(app, client):235 app.config['SERVER_NAME'] = 'example.com'236 237 @app.route('/', subdomain='<company_id>')238 def view(company_id):1 unmodified line240 241 with app.test_request_context():242 url = flask.url_for('view', company_id='xxx')243 251- with app.test_client() as c:252- response = c.get(url)244+ with client:245+ response = client.get(url)246 247 assert 200 == response.status_code248 assert b'xxx' == response.data249 250 258-def test_nosubdomain():259- app = flask.Flask(__name__)251+def test_nosubdomain(app, client):252 app.config['SERVER_NAME'] = 'example.com'253 254 @app.route('/<company_id>')255 def view(company_id):1 unmodified line257 258 with app.test_request_context():259 url = flask.url_for('view', company_id='xxx')260 269- with app.test_client() as c:270- response = c.get(url)261+ with client:262+ response = client.get(url)263 264 assert 200 == response.status_code265 assert b'xxx' == response.datamodified:tests/test_views.py+16 added-22 removed
70 unmodified lines71 app.add_url_rule('/', view_func=view)72 common_test(app)73 74 75-def test_view_inheritance(app):75+def test_view_inheritance(app, client):76 class Index(flask.views.MethodView):77 def get(self):78 return 'GET'79 4 unmodified lines84 def delete(self):85 return 'DELETE'86 87 app.add_url_rule('/', view_func=BetterIndex.as_view('index'))88- c = app.test_client()88 90- meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])89+ meths = parse_set_header(client.open('/', method='OPTIONS').headers['Allow'])90 assert sorted(meths) == ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST']91 92 94-def test_view_decorators(app):93+def test_view_decorators(app, client):94 def add_x_parachute(f):95 def new_function(*args, **kwargs):96 resp = flask.make_response(f(*args, **kwargs))97 resp.headers['X-Parachute'] = 'awesome'7 unmodified lines105 def dispatch_request(self):106 return 'Awesome'107 108 app.add_url_rule('/', view_func=Index.as_view('index'))110- c = app.test_client()111- rv = c.get('/')109+ rv = client.get('/')110 assert rv.headers['X-Parachute'] == 'awesome'111 assert rv.data == b'Awesome'112 113 36 unmodified lines150 rv = c.open('/', method='OPTIONS')151 assert 'OPTIONS' in rv.allow152 153 156-def test_implicit_head(app):154+def test_implicit_head(app, client):155 class Index(flask.views.MethodView):156 def get(self):157 return flask.Response('Blub', headers={158 'X-Method': flask.request.method159 })160 161 app.add_url_rule('/', view_func=Index.as_view('index'))164- c = app.test_client()165- rv = c.get('/')162+ rv = client.get('/')163 assert rv.data == b'Blub'164 assert rv.headers['X-Method'] == 'GET'168- rv = c.head('/')165+ rv = client.head('/')166 assert rv.data == b''167 assert rv.headers['X-Method'] == 'HEAD'168 169 173-def test_explicit_head(app):170+def test_explicit_head(app, client):171 class Index(flask.views.MethodView):172 def get(self):173 return 'GET'174 175 def head(self):176 return flask.Response('', headers={'X-Method': 'HEAD'})177 178 app.add_url_rule('/', view_func=Index.as_view('index'))182- c = app.test_client()183- rv = c.get('/')179+ rv = client.get('/')180 assert rv.data == b'GET'185- rv = c.head('/')181+ rv = client.head('/')182 assert rv.data == b''183 assert rv.headers['X-Method'] == 'HEAD'184 185 14 unmodified lines200 # But these tests should still pass. We just log a warning.201 common_test(app)202 203 208-def test_multiple_inheritance(app):204+def test_multiple_inheritance(app, client):205 class GetView(flask.views.MethodView):206 def get(self):207 return 'GET'208 5 unmodified lines214 pass215 216 app.add_url_rule('/', view_func=GetDeleteView.as_view('index'))217 222- c = app.test_client()223- assert c.get('/').data == b'GET'224- assert c.delete('/').data == b'DELETE'218+ assert client.get('/').data == b'GET'219+ assert client.delete('/').data == b'DELETE'220 assert sorted(GetDeleteView.methods) == ['DELETE', 'GET']221 222 228-def test_remove_method_from_parent(app):223+def test_remove_method_from_parent(app, client):224 class GetView(flask.views.MethodView):225 def get(self):226 return 'GET'227 5 unmodified lines233 methods = ['GET']234 235 app.add_url_rule('/', view_func=View.as_view('index'))236 242- c = app.test_client()243- assert c.get('/').data == b'GET'244- assert c.post('/').status_code == 405237+ assert client.get('/').data == b'GET'238+ assert client.post('/').status_code == 405239 assert sorted(View.methods) == ['GET']