Skip to content
Myr

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

10 files+230 added−283 removed

modified:tests/test_basic.py+125 added-182 removed
949 unmodified lines
950 assert client.get('/2').data == b'apple'951 assert client.get('/3').data == b'apple'952953954def test_trapping_of_bad_request_key_errors(app):954def test_trapping_of_bad_request_key_errors(app, client):955 @app.route('/fail')956 def fail():957 flask.request.form['missing_key']958959 c = app.test_client()960 assert c.get('/fail').status_code == 400959 assert client.get('/fail').status_code == 400960961 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)965966967def test_trapping_of_all_http_exceptions(app, client):
17 unmodified lines
985986 # 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)994995998def test_response_types():999 app = flask.Flask(__name__)1000 app.testing = True1001996def test_response_types(app, client):997 @app.route('/text')998 def from_text():999 return u'Hällo Wörld'1000
33 unmodified lines
1034 @app.route('/wsgi')1035 def from_wsgi():1036 return NotFound()10371043 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')10401045 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')10471048 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'10461054 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'10521060 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'10571065 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 == 40410631071 rv = c.get('/response_status')1064 rv = client.get('/response_status')1065 assert rv.data == b'Hello world'1066 assert rv.status_code == 50010671075 rv = c.get('/wsgi')1068 rv = client.get('/wsgi')1069 assert b'Not Found' in rv.data1070 assert rv.status_code == 40410711072
39 unmodified lines
11121113 pytest.raises(TypeError, c.get, '/bad_wsgi')111411151123def 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'1116def 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'11211131 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'11261136 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'113111321142def 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'1133def 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'11391151 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'11451157 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'115211531165def test_jsonify_no_prettyprint():1166 app = flask.Flask(__name__)1154def 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 }11631177 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_msg116711681182def test_jsonify_prettyprint():1183 app = flask.Flask(__name__)1169def 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'11741190 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_response117811791195def test_jsonify_mimetype():1196 app = flask.Flask(__name__)1180def 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'118811891207def 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)1190def 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)119411951215def test_url_generation():1216 app = flask.Flask(__name__)12171196def test_url_generation(app, req_ctx):1197 @app.route('/hello/<name>', methods=['POST'])1198 def hello():1199 pass12001222 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'120412051228def test_build_error_handler():1229 app = flask.Flask(__name__)12301206def 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 lines
1229 with app.test_request_context():1230 assert flask.url_for('spam') == '/test_handler/'123112321257def test_build_error_handler_reraise():1258 app = flask.Flask(__name__)12591233def 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 lines
1240 with app.test_request_context():1241 pytest.raises(BuildError, flask.url_for, 'not.existing')124212431270def test_url_for_passes_special_values_to_build_error_handler():1271 app = flask.Flask(__name__)12721244def 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 lines
1255 with app.test_request_context():1256 flask.url_for('/')125712581287def test_custom_converters():1259def test_custom_converters(app, client):1260 from werkzeug.routing import BaseConverter12611262 class ListConverter(BaseConverter):1263 def to_python(self, value):
2 unmodified lines
1266 def to_url(self, value):1267 base_to_url = super(ListConverter, self).to_url1268 return ','.join(base_to_url(x) for x in value)12691298 app = flask.Flask(__name__)1270 app.url_map.converters['list'] = ListConverter12711272 @app.route('/<list:args>')1273 def index(args):1274 return '|'.join(args)12751305 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'127712781309def test_static_files():1310 app = flask.Flask(__name__)1311 app.testing = True1312 rv = app.test_client().get('/static/index.html')1279def 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 lines
1333 assert repr(flask.g) == '<LocalProxy unbound>'1334 assert not flask.g133513361369def test_test_app_proper_environ():1370 app = flask.Flask(__name__)1337def test_test_app_proper_environ(app, client):1338 app.config.update(1339 SERVER_NAME='localhost.localdomain:5000'1340 )1341
4 unmodified lines
1346 @app.route('/', subdomain='foo')1347 def subdomain():1348 return 'Foo SubDomain'13491383 rv = app.test_client().get('/')1350 rv = client.get('/')1351 assert rv.data == b'Foo'13521386 rv = app.test_client().get('/', 'http://localhost.localdomain:5000')1353 rv = client.get('/', 'http://localhost.localdomain:5000')1354 assert rv.data == b'Foo'13551389 rv = app.test_client().get('/', 'https://localhost.localdomain:5000')1356 rv = client.get('/', 'https://localhost.localdomain:5000')1357 assert rv.data == b'Foo'13581359 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'13621363 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.7
4 unmodified lines
1374 )13751376 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.7
2 unmodified lines
1385 "('localhost.localdomain') does not match the "1386 "server name from the WSGI environment ('foo.localhost')"1387 )13881422 rv = app.test_client().get('/', 'http://foo.localhost.localdomain')1389 rv = client.get('/', 'http://foo.localhost.localdomain')1390 assert rv.data == b'Foo SubDomain'139113921426def test_exception_propagation():1393def test_exception_propagation(app, client):1394 def apprunner(config_key):1428 app = flask.Flask(__name__)1395 app.config['LOGGER_HANDLER_POLICY'] = 'never'13961397 @app.route('/')1398 def index():1399 1 // 014001435 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 == 50014071408 # 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 fail
8 unmodified lines
1419@pytest.mark.parametrize('use_debugger', [True, False])1420@pytest.mark.parametrize('use_reloader', [True, False])1421@pytest.mark.parametrize('propagate_exceptions', [None, True, False])1422def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1458 use_reloader, propagate_exceptions):1423 use_reloader, propagate_exceptions, app):1424 rv = {}14251426 # Mocks werkzeug.serving.run_simple method1427 def run_simple_mock(*args, **kwargs):1428 rv['passthrough_errors'] = kwargs.get('passthrough_errors')14291465 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)143314341471def test_max_content_length():1472 app = flask.Flask(__name__)1435def test_max_content_length(app, client):1436 app.config['MAX_CONTENT_LENGTH'] = 6414371438 @app.before_request1439 def always_first():
8 unmodified lines
1448 @app.errorhandler(413)1449 def catcher(error):1450 return '42'14511489 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'145414551494def test_url_processors():1495 app = flask.Flask(__name__)1456def test_url_processors(app, client):14571458 @app.url_defaults1459 def add_language_code(endpoint, values):1460 if flask.g.lang_code is not None and \
15 unmodified lines
1476 @app.route('/foo')1477 def something_else():1478 return flask.url_for('about', lang_code='en')14791519 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'14831521 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'148415251526def test_inject_blueprint_url_defaults():1485def test_inject_blueprint_url_defaults(app):1527 app = flask.Flask(__name__)1486 bp = flask.Blueprint('foo.bar.baz', __name__,1487 template_folder='template')14881489 @bp.url_defaults
16 unmodified lines
1506 expected = '/login'1507 assert url == expected150815091552def test_nonascii_pathinfo():1553 app = flask.Flask(__name__)1554 app.testing = True15551510def test_nonascii_pathinfo(app, client):1511 @app.route(u'/киртест')1512 def index():1513 return 'Hello World!'15141560 c = app.test_client()1561 rv = c.get(u'/киртест')1515 rv = client.get(u'/киртест')1516 assert rv.data == b'Hello World!'151715181565def test_debug_mode_complains_after_first_request():1566 app = flask.Flask(__name__)1519def test_debug_mode_complains_after_first_request(app, client):1520 app.debug = True15211522 @app.route('/')1523 def index():1524 return 'Awesome'15251526 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 lines
1536 @app.route('/foo')1537 def working():1538 return 'Meh'15391587 assert app.test_client().get('/foo').data == b'Meh'1540 assert client.get('/foo').data == b'Meh'1541 assert app.got_first_request154215431591def test_before_first_request_functions():1544def test_before_first_request_functions(app, client):1545 got = []1593 app = flask.Flask(__name__)15461547 @app.before_first_request1548 def foo():1549 got.append(42)15501599 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_request155615571607def test_before_first_request_functions_concurrent():1558def test_before_first_request_functions_concurrent(app, client):1559 got = []1609 app = flask.Flask(__name__)15601561 @app.before_first_request1562 def foo():1563 time.sleep(0.2)1564 got.append(42)15651616 c = app.test_client()16171566 def get_and_assert():1619 c.get("/")1567 client.get("/")1568 assert got == [42]15691570 t = Thread(target=get_and_assert)1571 t.start()
1 unmodified line
1573 t.join()1574 assert app.got_first_request157515761629def test_routing_redirect_debugging():1630 app = flask.Flask(__name__)1577def test_routing_redirect_debugging(app, client):1578 app.debug = True15791580 @app.route('/foo/', methods=['GET', 'POST'])1581 def foo():1582 return 'success'15831637 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)15901644 rv = c.get('/foo', data={}, follow_redirects=True)1591 rv = client.get('/foo', data={}, follow_redirects=True)1592 assert rv.data == b'success'15931594 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'159815991653def test_route_decorator_custom_endpoint():1654 app = flask.Flask(__name__)1600def test_route_decorator_custom_endpoint(app, client):1601 app.debug = True16021603 @app.route('/foo/')1604 def foo():
11 unmodified lines
1616 assert flask.url_for('foo') == '/foo/'1617 assert flask.url_for('bar') == '/bar/'1618 assert flask.url_for('123') == '/bar/123'16191674 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'162316241680def test_preserve_only_once():1681 app = flask.Flask(__name__)1625def test_preserve_only_once(app, client):1626 app.debug = True16271628 @app.route('/fail')1629 def fail_func():1630 1 // 016311688 c = app.test_client()1632 for x in range(3):1633 with pytest.raises(ZeroDivisionError):1691 c.get('/fail')1634 client.get('/fail')16351636 assert flask._request_ctx_stack.top is not None1637 assert flask._app_ctx_stack.top is not None1638 # implicit appctx disappears too
160 unmodified lines
modified:tests/test_blueprints.py+8 added
716 unmodified lines
717 with app.app_context():718 rv = flask.render_template_string('{{ get_answer() }}')719 assert rv == '42'720721722def test_request_processing(app, client):723 bp = flask.Blueprint('bp', __name__)724 evts = []725726 @bp.before_request727 def before_bp():728 evts.append('before')729730 @bp.after_request731 def after_bp(response):732 response.data += b'|after'733 evts.append('after')734 return response735736 @bp.teardown_request737 def teardown_bp(exc):738 evts.append('teardown')739
8 unmodified lines
748 rv = client.get('/bp')749 assert rv.data == b'request|after'750 assert evts == ['before', 'after', 'teardown']751752753def test_app_request_processing(app, client):754 bp = flask.Blueprint('bp', __name__)755 evts = []756757 @bp.before_app_first_request758 def before_first_request():759 evts.append('first')760761 @bp.before_app_request762 def before_app():763 evts.append('before')764765 @bp.after_app_request766 def after_app(response):767 response.data += b'|after'768 evts.append('after')769 return response770771 @bp.teardown_app_request772 def teardown_app(exc):773 evts.append('teardown')774
46 unmodified lines
modified:tests/test_cli.py+22 added
38 unmodified lines
3940def test_find_best_app(test_apps):41 """Test if `find_best_app` behaves as expected with different combinations of input."""42 script_info = ScriptInfo()4344 class Module:45 app = Flask('appname')4647 assert find_best_app(script_info, Module) == Module.app4849 class Module:50 application = Flask('appname')5152 assert find_best_app(script_info, Module) == Module.application5354 class Module:55 myapp = Flask('appname')5657 assert find_best_app(script_info, Module) == Module.myapp5859 class Module:60 @staticmethod61 def create_app():62 return Flask('appname')6364 assert isinstance(find_best_app(script_info, Module), Flask)65 assert find_best_app(script_info, Module).name == 'appname'6667 class Module:68 @staticmethod69 def create_app(foo):70 return Flask('appname')7172 assert isinstance(find_best_app(script_info, Module), Flask)73 assert find_best_app(script_info, Module).name == 'appname'7475 class Module:76 @staticmethod77 def create_app(foo=None, script_info=None):78 return Flask('appname')7980 assert isinstance(find_best_app(script_info, Module), Flask)81 assert find_best_app(script_info, Module).name == 'appname'8283 class Module:84 @staticmethod85 def make_app():86 return Flask('appname')8788 assert isinstance(find_best_app(script_info, Module), Flask)89 assert find_best_app(script_info, Module).name == 'appname'9091 class Module:92 myapp = Flask('appname1')9394 @staticmethod95 def create_app():96 return Flask('appname2')9798 assert find_best_app(script_info, Module) == Module.myapp99100 class Module:101 myapp = Flask('appname1')102103 @staticmethod104 def create_app():105 return Flask('appname2')106107 assert find_best_app(script_info, Module) == Module.myapp108109 class Module:110 pass111112 pytest.raises(NoAppException, find_best_app, script_info, Module)113114 class Module:115 myapp1 = Flask('appname1')116 myapp2 = Flask('appname2')117118 pytest.raises(NoAppException, find_best_app, script_info, Module)119120 class Module:121 @staticmethod122 def create_app(foo, bar):123 return Flask('appname2')124125 pytest.raises(NoAppException, find_best_app, script_info, Module)126127128def test_prepare_exec_for_file(test_apps):
48 unmodified lines
177def 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_ver181182 class MockCtx(object):183 resilient_parsing = False184 color = None185186 def exit(self): return187188 ctx = MockCtx()189 get_version(ctx, None, "test")190 out, err = capsys.readouterr()191 assert flask_ver in out
16 unmodified lines
208209210def test_with_appcontext(runner):211 """Test of with_appcontext."""212213 @click.command()214 @with_appcontext215 def testcmd():216 click.echo(current_app.name)
6 unmodified lines
223224225def test_appgroup(runner):226 """Test of with_appcontext."""227228 @click.group(cls=AppGroup)229 def cli():230 pass231
21 unmodified lines
253254255def test_flaskgroup(runner):256 """Test FlaskGroup."""257258 def create_app(info):259 return Flask("flaskgroup")260261 @click.group(cls=FlaskGroup, create_app=create_app)
10 unmodified lines
272273274def test_print_exceptions(runner):275 """Print the stacktrace if the CLI."""276277 def create_app(info):278 raise Exception("oh no")279 return Flask("flaskgroup")280
66 unmodified lines
modified:tests/test_deprecations.py-2 removed
15 unmodified lines
1617class TestRequestDeprecation(object):18 def test_request_json(self, recwarn, app, client):19 """Request.json is deprecated"""20 app.testing = True2021 @app.route('/', methods=['POST'])22 def index():23 assert flask.request.json == {'spam': 42}
4 unmodified lines
28 recwarn.pop(DeprecationWarning)2930 def test_request_module(self, recwarn, app, client):31 """Request.module is deprecated"""33 app.testing = True3233 @app.route('/')34 def index():35 assert flask.request.module is None
4 unmodified lines
modified:tests/test_helpers.py+8 added-20 removed
83 unmodified lines
84 rv = client.post('/json', data='"foo"', content_type='application/x+json')85 assert rv.data == b'foo'8687 def test_json_body_encoding(self, app, client):88 app.testing = True8889 @app.route('/')90 def index():91 return flask.request.get_json()
147 unmodified lines
239 if len(obj) == 1 and '_foo' in obj:240 return X(obj['_foo'])241 return obj242244 app.testing = True243 app.json_encoder = MyEncoder244 app.json_decoder = MyDecoder245246 @app.route('/', methods=['POST'])
35 unmodified lines
282 @bp.route('/bp', methods=['POST'])283 def index():284 return flask.json.dumps(flask.request.get_json()['x'])285288 app.testing = True286 app.register_blueprint(bp)287288 rv = client.post('/bp', data=flask.json.dumps({289 'x': {'_foo': 42}290 }), content_type='application/json')291 assert rv.data == b'"<42>"'292296 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'296300 app.testing = True297 app.request_class = ModifiedRequest298 app.url_map.charset = 'euc-kr'299300 @app.route('/')301 def index():302 return flask.request.args['foo']303308 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')307308 if not has_encoding('euc-kr'):309 test_modified_url_encoding = None310311 def test_json_key_sorting(self, app, client):316 app.testing = True312 app.debug = True313314 assert app.config['JSON_SORT_KEYS'] == True315 d = dict.fromkeys(range(20), 'foo')
216 unmodified lines
532 assert rv.status_code == 200533 rv.close()534535 def test_attachment(self, app, req_ctx):541 app = flask.Flask(__name__)536537 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 lines
612 assert cc.max_age == 10613 rv.close()614615 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()622623 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')626627 with pytest.raises(BadRequest):
8 unmodified lines
636 assert logger1.name == __name__637 app.logger_name = __name__ + '/test_logger_cache'638 assert app.logger is not logger1639648 def test_debug_log(self, capsys):649 app = flask.Flask(__name__)640 def test_debug_log(self, capsys, app, client):641 app.debug = True642643 @app.route('/')644 def index():
4 unmodified lines
649 @app.route('/exc')650 def exc():651 1 // 0652662 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 err660661 with pytest.raises(ZeroDivisionError):671 c.get('/exc')662 client.get('/exc')663664 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 == 10669679 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 lines
677 @app.route('/')678 def index():679 1 // 0680690 rv = app.test_client().get('/')681 rv = client.get('/')682 assert rv.status_code == 500683 assert b'Internal Server Error' in rv.data684685 err = out.getvalue()
112 unmodified lines
798799800class TestStreaming(object):801 def test_streaming_with_context(self, app, client):811 app.testing = True802803 @app.route('/')804 def index():805 def generate():
6 unmodified lines
812 rv = client.get('/?name=World')813 assert rv.data == b'Hello World!'814815 def test_streaming_with_context_as_decorator(self, app, client):826 app.testing = True816817 @app.route('/')818 def index():819 @flask.stream_with_context
7 unmodified lines
827 rv = client.get('/?name=World')828 assert rv.data == b'Hello World!'829830 def test_streaming_with_context_and_custom_close(self, app, client):842 app.testing = True831 called = []832833 class Wrapper(object):834 def __init__(self, gen):
96 unmodified lines
modified:tests/test_regression.py+1 added-3 removed
74 unmodified lines
75 with pytest.raises(NotFound):76 safe_join('/foo', '..')777879def test_aborting():79def test_aborting(app):80 class Foo(Exception):81 whatever = 4282 app = flask.Flask(__name__)83 app.testing = True8283 @app.errorhandler(Foo)84 def handle_foo(e):85 return str(e.whatever)
14 unmodified lines
modified:tests/test_signals.py+8 added-4 removed
16 unmodified lines
17 blinker = None1819import flask202121pytestmark = pytest.mark.skipif(22 blinker is None,23 reason='Signals require the blinker library.'24)2527def test_template_rendered():28 app = flask.Flask(__name__)2627def test_template_rendered(app, client):28 @app.route('/')29 def index():30 return flask.render_template('simple_template.html', whiskey=42)31
3 unmodified lines
35 recorded.append((template, context))3637 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)464748def test_before_render_template():49 app = flask.Flask(__name__)5051 @app.route('/')
16 unmodified lines
68 assert rv.data == b'<h1>43</h1>'69 finally:70 flask.before_render_template.disconnect(record, app)717273def test_request_signals():74 app = flask.Flask(__name__)75 calls = []76
31 unmodified lines
108 finally:109 flask.request_started.disconnect(before_request_signal, app)110 flask.request_finished.disconnect(after_request_signal, app)111112113def test_request_exception_signal():114 app = flask.Flask(__name__)115 recorded = []116
11 unmodified lines
128 assert isinstance(recorded[0], ZeroDivisionError)129 finally:130 flask.got_request_exception.disconnect(record, app)131132133def test_appcontext_signals():134 app = flask.Flask(__name__)135 recorded = []136
18 unmodified lines
155 finally:156 flask.appcontext_pushed.disconnect(record_push, app)157 flask.appcontext_popped.disconnect(record_pop, app)158159160def test_flash_signal():161 app = flask.Flask(__name__)162 app.config['SECRET_KEY'] = 'secret'163
18 unmodified lines
182 assert category == 'notice'183 finally:184 flask.message_flashed.disconnect(record, app)185186187def test_appcontext_tearing_down_signal():188 app = flask.Flask(__name__)189 recorded = []190
16 unmodified lines
modified:tests/test_templating.py+4 added-4 removed
14 unmodified lines
15import logging16from jinja2 import TemplateNotFound171819def test_context_processing(app):19def test_context_processing(app, client):20 @app.context_processor21 def context_processor():22 return {'injected_value': 42}2324 @app.route('/')25 def index():26 return flask.render_template('context_template.html', value=23)2728 rv = app.test_client().get('/')28 rv = client.get('/')29 assert rv.data == b'<p>23|42'303132def test_original_win(app, client):
219 unmodified lines
252 assert app.jinja_env.tests['boolean'] == is_boolean253 assert app.jinja_env.tests['boolean'](False)254255256def test_template_test_with_template(app):256def test_template_test_with_template(app, client):257 @app.template_test()258 def boolean(value):259 return isinstance(value, bool)260261 @app.route('/')262 def index():263 return flask.render_template('template_test.html', value=False)264265 rv = app.test_client().get('/')265 rv = client.get('/')266 assert b'Success!' in rv.data267268269def test_add_template_test_with_template(app, client):
165 unmodified lines
modified:tests/test_testing.py+38 added-46 removed
36 unmodified lines
37 return flask.request.url3839 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/'444546def test_environ_base_default(app, client, app_ctx):47 app.testing = True4847 @app.route('/')48 def index():49 flask.g.user_agent = flask.request.headers["User-Agent"]50 return flask.request.remote_addr
35 unmodified lines
86 @app.route('/getsession')87 def get_session():88 return flask.session.get('data', '<missing>')8992 with client as c:93 rv = c.get('/getsession')90 with client:91 rv = client.get('/getsession')92 assert rv.data == b'<missing>'9396 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'99100 # 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'103106 rv = c.get('/getsession')104 rv = client.get('/getsession')105 assert rv.data == b'foo'106107110def test_session_transactions(app):108def test_session_transactions(app, client):109 app.secret_key = 'testing'110111 @app.route('/')112 def index():113 return text_type(flask.session['foo'])114117 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]125126
16 unmodified lines
143 assert req is not None144 with client.session_transaction():145 assert req is flask.request._get_current_object()146147148def 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)154155157def test_test_client_context_binding():158 app = flask.Flask(__name__)156def test_test_client_context_binding(app, client):157 app.config['LOGGER_HANDLER_POLICY'] = 'never'158 app.testing = False159160 @app.route('/')161 def index():162 flask.g.value = 42
2 unmodified lines
165 @app.route('/other')166 def other():167 1 // 0168170 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 == 200174176 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 = 23
5 unmodified lines
185 else:186 raise AssertionError('some kind of exception expected')187188190def test_reuse_client():191 app = flask.Flask(__name__)192 c = app.test_client()189def test_reuse_client(client):190 c = client191192 with c:195 assert c.get('/').status_code == 404193 assert client.get('/').status_code == 404194195 with c:198 assert c.get('/').status_code == 404196 assert client.get('/').status_code == 404197198201def test_test_client_calls_teardown_handlers():202 app = flask.Flask(__name__)199def test_test_client_calls_teardown_handlers(app, client):200 called = []201202 @app.teardown_request203 def remember(error):204 called.append(error)205209 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]211212 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]220221225def test_full_url_request():226 app = flask.Flask(__name__)227 app.testing = True228222def test_full_url_request(app, client):223 @app.route('/action', methods=['POST'])224 def action():225 return 'x'226233 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.args232233240def test_subdomain():241 app = flask.Flask(__name__)234def test_subdomain(app, client):235 app.config['SERVER_NAME'] = 'example.com'236237 @app.route('/', subdomain='<company_id>')238 def view(company_id):
1 unmodified line
240241 with app.test_request_context():242 url = flask.url_for('view', company_id='xxx')243251 with app.test_client() as c:252 response = c.get(url)244 with client:245 response = client.get(url)246247 assert 200 == response.status_code248 assert b'xxx' == response.data249250258def test_nosubdomain():259 app = flask.Flask(__name__)251def test_nosubdomain(app, client):252 app.config['SERVER_NAME'] = 'example.com'253254 @app.route('/<company_id>')255 def view(company_id):
1 unmodified line
257258 with app.test_request_context():259 url = flask.url_for('view', company_id='xxx')260269 with app.test_client() as c:270 response = c.get(url)261 with client:262 response = client.get(url)263264 assert 200 == response.status_code265 assert b'xxx' == response.data
modified:tests/test_views.py+16 added-22 removed
70 unmodified lines
71 app.add_url_rule('/', view_func=view)72 common_test(app)737475def test_view_inheritance(app):75def test_view_inheritance(app, client):76 class Index(flask.views.MethodView):77 def get(self):78 return 'GET'79
4 unmodified lines
84 def delete(self):85 return 'DELETE'8687 app.add_url_rule('/', view_func=BetterIndex.as_view('index'))88 c = app.test_client()8890 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']919294def test_view_decorators(app):93def 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 lines
105 def dispatch_request(self):106 return 'Awesome'107108 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'112113
36 unmodified lines
150 rv = c.open('/', method='OPTIONS')151 assert 'OPTIONS' in rv.allow152153156def test_implicit_head(app):154def 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 })160161 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'168169173def test_explicit_head(app):170def test_explicit_head(app, client):171 class Index(flask.views.MethodView):172 def get(self):173 return 'GET'174175 def head(self):176 return flask.Response('', headers={'X-Method': 'HEAD'})177178 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'184185
14 unmodified lines
200 # But these tests should still pass. We just log a warning.201 common_test(app)202203208def test_multiple_inheritance(app):204def test_multiple_inheritance(app, client):205 class GetView(flask.views.MethodView):206 def get(self):207 return 'GET'208
5 unmodified lines
214 pass215216 app.add_url_rule('/', view_func=GetDeleteView.as_view('index'))217222 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']221222228def test_remove_method_from_parent(app):223def test_remove_method_from_parent(app, client):224 class GetView(flask.views.MethodView):225 def get(self):226 return 'GET'227
5 unmodified lines
233 methods = ['GET']234235 app.add_url_rule('/', view_func=View.as_view('index'))236242 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']