DRYing up the test suite using pytest fixtures (#2306)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* add fixtures to conftest.py * use fixtures in test_appctx.py * use fixtures in test_blueprints.py * use fixtures in test_depreciations.py * use fixtures in test_regressions.py * use fixtures in test_reqctx.py * use fixtures in test_templating.py * use fixtures in test_user_error_handler.py * use fixtures in test_views.py * use fixtures in test_basics.py * use fixtures in test_helpers.py * use fixtures in test_testing.py * update conftest.py * make docstrings PEP-257 compliant * cleanup * switch dictonary format * use pytest parameterization for test_json_as_unicode
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+997 added−972 removed
- tests:+997 added−972 removed
Provenance
- Commit
5b0b971- Tree
dd72dad- Author
Christian Stade-Schuldt <tafkasorg@yahoo.de>- Committer
David Lord <davidism@gmail.com>- Parent
81c2440
12 files changed+997 added−972 removed
modified:tests/conftest.py+45 added-7 removed
11 unmodified lines12 import sys13 import pkgutil14 import pytest15 import textwrap16+from flask import Flask as _Flask17 18 19+class Flask(_Flask):20+ testing = True21+ secret_key = __name__22+23+ def make_response(self, rv):24+ if rv is None:25+ rv = ''26+ return super(Flask, self).make_response(rv)27+28+29 @pytest.fixture30+def app():31+ app = Flask(__name__)32+ return app33+34+35+@pytest.fixture36+def app_ctx(app):37+ with app.app_context() as ctx:38+ yield ctx39+40+41+@pytest.fixture42+def req_ctx(app):43+ with app.test_request_context() as ctx:44+ yield ctx45+46+47+@pytest.fixture48+def client(app):49+ return app.test_client()50+51+52+@pytest.fixture53 def test_apps(monkeypatch):54 monkeypatch.syspath_prepend(55 os.path.abspath(os.path.join(56 os.path.dirname(__file__), 'test_apps'))39 unmodified lines96 old_get_loader = pkgutil.get_loader97 98 def get_loader(*args, **kwargs):99 return LimitedLoader(old_get_loader(*args, **kwargs))100+101 monkeypatch.setattr(pkgutil, 'get_loader', get_loader)102 103 104 @pytest.fixture105 def modules_tmpdir(tmpdir, monkeypatch):71- '''A tmpdir added to sys.path'''106+ """A tmpdir added to sys.path."""107 rv = tmpdir.mkdir('modules_tmpdir')108 monkeypatch.syspath_prepend(str(rv))109 return rv110 5 unmodified lines116 117 118 @pytest.fixture119 def site_packages(modules_tmpdir, monkeypatch):85- '''Create a fake site-packages'''120+ """Create a fake site-packages."""121 rv = modules_tmpdir \87- .mkdir('lib')\88- .mkdir('python{x[0]}.{x[1]}'.format(x=sys.version_info))\122+ .mkdir('lib') \123+ .mkdir('python{x[0]}.{x[1]}'.format(x=sys.version_info)) \124 .mkdir('site-packages')125 monkeypatch.syspath_prepend(str(rv))126 return rv127 128 129 @pytest.fixture130 def install_egg(modules_tmpdir, monkeypatch):96- '''Generate egg from package name inside base and put the egg into97- sys.path'''131+ """Generate egg from package name inside base and put the egg into132+ sys.path."""133+134 def inner(name, base=modules_tmpdir):135 if not isinstance(name, str):136 raise ValueError(name)137 base.join(name).ensure_dir()15 unmodified lines153 )154 egg_path, = modules_tmpdir.join('dist/').listdir()155 monkeypatch.syspath_prepend(str(egg_path))156 return egg_path157+158 return inner159 160 161 @pytest.fixture162 def purge_module(request):163 def inner(name):164 request.addfinalizer(lambda: sys.modules.pop(name, None))165+166 return inner167 168 169 @pytest.yield_fixture(autouse=True)170 def catch_deprecation_warnings(recwarn):171 yield172 gc.collect()135- assert not recwarn.list173+ assert not recwarn.list, '\n'.join(str(w.message) for w in recwarn.list)modified:tests/test_appctx.py+50 added-44 removed
12 unmodified lines13 14 import flask15 16 17-def test_basic_url_generation():18- app = flask.Flask(__name__)17+def test_basic_url_generation(app):18 app.config['SERVER_NAME'] = 'localhost'19 app.config['PREFERRED_URL_SCHEME'] = 'https'20 21 @app.route('/')3 unmodified lines25 with app.app_context():26 rv = flask.url_for('index')27 assert rv == 'https://localhost/'28 30-def test_url_generation_requires_server_name():31- app = flask.Flask(__name__)29+30+def test_url_generation_requires_server_name(app):31 with app.app_context():32 with pytest.raises(RuntimeError):33 flask.url_for('index')34 35+36 def test_url_generation_without_context_fails():37 with pytest.raises(RuntimeError):38 flask.url_for('index')39 40-def test_request_context_means_app_context():41- app = flask.Flask(__name__)40+41+def test_request_context_means_app_context(app):42 with app.test_request_context():43 assert flask.current_app._get_current_object() == app44 assert flask._app_ctx_stack.top is None45 46-def test_app_context_provides_current_app():47- app = flask.Flask(__name__)46+47+def test_app_context_provides_current_app(app):48 with app.app_context():49 assert flask.current_app._get_current_object() == app50 assert flask._app_ctx_stack.top is None51 52+52-def test_app_tearing_down():53+def test_app_tearing_down(app):54 cleanup_stuff = []54- app = flask.Flask(__name__)55+56 @app.teardown_appcontext57 def cleanup(exception):58 cleanup_stuff.append(exception)59 1 unmodified line61 pass62 63 assert cleanup_stuff == [None]64 65+64-def test_app_tearing_down_with_previous_exception():66+def test_app_tearing_down_with_previous_exception(app):67 cleanup_stuff = []66- app = flask.Flask(__name__)68+69 @app.teardown_appcontext70 def cleanup(exception):71 cleanup_stuff.append(exception)72 6 unmodified lines79 pass80 81 assert cleanup_stuff == [None]82 83+81-def test_app_tearing_down_with_handled_exception():84+def test_app_tearing_down_with_handled_exception(app):85 cleanup_stuff = []83- app = flask.Flask(__name__)86+87 @app.teardown_appcontext88 def cleanup(exception):89 cleanup_stuff.append(exception)90 4 unmodified lines95 pass96 97 assert cleanup_stuff == [None]98 96-def test_app_ctx_globals_methods():97- app = flask.Flask(__name__)98- with app.app_context():99- # get100- assert flask.g.get('foo') is None101- assert flask.g.get('foo', 'bar') == 'bar'102- # __contains__103- assert 'foo' not in flask.g104- flask.g.foo = 'bar'105- assert 'foo' in flask.g106- # setdefault107- flask.g.setdefault('bar', 'the cake is a lie')108- flask.g.setdefault('bar', 'hello world')109- assert flask.g.bar == 'the cake is a lie'110- # pop111- assert flask.g.pop('bar') == 'the cake is a lie'112- with pytest.raises(KeyError):113- flask.g.pop('bar')114- assert flask.g.pop('bar', 'more cake') == 'more cake'115- # __iter__116- assert list(flask.g) == ['foo']99 100+def test_app_ctx_globals_methods(app, app_ctx):101+ # get102+ assert flask.g.get('foo') is None103+ assert flask.g.get('foo', 'bar') == 'bar'104+ # __contains__105+ assert 'foo' not in flask.g106+ flask.g.foo = 'bar'107+ assert 'foo' in flask.g108+ # setdefault109+ flask.g.setdefault('bar', 'the cake is a lie')110+ flask.g.setdefault('bar', 'hello world')111+ assert flask.g.bar == 'the cake is a lie'112+ # pop113+ assert flask.g.pop('bar') == 'the cake is a lie'114+ with pytest.raises(KeyError):115+ flask.g.pop('bar')116+ assert flask.g.pop('bar', 'more cake') == 'more cake'117+ # __iter__118+ assert list(flask.g) == ['foo']119+120+118-def test_custom_app_ctx_globals_class():121+def test_custom_app_ctx_globals_class(app):122 class CustomRequestGlobals(object):123 def __init__(self):124 self.spam = 'eggs'122- app = flask.Flask(__name__)125+126 app.app_ctx_globals_class = CustomRequestGlobals127 with app.app_context():128 assert flask.render_template_string('{{ g.spam }}') == 'eggs'129 130+127-def test_context_refcounts():131+def test_context_refcounts(app, client):132 called = []129- app = flask.Flask(__name__)133+134 @app.teardown_request135 def teardown_req(error=None):136 called.append('request')137+138 @app.teardown_appcontext139 def teardown_app(error=None):140 called.append('app')141+142 @app.route('/')143 def index():144 with flask._app_ctx_stack.top:145 with flask._request_ctx_stack.top:146 pass147 env = flask._request_ctx_stack.top.request.environ148 assert env['werkzeug.request'] is not None149 return u''144- c = app.test_client()145- res = c.get('/')150+151+ res = client.get('/')152 assert res.status_code == 200153 assert res.data == b''154 assert called == ['request', 'app']155 156 151-def test_clean_pop():157+def test_clean_pop(app):158+ app.testing = False159 called = []153- app = flask.Flask(__name__)160 161 @app.teardown_request162 def teardown_req(error=None):163 1 / 07 unmodified lines171 called.append(flask.current_app.name)172 except ZeroDivisionError:173 pass174 169- assert called == ['test_appctx', 'TEARDOWN']175+ assert called == ['conftest', 'TEARDOWN']176 assert not flask.current_appmodified:tests/test_basic.py+207 added-280 removed
23 unmodified lines24 from werkzeug.routing import BuildError25 import werkzeug.serving26 27 28-def test_options_work():29- app = flask.Flask(__name__)30-28+def test_options_work(app, client):29 @app.route('/', methods=['GET', 'POST'])30 def index():31 return 'Hello World'32+34- rv = app.test_client().open('/', method='OPTIONS')33+ rv = client.open('/', method='OPTIONS')34 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']35 assert rv.data == b''36 37 39-def test_options_on_multiple_rules():40- app = flask.Flask(__name__)41-38+def test_options_on_multiple_rules(app, client):39 @app.route('/', methods=['GET', 'POST'])40 def index():41 return 'Hello World'42 43 @app.route('/', methods=['PUT'])44 def index_put():45 return 'Aha!'46+49- rv = app.test_client().open('/', method='OPTIONS')47+ rv = client.open('/', method='OPTIONS')48 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']49 50 51 def test_provide_automatic_options_attr():52 app = flask.Flask(__name__)53 54 def index():55 return 'Hello World!'56+57 index.provide_automatic_options = False58 app.route('/')(index)59 rv = app.test_client().open('/', method='OPTIONS')60 assert rv.status_code == 4051 unmodified line62 app = flask.Flask(__name__)63 64 def index2():65 return 'Hello World!'66+67 index2.provide_automatic_options = True68 app.route('/', methods=['OPTIONS'])(index2)69 rv = app.test_client().open('/', method='OPTIONS')70 assert sorted(rv.allow) == ['OPTIONS']71 72 73-def test_provide_automatic_options_kwarg():74- app = flask.Flask(__name__)75-73+def test_provide_automatic_options_kwarg(app, client):74 def index():75 return flask.request.method76 77 def more():3 unmodified lines81 app.add_url_rule(82 '/more', view_func=more, methods=['GET', 'POST'],83 provide_automatic_options=False84 )85+ assert client.get('/').data == b'GET'86 88- c = app.test_client()89- assert c.get('/').data == b'GET'90-91- rv = c.post('/')87+ rv = client.post('/')88 assert rv.status_code == 40589 assert sorted(rv.allow) == ['GET', 'HEAD']90 91 # Older versions of Werkzeug.test.Client don't have an options method96- if hasattr(c, 'options'):97- rv = c.options('/')92+ if hasattr(client, 'options'):93+ rv = client.options('/')94 else:99- rv = c.open('/', method='OPTIONS')95+ rv = client.open('/', method='OPTIONS')96 97 assert rv.status_code == 40598 103- rv = c.head('/')99+ rv = client.head('/')100 assert rv.status_code == 200101 assert not rv.data # head truncates106- assert c.post('/more').data == b'POST'107- assert c.get('/more').data == b'GET'102+ assert client.post('/more').data == b'POST'103+ assert client.get('/more').data == b'GET'104 109- rv = c.delete('/more')105+ rv = client.delete('/more')106 assert rv.status_code == 405107 assert sorted(rv.allow) == ['GET', 'HEAD', 'POST']108 113- if hasattr(c, 'options'):114- rv = c.options('/more')109+ if hasattr(client, 'options'):110+ rv = client.options('/more')111 else:116- rv = c.open('/more', method='OPTIONS')112+ rv = client.open('/more', method='OPTIONS')113 114 assert rv.status_code == 405115 116 121-def test_request_dispatching():122- app = flask.Flask(__name__)123-117+def test_request_dispatching(app, client):118 @app.route('/')119 def index():120 return flask.request.method121 122 @app.route('/more', methods=['GET', 'POST'])123 def more():124 return flask.request.method125 132- c = app.test_client()133- assert c.get('/').data == b'GET'134- rv = c.post('/')126+ assert client.get('/').data == b'GET'127+ rv = client.post('/')128 assert rv.status_code == 405129 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']137- rv = c.head('/')130+ rv = client.head('/')131 assert rv.status_code == 200132 assert not rv.data # head truncates140- assert c.post('/more').data == b'POST'141- assert c.get('/more').data == b'GET'142- rv = c.delete('/more')133+ assert client.post('/more').data == b'POST'134+ assert client.get('/more').data == b'GET'135+ rv = client.delete('/more')136 assert rv.status_code == 405137 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']138 139 147-def test_disallow_string_for_allowed_methods():148- app = flask.Flask(__name__)140+def test_disallow_string_for_allowed_methods(app):141 with pytest.raises(TypeError):142 @app.route('/', methods='GET POST')143 def index():144 return "Hey"145 146 155-def test_url_mapping():156- app = flask.Flask(__name__)157-147+def test_url_mapping(app, client):148 random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"149 150 def index():151 return flask.request.method3 unmodified lines155 156 def options():157 return random_uuid4158 169-159 app.add_url_rule('/', 'index', index)160 app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])161 162 # Issue 1288: Test that automatic options are not added when non-uppercase 'options' in methods163 app.add_url_rule('/options', 'options', options, methods=['options'])164 176- c = app.test_client()177- assert c.get('/').data == b'GET'178- rv = c.post('/')165+ assert client.get('/').data == b'GET'166+ rv = client.post('/')167 assert rv.status_code == 405168 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']181- rv = c.head('/')169+ rv = client.head('/')170 assert rv.status_code == 200171 assert not rv.data # head truncates184- assert c.post('/more').data == b'POST'185- assert c.get('/more').data == b'GET'186- rv = c.delete('/more')172+ assert client.post('/more').data == b'POST'173+ assert client.get('/more').data == b'GET'174+ rv = client.delete('/more')175 assert rv.status_code == 405176 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']189- rv = c.open('/options', method='OPTIONS')177+ rv = client.open('/options', method='OPTIONS')178 assert rv.status_code == 200179 assert random_uuid4 in rv.data.decode("utf-8")180 181 194-def test_werkzeug_routing():182+def test_werkzeug_routing(app, client):183 from werkzeug.routing import Submount, Rule196- app = flask.Flask(__name__)184 app.url_map.add(Submount('/foo', [185 Rule('/bar', endpoint='bar'),186 Rule('/', endpoint='index')187 ]))2 unmodified lines190 return 'bar'191 192 def index():193 return 'index'194+195 app.view_functions['bar'] = bar196 app.view_functions['index'] = index197 210- c = app.test_client()211- assert c.get('/foo/').data == b'index'212- assert c.get('/foo/bar').data == b'bar'198+ assert client.get('/foo/').data == b'index'199+ assert client.get('/foo/bar').data == b'bar'200 201 215-def test_endpoint_decorator():202+def test_endpoint_decorator(app, client):203 from werkzeug.routing import Submount, Rule217- app = flask.Flask(__name__)204 app.url_map.add(Submount('/foo', [205 Rule('/bar', endpoint='bar'),206 Rule('/', endpoint='index')207 ]))5 unmodified lines213 @app.endpoint('index')214 def index():215 return 'index'216 231- c = app.test_client()232- assert c.get('/foo/').data == b'index'233- assert c.get('/foo/bar').data == b'bar'217+ assert client.get('/foo/').data == b'index'218+ assert client.get('/foo/bar').data == b'bar'219 220 236-def test_session():237- app = flask.Flask(__name__)221+def test_session(app, client):222 app.secret_key = 'testkey'223 224 @app.route('/set', methods=['POST'])225 def set():3 unmodified lines229 @app.route('/get')230 def get():231 return flask.session['value']232 249- c = app.test_client()250- assert c.post('/set', data={'value': '42'}).data == b'value set'251- assert c.get('/get').data == b'42'233+ assert client.post('/set', data={'value': '42'}).data == b'value set'234+ assert client.get('/get').data == b'42'235 236 254-def test_session_using_server_name():255- app = flask.Flask(__name__)237+def test_session_using_server_name(app, client):238 app.config.update(239 SECRET_KEY='foo',240 SERVER_NAME='example.com'241 )1 unmodified line243 @app.route('/')244 def index():245 flask.session['testing'] = 42246 return 'Hello World'247+265- rv = app.test_client().get('/', 'http://example.com/')248+ rv = client.get('/', 'http://example.com/')249 assert 'domain=.example.com' in rv.headers['set-cookie'].lower()250 assert 'httponly' in rv.headers['set-cookie'].lower()251 252 270-def test_session_using_server_name_and_port():271- app = flask.Flask(__name__)253+def test_session_using_server_name_and_port(app, client):254 app.config.update(255 SECRET_KEY='foo',256 SERVER_NAME='example.com:8080'257 )1 unmodified line259 @app.route('/')260 def index():261 flask.session['testing'] = 42262 return 'Hello World'263+281- rv = app.test_client().get('/', 'http://example.com:8080/')264+ rv = client.get('/', 'http://example.com:8080/')265 assert 'domain=.example.com' in rv.headers['set-cookie'].lower()266 assert 'httponly' in rv.headers['set-cookie'].lower()267 268 286-def test_session_using_server_name_port_and_path():287- app = flask.Flask(__name__)269+def test_session_using_server_name_port_and_path(app, client):270 app.config.update(271 SECRET_KEY='foo',272 SERVER_NAME='example.com:8080',273 APPLICATION_ROOT='/foo'2 unmodified lines276 @app.route('/')277 def index():278 flask.session['testing'] = 42279 return 'Hello World'280+298- rv = app.test_client().get('/', 'http://example.com:8080/foo')281+ rv = client.get('/', 'http://example.com:8080/foo')282 assert 'domain=example.com' in rv.headers['set-cookie'].lower()283 assert 'path=/foo' in rv.headers['set-cookie'].lower()284 assert 'httponly' in rv.headers['set-cookie'].lower()285 286 304-def test_session_using_application_root():287+def test_session_using_application_root(app, client):288 class PrefixPathMiddleware(object):306-289 def __init__(self, app, prefix):290 self.app = app291 self.prefix = prefix292 293 def __call__(self, environ, start_response):294 environ['SCRIPT_NAME'] = self.prefix295 return self.app(environ, start_response)296 315- app = flask.Flask(__name__)297 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar')298 app.config.update(299 SECRET_KEY='foo',300 APPLICATION_ROOT='/bar'2 unmodified lines303 @app.route('/')304 def index():305 flask.session['testing'] = 42306 return 'Hello World'307+326- rv = app.test_client().get('/', 'http://example.com:8080/')308+ rv = client.get('/', 'http://example.com:8080/')309 assert 'path=/bar' in rv.headers['set-cookie'].lower()310 311 330-def test_session_using_session_settings():331- app = flask.Flask(__name__)312+def test_session_using_session_settings(app, client):313 app.config.update(314 SECRET_KEY='foo',315 SERVER_NAME='www.example.com:8080',316 APPLICATION_ROOT='/test',6 unmodified lines323 @app.route('/')324 def index():325 flask.session['testing'] = 42326 return 'Hello World'327+346- rv = app.test_client().get('/', 'http://www.example.com:8080/test/')328+ rv = client.get('/', 'http://www.example.com:8080/test/')329 cookie = rv.headers['set-cookie'].lower()330 assert 'domain=.example.com' in cookie331 assert 'path=/' in cookie332 assert 'secure' in cookie333 assert 'httponly' not in cookie334 335 354-def test_session_localhost_warning(recwarn):355- app = flask.Flask(__name__)336+def test_session_localhost_warning(recwarn, app, client):337 app.config.update(338 SECRET_KEY='testing',339 SERVER_NAME='localhost:5000',340 )2 unmodified lines343 def index():344 flask.session['testing'] = 42345 return 'testing'346 366- rv = app.test_client().get('/', 'http://localhost:5000/')347+ rv = client.get('/', 'http://localhost:5000/')348 assert 'domain' not in rv.headers['set-cookie'].lower()349 w = recwarn.pop(UserWarning)350 assert '"localhost" is not a valid cookie domain' in str(w.message)351 352 372-def test_session_ip_warning(recwarn):373- app = flask.Flask(__name__)353+def test_session_ip_warning(recwarn, app, client):354 app.config.update(355 SECRET_KEY='testing',356 SERVER_NAME='127.0.0.1:5000',357 )2 unmodified lines360 def index():361 flask.session['testing'] = 42362 return 'testing'363 384- rv = app.test_client().get('/', 'http://127.0.0.1:5000/')364+ rv = client.get('/', 'http://127.0.0.1:5000/')365 assert 'domain=127.0.0.1' in rv.headers['set-cookie'].lower()366 w = recwarn.pop(UserWarning)367 assert 'cookie domain is an IP' in str(w.message)368 3 unmodified lines372 373 def expect_exception(f, *args, **kwargs):374 e = pytest.raises(RuntimeError, f, *args, **kwargs)375 assert e.value.args and 'session is unavailable' in e.value.args[0]376+377 with app.test_request_context():378 assert flask.session.get('missing_key') is None379 expect_exception(flask.session.__setitem__, 'foo', 42)380 expect_exception(flask.session.pop, 'foo')381 382 402-def test_session_expiration():383+def test_session_expiration(app, client):384 permanent = True404- app = flask.Flask(__name__)385 app.secret_key = 'testkey'386 387 @app.route('/')388 def index():4 unmodified lines393 @app.route('/test')394 def test():395 return text_type(flask.session.permanent)396 417- client = app.test_client()397 rv = client.get('/')398 assert 'set-cookie' in rv.headers399 match = re.search(r'(?i)\bexpires=([^;]+)', rv.headers['set-cookie'])400 expires = parse_date(match.group())5 unmodified lines406 rv = client.get('/test')407 assert rv.data == b'True'408 409 permanent = False431- rv = app.test_client().get('/')410+ rv = client.get('/')411 assert 'set-cookie' in rv.headers412 match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])413 assert match is None414 415 437-def test_session_stored_last():438- app = flask.Flask(__name__)416+def test_session_stored_last(app, client):417 app.secret_key = 'development-key'440- app.testing = True418 419 @app.after_request420 def modify_session(response):421 flask.session['foo'] = 422 unmodified lines424 @app.route('/')425 def dump_session_contents():426 return repr(flask.session.get('foo'))427 451- c = app.test_client()452- assert c.get('/').data == b'None'453- assert c.get('/').data == b'42'428+ assert client.get('/').data == b'None'429+ assert client.get('/').data == b'42'430 431 456-def test_session_special_types():457- app = flask.Flask(__name__)432+def test_session_special_types(app, client):433 app.secret_key = 'development-key'459- app.testing = True434 now = datetime.utcnow().replace(microsecond=0)435 the_uuid = uuid.uuid4()436 437 @app.after_request8 unmodified lines446 @app.route('/')447 def dump_session_contents():448 return pickle.dumps(dict(flask.session))449 476- c = app.test_client()477- c.get('/')478- rv = pickle.loads(c.get('/').data)450+ client.get('/')451+ rv = pickle.loads(client.get('/').data)452 assert rv['m'] == flask.Markup('Hello!')453 assert type(rv['m']) == flask.Markup454 assert rv['dt'] == now455 assert rv['u'] == the_uuid1 unmodified line457 assert type(rv['b']) == bytes458 assert rv['t'] == (1, 2, 3)459 460 488-def test_session_cookie_setting():489- app = flask.Flask(__name__)490- app.testing = True461+def test_session_cookie_setting(app):462 app.secret_key = 'dev key'463 is_permanent = True464 465 @app.route('/bump')33 unmodified lines499 app.config['SESSION_REFRESH_EACH_REQUEST'] = False500 run_test(expect_header=False)501 502 532-def test_session_vary_cookie():533- app = flask.Flask(__name__)503+def test_session_vary_cookie(app, client):504 app.secret_key = 'testkey'505 506 @app.route('/set')507 def set_session():15 unmodified lines523 @app.route('/no-vary-header')524 def no_vary_header():525 return ''526 557- c = app.test_client()558-527 def expect(path, header=True):560- rv = c.get(path)528+ rv = client.get(path)529 530 if header:531 assert rv.headers['Vary'] == 'Cookie'532 else:5 unmodified lines538 expect('/setdefault')539 expect('/no-vary-header', False)540 541 574-def test_flashes():575- app = flask.Flask(__name__)542+def test_flashes(app, req_ctx):543 app.secret_key = 'testkey'544 578- with app.test_request_context():579- assert not flask.session.modified580- flask.flash('Zap')581- flask.session.modified = False582- flask.flash('Zip')583- assert flask.session.modified584- assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']545+ assert not flask.session.modified546+ flask.flash('Zap')547+ flask.session.modified = False548+ flask.flash('Zip')549+ assert flask.session.modified550+ assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']551 552 587-def test_extended_flashing():553+def test_extended_flashing(app):554 # Be sure app.testing=True below, else tests can fail silently.555 #556 # Specifically, if app.testing is not set to True, the AssertionErrors557 # in the view functions will cause a 500 response to the test client558 # instead of propagating exceptions.559 594- app = flask.Flask(__name__)560 app.secret_key = 'testkey'596- app.testing = True561 562 @app.route('/')563 def index():564 flask.flash(u'Hello World')49 unmodified lines614 return ''615 616 # Create new test client on each test to clean flashed messages.617 654- c = app.test_client()655- c.get('/')656- c.get('/test/')618+ client = app.test_client()619+ client.get('/')620+ client.get('/test_with_categories/')621 658- c = app.test_client()659- c.get('/')660- c.get('/test_with_categories/')622+ client = app.test_client()623+ client.get('/')624+ client.get('/test_filter/')625 662- c = app.test_client()663- c.get('/')664- c.get('/test_filter/')626+ client = app.test_client()627+ client.get('/')628+ client.get('/test_filters/')629 666- c = app.test_client()667- c.get('/')668- c.get('/test_filters/')630+ client = app.test_client()631+ client.get('/')632+ client.get('/test_filters_without_returning_categories/')633 670- c = app.test_client()671- c.get('/')672- c.get('/test_filters_without_returning_categories/')634 674-675-def test_request_processing():635+def test_request_processing(app, client):676- app = flask.Flask(__name__)636 evts = []637 638 @app.before_request639 def before_request():9 unmodified lines649 def index():650 assert 'before' in evts651 assert 'after' not in evts652 return 'request'653+654 assert 'after' not in evts695- rv = app.test_client().get('/').data655+ rv = client.get('/').data656 assert 'after' in evts657 assert rv == b'request|after'658 659 700-def test_request_preprocessing_early_return():701- app = flask.Flask(__name__)660+def test_request_preprocessing_early_return(app, client):661 evts = []662 663 @app.before_request664 def before_request1():13 unmodified lines678 def index():679 evts.append('index')680 return "damnit"681 723- rv = app.test_client().get('/').data.strip()682+ rv = client.get('/').data.strip()683 assert rv == b'hello'684 assert evts == [1, 2]685 686 728-def test_after_request_processing():729- app = flask.Flask(__name__)730- app.testing = True731-687+def test_after_request_processing(app, client):688 @app.route('/')689 def index():690 @flask.after_this_request691 def foo(response):692 response.headers['X-Foo'] = 'a header'693 return response694+695 return 'Test'739- c = app.test_client()740- resp = c.get('/')696+697+ resp = client.get('/')698 assert resp.status_code == 200699 assert resp.headers['X-Foo'] == 'a header'700 701 745-def test_teardown_request_handler():702+def test_teardown_request_handler(app, client):703 called = []747- app = flask.Flask(__name__)704 705 @app.teardown_request706 def teardown_request(exc):707 called.append(True)1 unmodified line709 710 @app.route('/')711 def root():712 return "Response"757- rv = app.test_client().get('/')713+714+ rv = client.get('/')715 assert rv.status_code == 200716 assert b'Response' in rv.data717 assert len(called) == 1718 719 763-def test_teardown_request_handler_debug_mode():720+def test_teardown_request_handler_debug_mode(app, client):721 called = []765- app = flask.Flask(__name__)766- app.testing = True722 723 @app.teardown_request724 def teardown_request(exc):725 called.append(True)1 unmodified line727 728 @app.route('/')729 def root():730 return "Response"776- rv = app.test_client().get('/')731+732+ rv = client.get('/')733 assert rv.status_code == 200734 assert b'Response' in rv.data735 assert len(called) == 1736 737 782-def test_teardown_request_handler_error():738+def test_teardown_request_handler_error(app, client):739 called = []784- app = flask.Flask(__name__)740 app.config['LOGGER_HANDLER_POLICY'] = 'never'741+ app.testing = False742 743 @app.teardown_request744 def teardown_request1(exc):745 assert type(exc) == ZeroDivisionError20 unmodified lines766 767 @app.route('/')768 def fails():769 1 // 0814- rv = app.test_client().get('/')770+771+ rv = client.get('/')772 assert rv.status_code == 500773 assert b'Internal Server Error' in rv.data774 assert len(called) == 2775 776 820-def test_before_after_request_order():777+def test_before_after_request_order(app, client):778 called = []822- app = flask.Flask(__name__)779 780 @app.before_request781 def before1():782 called.append(1)22 unmodified lines805 806 @app.route('/')807 def index():808 return '42'853- rv = app.test_client().get('/')809+810+ rv = client.get('/')811 assert rv.data == b'42'812 assert called == [1, 2, 3, 4, 5, 6]813 814 858-def test_error_handling():859- app = flask.Flask(__name__)815+def test_error_handling(app, client):816 app.config['LOGGER_HANDLER_POLICY'] = 'never'817+ app.testing = False818 819 @app.errorhandler(404)820 def not_found(e):821 return 'not found', 40416 unmodified lines838 839 @app.route('/forbidden')840 def error2():841 flask.abort(403)885- c = app.test_client()886- rv = c.get('/')842+843+ rv = client.get('/')844 assert rv.status_code == 404845 assert rv.data == b'not found'889- rv = c.get('/error')846+ rv = client.get('/error')847 assert rv.status_code == 500848 assert b'internal server error' == rv.data892- rv = c.get('/forbidden')849+ rv = client.get('/forbidden')850 assert rv.status_code == 403851 assert b'forbidden' == rv.data852 853 897-def test_error_handling_processing():898- app = flask.Flask(__name__)854+def test_error_handling_processing(app, client):855 app.config['LOGGER_HANDLER_POLICY'] = 'never'856+ app.testing = False857 858 @app.errorhandler(500)859 def internal_server_error(e):860 return 'internal server error', 5006 unmodified lines867 def after_request(resp):868 resp.mimetype = 'text/x-special'869 return resp870 914- with app.test_client() as c:915- resp = c.get('/')916- assert resp.mimetype == 'text/x-special'917- assert resp.data == b'internal server error'871+ resp = client.get('/')872+ assert resp.mimetype == 'text/x-special'873+ assert resp.data == b'internal server error'874 875 920-def test_baseexception_error_handling():921- app = flask.Flask(__name__)876+def test_baseexception_error_handling(app, client):877 app.config['LOGGER_HANDLER_POLICY'] = 'never'878+ app.testing = False879 880 @app.route('/')881 def broken_func():882 raise KeyboardInterrupt()883 928- with app.test_client() as c:929- with pytest.raises(KeyboardInterrupt):930- c.get('/')884+ with pytest.raises(KeyboardInterrupt):885+ client.get('/')886 887 ctx = flask._request_ctx_stack.top888 assert ctx.preserved889 assert type(ctx._preserved_exc) is KeyboardInterrupt890 891 937-def test_before_request_and_routing_errors():938- app = flask.Flask(__name__)939-892+def test_before_request_and_routing_errors(app, client):893 @app.before_request894 def attach_something():895 flask.g.something = 'value'896 897 @app.errorhandler(404)898 def return_something(error):899 return flask.g.something, 404947- rv = app.test_client().get('/')900+901+ rv = client.get('/')902 assert rv.status_code == 404903 assert rv.data == b'value'904 905 952-def test_user_error_handling():906+def test_user_error_handling(app, client):907 class MyException(Exception):908 pass909 956- app = flask.Flask(__name__)957-910 @app.errorhandler(MyException)911 def handle_my_exception(e):912 assert isinstance(e, MyException)913 return '42'1 unmodified line915 @app.route('/')916 def index():917 raise MyException()918 967- c = app.test_client()968- assert c.get('/').data == b'42'919+ assert client.get('/').data == b'42'920 921 971-def test_http_error_subclass_handling():922+def test_http_error_subclass_handling(app, client):923 class ForbiddenSubclass(Forbidden):924 pass925 975- app = flask.Flask(__name__)976-926 @app.errorhandler(ForbiddenSubclass)927 def handle_forbidden_subclass(e):928 assert isinstance(e, ForbiddenSubclass)929 return 'banana'15 unmodified lines945 @app.route('/3')946 def index3():947 raise Forbidden()948 1000- c = app.test_client()1001- assert c.get('/1').data == b'banana'1002- assert c.get('/2').data == b'apple'1003- assert c.get('/3').data == b'apple'949+ assert client.get('/1').data == b'banana'950+ assert client.get('/2').data == b'apple'951+ assert client.get('/3').data == b'apple'952 953 1006-def test_trapping_of_bad_request_key_errors():1007- app = flask.Flask(__name__)1008- app.testing = True1009-954+def test_trapping_of_bad_request_key_errors(app):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 == 400961 962 app.config['TRAP_BAD_REQUEST_ERRORS'] = True2 unmodified lines965 c.get("/fail")966 assert e.errisinstance(BadRequest)967 968 1023-def test_trapping_of_all_http_exceptions():1024- app = flask.Flask(__name__)1025- app.testing = True969+def test_trapping_of_all_http_exceptions(app, client):970 app.config['TRAP_HTTP_EXCEPTIONS'] = True971 972 @app.route('/fail')973 def fail():974 flask.abort(404)975 1032- c = app.test_client()976 with pytest.raises(NotFound):1034- c.get('/fail')977+ client.get('/fail')978 979 1037-def test_enctype_debug_helper():980+def test_enctype_debug_helper(app, client):981 from flask.debughelpers import DebugFilesKeyError1039- app = flask.Flask(__name__)982 app.debug = True983 984 @app.route('/fail', methods=['POST'])985 def index():1 unmodified line987 988 # with statement is important because we leave an exception on the989 # stack otherwise and we want to ensure that this is not the case990 # to not negatively affect other tests.1049- with app.test_client() as c:991+ with client as c:992 with pytest.raises(DebugFilesKeyError) as e:993 c.post('/fail', data={'foo': 'index.txt'})994 assert 'no file contents were transmitted' in str(e.value)995 assert 'This was submitted: "index.txt"' in str(e.value)175 unmodified lines1171 "msg": {1172 "submsg": "W00t"1173 },1174 "msg2": "foobar"1233- }1175+ }1176 1177 rv = flask.make_response(1178 flask.jsonify(uncompressed_msg), 200)1179 assert rv.data == compressed_msg2 unmodified lines1182 def test_jsonify_prettyprint():1183 app = flask.Flask(__name__)1184 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1185 with app.test_request_context():1244- compressed_msg = {"msg":{"submsg":"W00t"},"msg2":"foobar"}1245- pretty_response =\1186+ compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1187+ pretty_response = \1188 b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'1189 1190 rv = flask.make_response(1191 flask.jsonify(compressed_msg), 200)25 unmodified lines1217 1218 @app.route('/hello/<name>', methods=['POST'])1219 def hello():1220 pass1221+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) == \1282- 'http://localhost/hello/test%20x'1225+ 'http://localhost/hello/test%20x'1226 1227 1228 def test_build_error_handler():1229 app = flask.Flask(__name__)17 unmodified lines1247 # Test a custom handler.1248 def handler(error, endpoint, values):1249 # Just a test.1250 return '/test_handler/'1251+1252 app.url_build_error_handlers.append(handler)1253 with app.test_request_context():1254 assert flask.url_for('spam') == '/test_handler/'1255 3 unmodified lines1259 1260 # Test a custom handler which reraises the BuildError1261 def handler_raises_build_error(error, endpoint, values):1262 raise error1263+1264 app.url_build_error_handlers.append(handler_raises_build_error)1265 1266 with app.test_request_context():1267 pytest.raises(BuildError, flask.url_for, 'not.existing')19 unmodified lines1287 def test_custom_converters():1288 from werkzeug.routing import BaseConverter1289 1290 class ListConverter(BaseConverter):1346-1291 def to_python(self, value):1292 return value.split(',')1293 1294 def to_url(self, value):1295 base_to_url = super(ListConverter, self).to_url1296 return ','.join(base_to_url(x) for x in value)1297+1298 app = flask.Flask(__name__)1299 app.url_map.converters['list'] = ListConverter1300 1301 @app.route('/<list:args>')1302 def index(args):1303 return '|'.join(args)1304+1305 c = app.test_client()1306 assert c.get('/1,2,3').data == b'1|2|3'1307 1308 4 unmodified lines1313 assert rv.status_code == 2001314 assert rv.data.strip() == b'<h1>Hello World!</h1>'1315 with app.test_request_context():1316 assert flask.url_for('static', filename='index.html') == \1371- '/static/index.html'1317+ '/static/index.html'1318 rv.close()1319 1320 1321 def test_static_path_deprecated(recwarn):26 unmodified lines1348 rv = c.get('http://example.com/static/index.html')1349 assert rv.status_code == 2001350 rv.close()1351 with app.test_request_context():1406- rv = flask.url_for('static', filename='index.html', _external=True)1407- assert rv == 'http://example.com/static/index.html'1352+ rv = flask.url_for('static', filename='index.html', _external=True)1353+ assert rv == 'http://example.com/static/index.html'1354 # Providing static_host without host_matching=True should error.1355 with pytest.raises(Exception):1356 flask.Flask(__name__, static_host='example.com')1357 # Providing host_matching=True with static_folder but without static_host should error.72 unmodified lines1430 1431 @app.route('/')1432 def index():1433 1 // 01434+1435 c = app.test_client()1436 if config_key is not None:1437 app.config[config_key] = True1438 with pytest.raises(Exception):57 unmodified lines1496 1497 @app.url_defaults1498 def add_language_code(endpoint, values):1499 if flask.g.lang_code is not None and \1553- app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1500+ app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1501 values.setdefault('lang_code', flask.g.lang_code)1502 1503 @app.url_value_preprocessor1504 def pull_lang_code(endpoint, values):63 unmodified lines1568 1569 @app.route('/')1570 def index():1571 return 'Awesome'1572+1573 assert not app.got_first_request1574 assert app.test_client().get('/').data == b'Awesome'1575 with pytest.raises(AssertionError) as e:1576 @app.route('/foo')5 unmodified lines1582 1583 @app.route('/foo')1584 def working():1585 return 'Meh'1586+1587 assert app.test_client().get('/foo').data == b'Meh'1588 assert app.got_first_request1589 1590 3 unmodified lines1594 1595 @app.before_first_request1596 def foo():1597 got.append(42)1598+1599 c = app.test_client()1600 c.get('/')1601 assert got == [42]1602 c.get('/')29 unmodified lines1632 1633 @app.route('/foo/', methods=['GET', 'POST'])1634 def foo():1635 return 'success'1636+1637 with app.test_client() as c:1638 with pytest.raises(AssertionError) as e:1639 c.post('/foo', data={})1640 assert 'http://localhost/foo/' in str(e)56 unmodified lines1697 assert flask._request_ctx_stack.top is None1698 assert flask._app_ctx_stack.top is None1699 1700 1750-def test_preserve_remembers_exception():1751- app = flask.Flask(__name__)1701+def test_preserve_remembers_exception(app, client):1702 app.debug = True1703 errors = []1704 1705 @app.route('/fail')7 unmodified lines1713 @app.teardown_request1714 def teardown_handler(exc):1715 errors.append(exc)1716 1767- c = app.test_client()1768-1717 # After this failure we did not yet call the teardown handler1718 with pytest.raises(ZeroDivisionError):1771- c.get('/fail')1719+ client.get('/fail')1720 assert errors == []1721 1722 # But this request triggers it, and it's an error1775- c.get('/success')1723+ client.get('/success')1724 assert len(errors) == 21725 assert isinstance(errors[0], ZeroDivisionError)1726 1727 # At this point another request does nothing.1780- c.get('/success')1728+ client.get('/success')1729 assert len(errors) == 31730 assert errors[1] is None1731 1732 1785-def test_get_method_on_g():1786- app = flask.Flask(__name__)1787- app.testing = True1733+def test_get_method_on_g(app_ctx):1734+ assert flask.g.get('x') is None1735+ assert flask.g.get('x', 11) == 111736+ flask.g.x = 421737+ assert flask.g.get('x') == 421738+ assert flask.g.x == 421739 1789- with app.app_context():1790- assert flask.g.get('x') is None1791- assert flask.g.get('x', 11) == 111792- flask.g.x = 421793- assert flask.g.get('x') == 421794- assert flask.g.x == 421740 1741+def test_g_iteration_protocol(app_ctx):1742+ flask.g.foo = 231743+ flask.g.bar = 421744+ assert 'foo' in flask.g1745+ assert 'foos' not in flask.g1746+ assert sorted(flask.g) == ['bar', 'foo']1747 1797-def test_g_iteration_protocol():1798- app = flask.Flask(__name__)1799- app.testing = True1748 1801- with app.app_context():1802- flask.g.foo = 231803- flask.g.bar = 421804- assert 'foo' in flask.g1805- assert 'foos' not in flask.g1806- assert sorted(flask.g) == ['bar', 'foo']1749+def test_subdomain_basic_support(app, client):1750+ app.config['SERVER_NAME'] = 'localhost.localdomain'1751 1808-1809-def test_subdomain_basic_support():1810- app = flask.Flask(__name__)1811- app.config['SERVER_NAME'] = 'localhost'1812-1752 @app.route('/')1753 def normal_index():1754 return 'normal index'1755 1756 @app.route('/', subdomain='test')1757 def test_index():1758 return 'test index'1759 1821- c = app.test_client()1822- rv = c.get('/', 'http://localhost/')1760+ rv = client.get('/', 'http://localhost.localdomain/')1761 assert rv.data == b'normal index'1762 1825- rv = c.get('/', 'http://test.localhost/')1763+ rv = client.get('/', 'http://test.localhost.localdomain/')1764 assert rv.data == b'test index'1765 1766 1829-def test_subdomain_matching():1830- app = flask.Flask(__name__)1831- app.config['SERVER_NAME'] = 'localhost'1767+def test_subdomain_matching(app, client):1768+ app.config['SERVER_NAME'] = 'localhost.localdomain'1769 1770 @app.route('/', subdomain='<user>')1771 def index(user):1772 return 'index for %s' % user1773 1837- c = app.test_client()1838- rv = c.get('/', 'http://mitsuhiko.localhost/')1774+ rv = client.get('/', 'http://mitsuhiko.localhost.localdomain/')1775 assert rv.data == b'index for mitsuhiko'1776 1777 1842-def test_subdomain_matching_with_ports():1843- app = flask.Flask(__name__)1844- app.config['SERVER_NAME'] = 'localhost:3000'1778+def test_subdomain_matching_with_ports(app, client):1779+ app.config['SERVER_NAME'] = 'localhost.localdomain:3000'1780 1781 @app.route('/', subdomain='<user>')1782 def index(user):1783 return 'index for %s' % user1784 1850- c = app.test_client()1851- rv = c.get('/', 'http://mitsuhiko.localhost:3000/')1785+ rv = client.get('/', 'http://mitsuhiko.localhost.localdomain:3000/')1786 assert rv.data == b'index for mitsuhiko'1787 1788 1855-def test_multi_route_rules():1856- app = flask.Flask(__name__)1857-1789+def test_multi_route_rules(app, client):1790 @app.route('/')1791 @app.route('/<test>/')1792 def index(test='a'):1793 return test1794 1863- rv = app.test_client().open('/')1795+ rv = client.open('/')1796 assert rv.data == b'a'1865- rv = app.test_client().open('/b/')1797+ rv = client.open('/b/')1798 assert rv.data == b'b'1799 1800 1869-def test_multi_route_class_views():1801+def test_multi_route_class_views(app, client):1802 class View(object):1871-1803 def __init__(self, app):1804 app.add_url_rule('/', 'index', self.index)1805 app.add_url_rule('/<test>/', 'index', self.index)1806 1807 def index(self, test='a'):1808 return test1809 1879- app = flask.Flask(__name__)1810 _ = View(app)1881- rv = app.test_client().open('/')1811+ rv = client.open('/')1812 assert rv.data == b'a'1883- rv = app.test_client().open('/b/')1813+ rv = client.open('/b/')1814 assert rv.data == b'b'1815 1816 1887-def test_run_defaults(monkeypatch):1817+def test_run_defaults(monkeypatch, app):1818 rv = {}1819 1820 # Mocks werkzeug.serving.run_simple method1821 def run_simple_mock(*args, **kwargs):1822 rv['result'] = 'running...'1823 1894- app = flask.Flask(__name__)1824 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1825 app.run()1826 assert rv['result'] == 'running...'1827 1828 1900-def test_run_server_port(monkeypatch):1829+def test_run_server_port(monkeypatch, app):1830 rv = {}1831 1832 # Mocks werkzeug.serving.run_simple method1833 def run_simple_mock(hostname, port, application, *args, **kwargs):1834 rv['result'] = 'running on %s:%s ...' % (hostname, port)1835 1907- app = flask.Flask(__name__)1836 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1837 hostname, port = 'localhost', 80001838 app.run(hostname, port, debug=True)1839 assert rv['result'] == 'running on %s:%s ...' % (hostname, port)1840 1841 1842 @pytest.mark.parametrize('host,port,expect_host,expect_port', (1915- (None, None, 'pocoo.org', 8080),1916- ('localhost', None, 'localhost', 8080),1917- (None, 80, 'pocoo.org', 80),1918- ('localhost', 80, 'localhost', 80),1843+ (None, None, 'pocoo.org', 8080),1844+ ('localhost', None, 'localhost', 8080),1845+ (None, 80, 'pocoo.org', 80),1846+ ('localhost', 80, 'localhost', 80),1847 ))1920-def test_run_from_config(monkeypatch, host, port, expect_host, expect_port):1848+def test_run_from_config(monkeypatch, host, port, expect_host, expect_port, app):1849 def run_simple_mock(hostname, port, *args, **kwargs):1850 assert hostname == expect_host1851 assert port == expect_port1852 1853 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1926- app = flask.Flask(__name__)1854 app.config['SERVER_NAME'] = 'pocoo.org:8080'1855 app.run(host, port)modified:tests/test_blueprints.py+162 added-118 removed
16 unmodified lines17 from werkzeug.http import parse_cache_control_header18 from jinja2 import TemplateNotFound19 20 21-def test_blueprint_specific_error_handling():21+def test_blueprint_specific_error_handling(app, client):22 frontend = flask.Blueprint('frontend', __name__)23 backend = flask.Blueprint('backend', __name__)24 sideend = flask.Blueprint('sideend', __name__)25 16 unmodified lines42 @sideend.route('/what-is-a-sideend')43 def sideend_no():44 flask.abort(403)45 46- app = flask.Flask(__name__)46 app.register_blueprint(frontend)47 app.register_blueprint(backend)48 app.register_blueprint(sideend)49 50 @app.errorhandler(403)51 def app_forbidden(e):52 return 'application itself says no', 40353 55- c = app.test_client()54+ assert client.get('/frontend-no').data == b'frontend says no'55+ assert client.get('/backend-no').data == b'backend says no'56+ assert client.get('/what-is-a-sideend').data == b'application itself says no'57 57- assert c.get('/frontend-no').data == b'frontend says no'58- assert c.get('/backend-no').data == b'backend says no'59- assert c.get('/what-is-a-sideend').data == b'application itself says no'58 61-def test_blueprint_specific_user_error_handling():59+def test_blueprint_specific_user_error_handling(app, client):60 class MyDecoratorException(Exception):61 pass62+63 class MyFunctionException(Exception):64 pass65 66 blue = flask.Blueprint('blue', __name__)5 unmodified lines72 73 def my_function_exception_handler(e):74 assert isinstance(e, MyFunctionException)75 return 'bam'76+77 blue.register_error_handler(MyFunctionException, my_function_exception_handler)78 79 @blue.route('/decorator')80 def blue_deco_test():81 raise MyDecoratorException()82+83 @blue.route('/function')84 def blue_func_test():85 raise MyFunctionException()86 86- app = flask.Flask(__name__)87 app.register_blueprint(blue)88 89- c = app.test_client()89+ assert client.get('/decorator').data == b'boom'90+ assert client.get('/function').data == b'bam'91 91- assert c.get('/decorator').data == b'boom'92- assert c.get('/function').data == b'bam'92 94-def test_blueprint_app_error_handling():93+def test_blueprint_app_error_handling(app, client):94 errors = flask.Blueprint('errors', __name__)95 96 @errors.app_errorhandler(403)97 def forbidden_handler(e):98 return 'you shall not pass', 40399 101- app = flask.Flask(__name__)102-100 @app.route('/forbidden')101 def app_forbidden():102 flask.abort(403)103 5 unmodified lines109 110 app.register_blueprint(errors)111 app.register_blueprint(forbidden_bp)112 116- c = app.test_client()113+ assert client.get('/forbidden').data == b'you shall not pass'114+ assert client.get('/nope').data == b'you shall not pass'115 118- assert c.get('/forbidden').data == b'you shall not pass'119- assert c.get('/nope').data == b'you shall not pass'116 121-def test_blueprint_url_definitions():117+def test_blueprint_url_definitions(app, client):118 bp = flask.Blueprint('test', __name__)119 120 @bp.route('/foo', defaults={'baz': 42})121 def foo(bar, baz):2 unmodified lines124 @bp.route('/bar')125 def bar(bar):126 return text_type(bar)127 132- app = flask.Flask(__name__)128 app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23})129 app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19})130 136- c = app.test_client()137- assert c.get('/1/foo').data == b'23/42'138- assert c.get('/2/foo').data == b'19/42'139- assert c.get('/1/bar').data == b'23'140- assert c.get('/2/bar').data == b'19'131+ assert client.get('/1/foo').data == b'23/42'132+ assert client.get('/2/foo').data == b'19/42'133+ assert client.get('/1/bar').data == b'23'134+ assert client.get('/2/bar').data == b'19'135 136+142-def test_blueprint_url_processors():137+def test_blueprint_url_processors(app, client):138 bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')139 140 @bp.url_defaults141 def add_language_code(endpoint, values):10 unmodified lines152 @bp.route('/about')153 def about():154 return flask.url_for('.index')155 161- app = flask.Flask(__name__)156 app.register_blueprint(bp)157 164- c = app.test_client()158+ assert client.get('/de/').data == b'/de/about'159+ assert client.get('/de/about').data == b'/de/'160 166- assert c.get('/de/').data == b'/de/about'167- assert c.get('/de/about').data == b'/de/'161 162 def test_templates_and_static(test_apps):163 from blueprintapp import app171- c = app.test_client()164+ client = app.test_client()165 173- rv = c.get('/')166+ rv = client.get('/')167 assert rv.data == b'Hello from the Frontend'175- rv = c.get('/admin/')168+ rv = client.get('/admin/')169 assert rv.data == b'Hello from the Admin'177- rv = c.get('/admin/index2')170+ rv = client.get('/admin/index2')171 assert rv.data == b'Hello from the Admin'179- rv = c.get('/admin/static/test.txt')172+ rv = client.get('/admin/static/test.txt')173 assert rv.data.strip() == b'Admin File'174 rv.close()182- rv = c.get('/admin/static/css/test.css')175+ rv = client.get('/admin/static/css/test.css')176 assert rv.data.strip() == b'/* nested file */'177 rv.close()178 179 # try/finally, in case other tests use this app for Blueprint tests.2 unmodified lines182 expected_max_age = 3600183 if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == expected_max_age:184 expected_max_age = 7200185 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age193- rv = c.get('/admin/static/css/test.css')186+ rv = client.get('/admin/static/css/test.css')187 cc = parse_cache_control_header(rv.headers['Cache-Control'])188 assert cc.max_age == expected_max_age189 rv.close()190 finally:9 unmodified lines200 201 with flask.Flask(__name__).test_request_context():202 assert flask.render_template('nested/nested.txt') == 'I\'m nested'203 204+205 def test_default_static_cache_timeout():206 app = flask.Flask(__name__)207+208 class MyBlueprint(flask.Blueprint):209 def get_send_file_max_age(self, filename):210 return 100211 14 unmodified lines226 rv.close()227 finally:228 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default229 230+231 def test_templates_list(test_apps):232 from blueprintapp import app233 templates = sorted(app.jinja_env.list_templates())234 assert templates == ['admin/index.html', 'frontend/index.html']235 236+240-def test_dotted_names():237+def test_dotted_names(app, client):238 frontend = flask.Blueprint('myapp.frontend', __name__)239 backend = flask.Blueprint('myapp.backend', __name__)240 241 @frontend.route('/fe')7 unmodified lines249 @backend.route('/be')250 def backend_index():251 return flask.url_for('myapp.frontend.frontend_index')252 256- app = flask.Flask(__name__)253 app.register_blueprint(frontend)254 app.register_blueprint(backend)255 260- c = app.test_client()261- assert c.get('/fe').data.strip() == b'/be'262- assert c.get('/fe2').data.strip() == b'/fe'263- assert c.get('/be').data.strip() == b'/fe'256+ assert client.get('/fe').data.strip() == b'/be'257+ assert client.get('/fe2').data.strip() == b'/fe'258+ assert client.get('/be').data.strip() == b'/fe'259 265-def test_dotted_names_from_app():266- app = flask.Flask(__name__)267- app.testing = True260+261+def test_dotted_names_from_app(app, client):262 test = flask.Blueprint('test', __name__)263 264 @app.route('/')265 def app_index():4 unmodified lines270 return flask.url_for('app_index')271 272 app.register_blueprint(test)273 280- with app.test_client() as c:281- rv = c.get('/')282- assert rv.data == b'/test/'274+ rv = client.get('/')275+ assert rv.data == b'/test/'276 277+284-def test_empty_url_defaults():278+def test_empty_url_defaults(app, client):279 bp = flask.Blueprint('bp', __name__)280 281 @bp.route('/', defaults={'page': 1})282 @bp.route('/page/<int:page>')283 def something(page):284 return str(page)285 292- app = flask.Flask(__name__)286 app.register_blueprint(bp)287 295- c = app.test_client()296- assert c.get('/').data == b'1'297- assert c.get('/page/2').data == b'2'288+ assert client.get('/').data == b'1'289+ assert client.get('/page/2').data == b'2'290 299-def test_route_decorator_custom_endpoint():291 292+def test_route_decorator_custom_endpoint(app, client):293 bp = flask.Blueprint('bp', __name__)294 295 @bp.route('/foo')296 def foo():10 unmodified lines307 @bp.route('/bar/foo')308 def bar_foo():309 return flask.request.endpoint310 319- app = flask.Flask(__name__)311 app.register_blueprint(bp, url_prefix='/py')312 313 @app.route('/')314 def index():315 return flask.request.endpoint316 326- c = app.test_client()327- assert c.get('/').data == b'index'328- assert c.get('/py/foo').data == b'bp.foo'329- assert c.get('/py/bar').data == b'bp.bar'330- assert c.get('/py/bar/123').data == b'bp.123'331- assert c.get('/py/bar/foo').data == b'bp.bar_foo'317+ assert client.get('/').data == b'index'318+ assert client.get('/py/foo').data == b'bp.foo'319+ assert client.get('/py/bar').data == b'bp.bar'320+ assert client.get('/py/bar/123').data == b'bp.123'321+ assert client.get('/py/bar/foo').data == b'bp.bar_foo'322 323+333-def test_route_decorator_custom_endpoint_with_dots():324+def test_route_decorator_custom_endpoint_with_dots(app, client):325 bp = flask.Blueprint('bp', __name__)326 327 @bp.route('/foo')328 def foo():32 unmodified lines361 bp.route('/bar/123', endpoint='bar.123'),362 lambda: None363 )364 374- app = flask.Flask(__name__)365 app.register_blueprint(bp, url_prefix='/py')366 377- c = app.test_client()378- assert c.get('/py/foo').data == b'bp.foo'367+ assert client.get('/py/foo').data == b'bp.foo'368 # The rule's didn't actually made it through380- rv = c.get('/py/bar')369+ rv = client.get('/py/bar')370 assert rv.status_code == 404382- rv = c.get('/py/bar/123')371+ rv = client.get('/py/bar/123')372 assert rv.status_code == 404373 374 386-def test_endpoint_decorator():375+def test_endpoint_decorator(app, client):376 from werkzeug.routing import Rule388- app = flask.Flask(__name__)377 app.url_map.add(Rule('/foo', endpoint='bar'))378 379 bp = flask.Blueprint('bp', __name__)380 2 unmodified lines383 return flask.request.endpoint384 385 app.register_blueprint(bp, url_prefix='/bp_prefix')386 399- c = app.test_client()400- assert c.get('/foo').data == b'bar'401- assert c.get('/bp_prefix/bar').status_code == 404387+ assert client.get('/foo').data == b'bar'388+ assert client.get('/bp_prefix/bar').status_code == 404389 390 404-def test_template_filter():391+def test_template_filter(app):392 bp = flask.Blueprint('bp', __name__)393+394 @bp.app_template_filter()395 def my_reverse(s):396 return s[::-1]409- app = flask.Flask(__name__)397+398 app.register_blueprint(bp, url_prefix='/py')399 assert 'my_reverse' in app.jinja_env.filters.keys()400 assert app.jinja_env.filters['my_reverse'] == my_reverse401 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'402 403+415-def test_add_template_filter():404+def test_add_template_filter(app):405 bp = flask.Blueprint('bp', __name__)406+407 def my_reverse(s):408 return s[::-1]409+410 bp.add_app_template_filter(my_reverse)420- app = flask.Flask(__name__)411 app.register_blueprint(bp, url_prefix='/py')412 assert 'my_reverse' in app.jinja_env.filters.keys()413 assert app.jinja_env.filters['my_reverse'] == my_reverse414 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'415 416+426-def test_template_filter_with_name():417+def test_template_filter_with_name(app):418 bp = flask.Blueprint('bp', __name__)419+420 @bp.app_template_filter('strrev')421 def my_reverse(s):422 return s[::-1]431- app = flask.Flask(__name__)423+424 app.register_blueprint(bp, url_prefix='/py')425 assert 'strrev' in app.jinja_env.filters.keys()426 assert app.jinja_env.filters['strrev'] == my_reverse427 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'428 429+437-def test_add_template_filter_with_name():430+def test_add_template_filter_with_name(app):431 bp = flask.Blueprint('bp', __name__)432+433 def my_reverse(s):434 return s[::-1]435+436 bp.add_app_template_filter(my_reverse, 'strrev')442- app = flask.Flask(__name__)437 app.register_blueprint(bp, url_prefix='/py')438 assert 'strrev' in app.jinja_env.filters.keys()439 assert app.jinja_env.filters['strrev'] == my_reverse440 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'441 442+448-def test_template_filter_with_template():443+def test_template_filter_with_template(app, client):444 bp = flask.Blueprint('bp', __name__)445+446 @bp.app_template_filter()447 def super_reverse(s):448 return s[::-1]453- app = flask.Flask(__name__)449+450 app.register_blueprint(bp, url_prefix='/py')451+452 @app.route('/')453 def index():454 return flask.render_template('template_filter.html', value='abcd')458- rv = app.test_client().get('/')455+456+ rv = client.get('/')457 assert rv.data == b'dcba'458 461-def test_template_filter_after_route_with_template():462- app = flask.Flask(__name__)459+460+def test_template_filter_after_route_with_template(app, client):461 @app.route('/')462 def index():463 return flask.render_template('template_filter.html', value='abcd')464+465 bp = flask.Blueprint('bp', __name__)466+467 @bp.app_template_filter()468 def super_reverse(s):469 return s[::-1]470+471 app.register_blueprint(bp, url_prefix='/py')471- rv = app.test_client().get('/')472+ rv = client.get('/')473 assert rv.data == b'dcba'474 475+474-def test_add_template_filter_with_template():476+def test_add_template_filter_with_template(app, client):477 bp = flask.Blueprint('bp', __name__)478+479 def super_reverse(s):480 return s[::-1]481+482 bp.add_app_template_filter(super_reverse)479- app = flask.Flask(__name__)483 app.register_blueprint(bp, url_prefix='/py')484+485 @app.route('/')486 def index():487 return flask.render_template('template_filter.html', value='abcd')484- rv = app.test_client().get('/')488+489+ rv = client.get('/')490 assert rv.data == b'dcba'491 492+487-def test_template_filter_with_name_and_template():493+def test_template_filter_with_name_and_template(app, client):494 bp = flask.Blueprint('bp', __name__)495+496 @bp.app_template_filter('super_reverse')497 def my_reverse(s):498 return s[::-1]492- app = flask.Flask(__name__)499+500 app.register_blueprint(bp, url_prefix='/py')501+502 @app.route('/')503 def index():504 return flask.render_template('template_filter.html', value='abcd')497- rv = app.test_client().get('/')505+506+ rv = client.get('/')507 assert rv.data == b'dcba'508 509+500-def test_add_template_filter_with_name_and_template():510+def test_add_template_filter_with_name_and_template(app, client):511 bp = flask.Blueprint('bp', __name__)512+513 def my_reverse(s):514 return s[::-1]515+516 bp.add_app_template_filter(my_reverse, 'super_reverse')505- app = flask.Flask(__name__)517 app.register_blueprint(bp, url_prefix='/py')518+519 @app.route('/')520 def index():521 return flask.render_template('template_filter.html', value='abcd')510- rv = app.test_client().get('/')522+523+ rv = client.get('/')524 assert rv.data == b'dcba'525 526+513-def test_template_test():527+def test_template_test(app):528 bp = flask.Blueprint('bp', __name__)529+530 @bp.app_template_test()531 def is_boolean(value):532 return isinstance(value, bool)518- app = flask.Flask(__name__)533+534 app.register_blueprint(bp, url_prefix='/py')535 assert 'is_boolean' in app.jinja_env.tests.keys()536 assert app.jinja_env.tests['is_boolean'] == is_boolean537 assert app.jinja_env.tests['is_boolean'](False)538 539+524-def test_add_template_test():540+def test_add_template_test(app):541 bp = flask.Blueprint('bp', __name__)542+543 def is_boolean(value):544 return isinstance(value, bool)545+546 bp.add_app_template_test(is_boolean)529- app = flask.Flask(__name__)547 app.register_blueprint(bp, url_prefix='/py')548 assert 'is_boolean' in app.jinja_env.tests.keys()549 assert app.jinja_env.tests['is_boolean'] == is_boolean550 assert app.jinja_env.tests['is_boolean'](False)551 552+535-def test_template_test_with_name():553+def test_template_test_with_name(app):554 bp = flask.Blueprint('bp', __name__)555+556 @bp.app_template_test('boolean')557 def is_boolean(value):558 return isinstance(value, bool)540- app = flask.Flask(__name__)559+560 app.register_blueprint(bp, url_prefix='/py')561 assert 'boolean' in app.jinja_env.tests.keys()562 assert app.jinja_env.tests['boolean'] == is_boolean563 assert app.jinja_env.tests['boolean'](False)564 565+546-def test_add_template_test_with_name():566+def test_add_template_test_with_name(app):567 bp = flask.Blueprint('bp', __name__)568+569 def is_boolean(value):570 return isinstance(value, bool)571+572 bp.add_app_template_test(is_boolean, 'boolean')551- app = flask.Flask(__name__)573 app.register_blueprint(bp, url_prefix='/py')574 assert 'boolean' in app.jinja_env.tests.keys()575 assert app.jinja_env.tests['boolean'] == is_boolean576 assert app.jinja_env.tests['boolean'](False)577 578+557-def test_template_test_with_template():579+def test_template_test_with_template(app, client):580 bp = flask.Blueprint('bp', __name__)581+582 @bp.app_template_test()583 def boolean(value):584 return isinstance(value, bool)562- app = flask.Flask(__name__)585+586 app.register_blueprint(bp, url_prefix='/py')587+588 @app.route('/')589 def index():590 return flask.render_template('template_test.html', value=False)567- rv = app.test_client().get('/')591+592+ rv = client.get('/')593 assert b'Success!' in rv.data594 570-def test_template_test_after_route_with_template():571- app = flask.Flask(__name__)595+596+def test_template_test_after_route_with_template(app, client):597 @app.route('/')598 def index():599 return flask.render_template('template_test.html', value=False)600+601 bp = flask.Blueprint('bp', __name__)602+603 @bp.app_template_test()604 def boolean(value):605 return isinstance(value, bool)606+607 app.register_blueprint(bp, url_prefix='/py')580- rv = app.test_client().get('/')608+ rv = client.get('/')609 assert b'Success!' in rv.data610 611+583-def test_add_template_test_with_template():612+def test_add_template_test_with_template(app, client):613 bp = flask.Blueprint('bp', __name__)614+615 def boolean(value):616 return isinstance(value, bool)617+618 bp.add_app_template_test(boolean)588- app = flask.Flask(__name__)619 app.register_blueprint(bp, url_prefix='/py')620+621 @app.route('/')622 def index():623 return flask.render_template('template_test.html', value=False)593- rv = app.test_client().get('/')624+625+ rv = client.get('/')626 assert b'Success!' in rv.data627 628+596-def test_template_test_with_name_and_template():629+def test_template_test_with_name_and_template(app, client):630 bp = flask.Blueprint('bp', __name__)631+632 @bp.app_template_test('boolean')633 def is_boolean(value):634 return isinstance(value, bool)601- app = flask.Flask(__name__)635+636 app.register_blueprint(bp, url_prefix='/py')637+638 @app.route('/')639 def index():640 return flask.render_template('template_test.html', value=False)606- rv = app.test_client().get('/')641+642+ rv = client.get('/')643 assert b'Success!' in rv.data644 645+609-def test_add_template_test_with_name_and_template():646+def test_add_template_test_with_name_and_template(app, client):647 bp = flask.Blueprint('bp', __name__)648+649 def is_boolean(value):650 return isinstance(value, bool)651+652 bp.add_app_template_test(is_boolean, 'boolean')614- app = flask.Flask(__name__)653 app.register_blueprint(bp, url_prefix='/py')654+655 @app.route('/')656 def index():657 return flask.render_template('template_test.html', value=False)619- rv = app.test_client().get('/')658+659+ rv = client.get('/')660 assert b'Success!' in rv.data661 662+663 def test_context_processing():664 app = flask.Flask(__name__)665 answer_bp = flask.Blueprint('answer_bp', __name__)666 34 unmodified lines701 702 assert b'42' in answer_page_bytes703 assert b'43' in answer_page_bytes704 705+706 def test_template_global():707 app = flask.Flask(__name__)708 bp = flask.Blueprint('bp', __name__)709+710 @bp.app_template_global()711 def get_answer():712 return 42713+714 # Make sure the function is not in the jinja_env already715 assert 'get_answer' not in app.jinja_env.globals.keys()716 app.register_blueprint(bp)717 76 unmodified linesmodified:tests/test_deprecations.py+4 added-9 removed
13 unmodified lines14 import flask15 16 17 class TestRequestDeprecation(object):18-19- def test_request_json(self, recwarn):18+ def test_request_json(self, recwarn, app, client):19 """Request.json is deprecated"""21- app = flask.Flask(__name__)20 app.testing = True21 22 @app.route('/', methods=['POST'])23 def index():24 assert flask.request.json == {'spam': 42}25 print(flask.request.json)26 return 'OK'27 30- c = app.test_client()31- c.post('/', data='{"spam": 42}', content_type='application/json')28+ client.post('/', data='{"spam": 42}', content_type='application/json')29 recwarn.pop(DeprecationWarning)30 34- def test_request_module(self, recwarn):31+ def test_request_module(self, recwarn, app, client):32 """Request.module is deprecated"""36- app = flask.Flask(__name__)33 app.testing = True34 35 @app.route('/')36 def index():37 assert flask.request.module is None38 return 'OK'39 44- c = app.test_client()45- c.get('/')40+ client.get('/')41 recwarn.pop(DeprecationWarning)modified:tests/test_helpers.py+291 added-322 removed
33 unmodified lines34 return False35 36 37 class TestJSON(object):38-39- def test_ignore_cached_json(self):38+ def test_ignore_cached_json(self, app):40- app = flask.Flask(__name__)39 with app.test_request_context('/', method='POST', data='malformed',40 content_type='application/json'):41 assert flask.request.get_json(silent=True, cache=True) is None42 with pytest.raises(BadRequest):43 flask.request.get_json(silent=False, cache=False)44 47- def test_post_empty_json_adds_exception_to_response_content_in_debug(self):48- app = flask.Flask(__name__)45+ def test_post_empty_json_adds_exception_to_response_content_in_debug(self, app, client):46 app.config['DEBUG'] = True47+48 @app.route('/json', methods=['POST'])49 def post_json():50 flask.request.get_json()51 return None54- c = app.test_client()55- rv = c.post('/json', data=None, content_type='application/json')52+53+ rv = client.post('/json', data=None, content_type='application/json')54 assert rv.status_code == 40055 assert b'Failed to decode JSON object' in rv.data56 59- def test_post_empty_json_wont_add_exception_to_response_if_no_debug(self):60- app = flask.Flask(__name__)57+ def test_post_empty_json_wont_add_exception_to_response_if_no_debug(self, app, client):58 app.config['DEBUG'] = False59+60 @app.route('/json', methods=['POST'])61 def post_json():62 flask.request.get_json()63 return None66- c = app.test_client()67- rv = c.post('/json', data=None, content_type='application/json')64+65+ rv = client.post('/json', data=None, content_type='application/json')66 assert rv.status_code == 40067 assert b'Failed to decode JSON object' not in rv.data68 71- def test_json_bad_requests(self):72- app = flask.Flask(__name__)69+ def test_json_bad_requests(self, app, client):70+71 @app.route('/json', methods=['POST'])72 def return_json():73 return flask.jsonify(foo=text_type(flask.request.get_json()))76- c = app.test_client()77- rv = c.post('/json', data='malformed', content_type='application/json')74+75+ rv = client.post('/json', data='malformed', content_type='application/json')76 assert rv.status_code == 40077 80- def test_json_custom_mimetypes(self):81- app = flask.Flask(__name__)78+ def test_json_custom_mimetypes(self, app, client):79+80 @app.route('/json', methods=['POST'])81 def return_json():82 return flask.request.get_json()85- c = app.test_client()86- rv = c.post('/json', data='"foo"', content_type='application/x+json')83+84+ rv = client.post('/json', data='"foo"', content_type='application/x+json')85 assert rv.data == b'foo'86 89- def test_json_body_encoding(self):90- app = flask.Flask(__name__)87+ def test_json_body_encoding(self, app, client):88 app.testing = True89+90 @app.route('/')91 def index():92 return flask.request.get_json()93 96- c = app.test_client()97- resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),98- content_type='application/json; charset=iso-8859-15')94+ resp = client.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),95+ content_type='application/json; charset=iso-8859-15')96 assert resp.data == u'Hällo Wörld'.encode('utf-8')97 101- def test_json_as_unicode(self):102- app = flask.Flask(__name__)98+ @pytest.mark.parametrize('test_value,expected', [(True, '"\\u2603"'), (False, u'"\u2603"')])99+ def test_json_as_unicode(self, test_value, expected, app, app_ctx):100 104- app.config['JSON_AS_ASCII'] = True105- with app.app_context():106- rv = flask.json.dumps(u'\N{SNOWMAN}')107- assert rv == '"\\u2603"'101+ app.config['JSON_AS_ASCII'] = test_value102+ rv = flask.json.dumps(u'\N{SNOWMAN}')103+ assert rv == expected104 109- app.config['JSON_AS_ASCII'] = False110- with app.app_context():111- rv = flask.json.dumps(u'\N{SNOWMAN}')112- assert rv == u'"\u2603"'113-114- def test_json_dump_to_file(self):105+ def test_json_dump_to_file(self, app, app_ctx):115- app = flask.Flask(__name__)106 test_data = {'name': 'Flask'}107 out = StringIO()108 119- with app.app_context():120- flask.json.dump(test_data, out)121- out.seek(0)122- rv = flask.json.load(out)123- assert rv == test_data109+ flask.json.dump(test_data, out)110+ out.seek(0)111+ rv = flask.json.load(out)112+ assert rv == test_data113 114 @pytest.mark.parametrize('test_value', [0, -1, 1, 23, 3.14, 's', "longer string", True, False, None])126- def test_jsonify_basic_types(self, test_value):115+ def test_jsonify_basic_types(self, test_value, app, client):116 """Test jsonify with basic types."""128- app = flask.Flask(__name__)129- c = app.test_client()117 118 url = '/jsonify_basic_types'119 app.add_url_rule(url, url, lambda x=test_value: flask.jsonify(x))133- rv = c.get(url)120+ rv = client.get(url)121 assert rv.mimetype == 'application/json'122 assert flask.json.loads(rv.data) == test_value123 137- def test_jsonify_dicts(self):124+ def test_jsonify_dicts(self, app, client):125 """Test jsonify with dicts and kwargs unpacking."""139- d = dict(140- a=0, b=23, c=3.14, d='t', e='Hi', f=True, g=False,141- h=['test list', 10, False],142- i={'test':'dict'}143- )144- app = flask.Flask(__name__)126+ d = {'a': 0, 'b': 23, 'c': 3.14, 'd': 't',127+ 'e': 'Hi', 'f': True, 'g': False,128+ 'h': ['test list', 10, False],129+ 'i': {'test': 'dict'}}130+131 @app.route('/kw')132 def return_kwargs():133 return flask.jsonify(**d)134+135 @app.route('/dict')136 def return_dict():137 return flask.jsonify(d)151- c = app.test_client()138+139 for url in '/kw', '/dict':153- rv = c.get(url)140+ rv = client.get(url)141 assert rv.mimetype == 'application/json'142 assert flask.json.loads(rv.data) == d143 157- def test_jsonify_arrays(self):144+ def test_jsonify_arrays(self, app, client):145 """Test jsonify of lists and args unpacking."""146 l = [147 0, 42, 3.14, 't', 'hello', True, False,148 ['test list', 2, False],162- {'test':'dict'}149+ {'test': 'dict'}150 ]164- app = flask.Flask(__name__)151+152 @app.route('/args_unpack')153 def return_args_unpack():154 return flask.jsonify(*l)155+156 @app.route('/array')157 def return_array():158 return flask.jsonify(l)171- c = app.test_client()159+160 for url in '/args_unpack', '/array':173- rv = c.get(url)161+ rv = client.get(url)162 assert rv.mimetype == 'application/json'163 assert flask.json.loads(rv.data) == l164 177- def test_jsonify_date_types(self):165+ def test_jsonify_date_types(self, app, client):166 """Test jsonify with datetime.date and datetime.datetime types."""167 test_dates = (168 datetime.datetime(1973, 3, 11, 6, 30, 45),169 datetime.date(1975, 1, 5)170 )183- app = flask.Flask(__name__)184- c = app.test_client()171 172 for i, d in enumerate(test_dates):173 url = '/datetest{0}'.format(i)174 app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val))189- rv = c.get(url)175+ rv = client.get(url)176 assert rv.mimetype == 'application/json'177 assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple())178 193- def test_jsonify_uuid_types(self):179+ def test_jsonify_uuid_types(self, app, client):180 """Test jsonify with uuid.UUID types"""181 182 test_uuid = uuid.UUID(bytes=b'\xDE\xAD\xBE\xEF' * 4)197- app = flask.Flask(__name__)183 url = '/uuid_test'184 app.add_url_rule(url, url, lambda: flask.jsonify(x=test_uuid))185 201- c = app.test_client()202- rv = c.get(url)186+ rv = client.get(url)187 188 rv_x = flask.json.loads(rv.data)['x']189 assert rv_x == str(test_uuid)190 rv_uuid = uuid.UUID(rv_x)191 assert rv_uuid == test_uuid192 209- def test_json_attr(self):210- app = flask.Flask(__name__)193+ def test_json_attr(self, app, client):194+195 @app.route('/add', methods=['POST'])196 def add():197 json = flask.request.get_json()198 return text_type(json['a'] + json['b'])215- c = app.test_client()216- rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),217- content_type='application/json')199+200+ rv = client.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),201+ content_type='application/json')202 assert rv.data == b'3'203 220- def test_template_escaping(self):221- app = flask.Flask(__name__)204+ def test_template_escaping(self, app, req_ctx):205 render = flask.render_template_string223- with app.test_request_context():224- rv = flask.json.htmlsafe_dumps('</script>')225- assert rv == u'"\\u003c/script\\u003e"'226- assert type(rv) == text_type227- rv = render('{{ "</script>"|tojson }}')228- assert rv == '"\\u003c/script\\u003e"'229- rv = render('{{ "<\0/script>"|tojson }}')230- assert rv == '"\\u003c\\u0000/script\\u003e"'231- rv = render('{{ "<!--<script>"|tojson }}')232- assert rv == '"\\u003c!--\\u003cscript\\u003e"'233- rv = render('{{ "&"|tojson }}')234- assert rv == '"\\u0026"'235- rv = render('{{ "\'"|tojson }}')236- assert rv == '"\\u0027"'237- rv = render("<a ng-data='{{ data|tojson }}'></a>",238- data={'x': ["foo", "bar", "baz'"]})239- assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'206+ rv = flask.json.htmlsafe_dumps('</script>')207+ assert rv == u'"\\u003c/script\\u003e"'208+ assert type(rv) == text_type209+ rv = render('{{ "</script>"|tojson }}')210+ assert rv == '"\\u003c/script\\u003e"'211+ rv = render('{{ "<\0/script>"|tojson }}')212+ assert rv == '"\\u003c\\u0000/script\\u003e"'213+ rv = render('{{ "<!--<script>"|tojson }}')214+ assert rv == '"\\u003c!--\\u003cscript\\u003e"'215+ rv = render('{{ "&"|tojson }}')216+ assert rv == '"\\u0026"'217+ rv = render('{{ "\'"|tojson }}')218+ assert rv == '"\\u0027"'219+ rv = render("<a ng-data='{{ data|tojson }}'></a>",220+ data={'x': ["foo", "bar", "baz'"]})221+ assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'222 241- def test_json_customization(self):223+ def test_json_customization(self, app, client):224 class X(object):225 def __init__(self, val):226 self.val = val227+228 class MyEncoder(flask.json.JSONEncoder):229 def default(self, o):230 if isinstance(o, X):231 return '<%d>' % o.val232 return flask.json.JSONEncoder.default(self, o)233+234 class MyDecoder(flask.json.JSONDecoder):235 def __init__(self, *args, **kwargs):236 kwargs.setdefault('object_hook', self.object_hook)237 flask.json.JSONDecoder.__init__(self, *args, **kwargs)238+239 def object_hook(self, obj):240 if len(obj) == 1 and '_foo' in obj:241 return X(obj['_foo'])242 return obj258- app = flask.Flask(__name__)243+244 app.testing = True245 app.json_encoder = MyEncoder246 app.json_decoder = MyDecoder247+248 @app.route('/', methods=['POST'])249 def index():250 return flask.json.dumps(flask.request.get_json()['x'])265- c = app.test_client()266- rv = c.post('/', data=flask.json.dumps({251+252+ rv = client.post('/', data=flask.json.dumps({253 'x': {'_foo': 42}254 }), content_type='application/json')255 assert rv.data == b'"<42>"'256 271- def test_blueprint_json_customization(self):257+ def test_blueprint_json_customization(self, app, client):258 class X(object):259 def __init__(self, val):260 self.val = val261 22 unmodified lines284 @bp.route('/bp', methods=['POST'])285 def index():286 return flask.json.dumps(flask.request.get_json()['x'])287 302- app = flask.Flask(__name__)288 app.testing = True289 app.register_blueprint(bp)290 306- c = app.test_client()307- rv = c.post('/bp', data=flask.json.dumps({291+ rv = client.post('/bp', data=flask.json.dumps({292 'x': {'_foo': 42}293 }), content_type='application/json')294 assert rv.data == b'"<42>"'295 312- def test_modified_url_encoding(self):296+ def test_modified_url_encoding(self, app):297 class ModifiedRequest(flask.Request):298 url_charset = 'euc-kr'315- app = flask.Flask(__name__)299+300 app.testing = True301 app.request_class = ModifiedRequest302 app.url_map.charset = 'euc-kr'303 7 unmodified lines311 312 if not has_encoding('euc-kr'):313 test_modified_url_encoding = None314 331- def test_json_key_sorting(self):332- app = flask.Flask(__name__)315+ def test_json_key_sorting(self, app, client):316 app.testing = True317 app.debug = True318 319 assert app.config['JSON_SORT_KEYS'] == True2 unmodified lines322 @app.route('/')323 def index():324 return flask.jsonify(values=d)325 343- c = app.test_client()344- rv = c.get('/')326+ rv = client.get('/')327 lines = [x.strip() for x in rv.data.strip().decode('utf-8').splitlines()]328 sorted_by_str = [329 '{',330 '"values": {',51 unmodified lines382 assert lines == sorted_by_int383 except AssertionError:384 assert lines == sorted_by_str385 386+387 class TestSendfile(object):388+ def test_send_file_regular(self, app, req_ctx):389+ rv = flask.send_file('static/index.html')390+ assert rv.direct_passthrough391+ assert rv.mimetype == 'text/html'392+ with app.open_resource('static/index.html') as f:393+ rv.direct_passthrough = False394+ assert rv.data == f.read()395+ rv.close()396 406- def test_send_file_regular(self):407- app = flask.Flask(__name__)408- with app.test_request_context():409- rv = flask.send_file('static/index.html')410- assert rv.direct_passthrough411- assert rv.mimetype == 'text/html'412- with app.open_resource('static/index.html') as f:413- rv.direct_passthrough = False414- assert rv.data == f.read()415- rv.close()416-417- def test_send_file_xsendfile(self, catch_deprecation_warnings):397+ def test_send_file_xsendfile(self, app, req_ctx, catch_deprecation_warnings):418- app = flask.Flask(__name__)398 app.use_x_sendfile = True420- with app.test_request_context():421- rv = flask.send_file('static/index.html')422- assert rv.direct_passthrough423- assert 'x-sendfile' in rv.headers424- assert rv.headers['x-sendfile'] == \425- os.path.join(app.root_path, 'static/index.html')426- assert rv.mimetype == 'text/html'427- rv.close()399+ rv = flask.send_file('static/index.html')400+ assert rv.direct_passthrough401+ assert 'x-sendfile' in rv.headers402+ assert rv.headers['x-sendfile'] == \403+ os.path.join(app.root_path, 'static/index.html')404+ assert rv.mimetype == 'text/html'405+ rv.close()406 429- def test_send_file_last_modified(self):430- app = flask.Flask(__name__)407+ def test_send_file_last_modified(self, app, client):408 last_modified = datetime.datetime(1999, 1, 1)409 410 @app.route('/')411 def index():412 return flask.send_file(StringIO("party like it's"),413 last_modified=last_modified,414 mimetype='text/plain')415 439- c = app.test_client()440- rv = c.get('/')416+ rv = client.get('/')417 assert rv.last_modified == last_modified418 443- def test_send_file_object_without_mimetype(self):444- app = flask.Flask(__name__)419+ def test_send_file_object_without_mimetype(self, app, req_ctx):420+ with pytest.raises(ValueError) as excinfo:421+ flask.send_file(StringIO("LOL"))422+ assert 'Unable to infer MIME-type' in str(excinfo)423+ assert 'no filename is available' in str(excinfo)424 446- with app.test_request_context():447- with pytest.raises(ValueError) as excinfo:448- flask.send_file(StringIO("LOL"))425+ flask.send_file(StringIO("LOL"), attachment_filename='filename')449- assert 'Unable to infer MIME-type' in str(excinfo)450- assert 'no filename is available' in str(excinfo)426 452- with app.test_request_context():453- flask.send_file(StringIO("LOL"), attachment_filename='filename')427+ def test_send_file_object(self, app, req_ctx):428+ with open(os.path.join(app.root_path, 'static/index.html'), mode='rb') as f:429+ rv = flask.send_file(f, mimetype='text/html')430+ rv.direct_passthrough = False431+ with app.open_resource('static/index.html') as f:432+ assert rv.data == f.read()433+ assert rv.mimetype == 'text/html'434+ rv.close()435 455- def test_send_file_object(self):456- app = flask.Flask(__name__)457-458- with app.test_request_context():459- with open(os.path.join(app.root_path, 'static/index.html'), mode='rb') as f:460- rv = flask.send_file(f, mimetype='text/html')461- rv.direct_passthrough = False462- with app.open_resource('static/index.html') as f:463- assert rv.data == f.read()464- assert rv.mimetype == 'text/html'465- rv.close()466-436 app.use_x_sendfile = True437 469- with app.test_request_context():470- with open(os.path.join(app.root_path, 'static/index.html')) as f:471- rv = flask.send_file(f, mimetype='text/html')472- assert rv.mimetype == 'text/html'473- assert 'x-sendfile' not in rv.headers474- rv.close()438+ with open(os.path.join(app.root_path, 'static/index.html')) as f:439+ rv = flask.send_file(f, mimetype='text/html')440+ assert rv.mimetype == 'text/html'441+ assert 'x-sendfile' not in rv.headers442+ rv.close()443 444 app.use_x_sendfile = False477- with app.test_request_context():478- f = StringIO('Test')479- rv = flask.send_file(f, mimetype='application/octet-stream')480- rv.direct_passthrough = False481- assert rv.data == b'Test'482- assert rv.mimetype == 'application/octet-stream'483- rv.close()445+ f = StringIO('Test')446+ rv = flask.send_file(f, mimetype='application/octet-stream')447+ rv.direct_passthrough = False448+ assert rv.data == b'Test'449+ assert rv.mimetype == 'application/octet-stream'450+ rv.close()451 485- class PyStringIO(object):486- def __init__(self, *args, **kwargs):487- self._io = StringIO(*args, **kwargs)488- def __getattr__(self, name):489- return getattr(self._io, name)490- f = PyStringIO('Test')491- f.name = 'test.txt'492- rv = flask.send_file(f, attachment_filename=f.name)493- rv.direct_passthrough = False494- assert rv.data == b'Test'495- assert rv.mimetype == 'text/plain'496- rv.close()452+ class PyStringIO(object):453+ def __init__(self, *args, **kwargs):454+ self._io = StringIO(*args, **kwargs)455 498- f = StringIO('Test')499- rv = flask.send_file(f, mimetype='text/plain')500- rv.direct_passthrough = False501- assert rv.data == b'Test'502- assert rv.mimetype == 'text/plain'503- rv.close()456+ def __getattr__(self, name):457+ return getattr(self._io, name)458 459+ f = PyStringIO('Test')460+ f.name = 'test.txt'461+ rv = flask.send_file(f, attachment_filename=f.name)462+ rv.direct_passthrough = False463+ assert rv.data == b'Test'464+ assert rv.mimetype == 'text/plain'465+ rv.close()466+467+ f = StringIO('Test')468+ rv = flask.send_file(f, mimetype='text/plain')469+ rv.direct_passthrough = False470+ assert rv.data == b'Test'471+ assert rv.mimetype == 'text/plain'472+ rv.close()473+474 app.use_x_sendfile = True475 507- with app.test_request_context():508- f = StringIO('Test')509- rv = flask.send_file(f, mimetype='text/html')510- assert 'x-sendfile' not in rv.headers511- rv.close()476+ f = StringIO('Test')477+ rv = flask.send_file(f, mimetype='text/html')478+ assert 'x-sendfile' not in rv.headers479+ rv.close()480 481 @pytest.mark.skipif(482 not callable(getattr(Range, 'to_content_range_header', None)),483 reason="not implement within werkzeug"484 )517- def test_send_file_range_request(self):518- app = flask.Flask(__name__)519-485+ def test_send_file_range_request(self, app, client):486 @app.route('/')487 def index():488 return flask.send_file('static/index.html', conditional=True)489 524- c = app.test_client()525-526- rv = c.get('/', headers={'Range': 'bytes=4-15'})490+ rv = client.get('/', headers={'Range': 'bytes=4-15'})491 assert rv.status_code == 206492 with app.open_resource('static/index.html') as f:493 assert rv.data == f.read()[4:16]494 rv.close()495 532- rv = c.get('/', headers={'Range': 'bytes=4-'})496+ rv = client.get('/', headers={'Range': 'bytes=4-'})497 assert rv.status_code == 206498 with app.open_resource('static/index.html') as f:499 assert rv.data == f.read()[4:]500 rv.close()501 538- rv = c.get('/', headers={'Range': 'bytes=4-1000'})502+ rv = client.get('/', headers={'Range': 'bytes=4-1000'})503 assert rv.status_code == 206504 with app.open_resource('static/index.html') as f:505 assert rv.data == f.read()[4:]506 rv.close()507 544- rv = c.get('/', headers={'Range': 'bytes=-10'})508+ rv = client.get('/', headers={'Range': 'bytes=-10'})509 assert rv.status_code == 206510 with app.open_resource('static/index.html') as f:511 assert rv.data == f.read()[-10:]512 rv.close()513 550- rv = c.get('/', headers={'Range': 'bytes=1000-'})514+ rv = client.get('/', headers={'Range': 'bytes=1000-'})515 assert rv.status_code == 416516 rv.close()517 554- rv = c.get('/', headers={'Range': 'bytes=-'})518+ rv = client.get('/', headers={'Range': 'bytes=-'})519 assert rv.status_code == 416520 rv.close()521 558- rv = c.get('/', headers={'Range': 'somethingsomething'})522+ rv = client.get('/', headers={'Range': 'somethingsomething'})523 assert rv.status_code == 416524 rv.close()525 526 last_modified = datetime.datetime.utcfromtimestamp(os.path.getmtime(527 os.path.join(app.root_path, 'static/index.html'))).replace(528 microsecond=0)529 566- rv = c.get('/', headers={'Range': 'bytes=4-15',567- 'If-Range': http_date(last_modified)})530+ rv = client.get('/', headers={'Range': 'bytes=4-15',531+ 'If-Range': http_date(last_modified)})532 assert rv.status_code == 206533 rv.close()534 571- rv = c.get('/', headers={'Range': 'bytes=4-15', 'If-Range': http_date(535+ rv = client.get('/', headers={'Range': 'bytes=4-15', 'If-Range': http_date(536 datetime.datetime(1999, 1, 1))})537 assert rv.status_code == 200538 rv.close()539 576- def test_attachment(self):540+ def test_attachment(self, app, req_ctx):541 app = flask.Flask(__name__)578- with app.test_request_context():579- with open(os.path.join(app.root_path, 'static/index.html')) as f:580- rv = flask.send_file(f, as_attachment=True,581- attachment_filename='index.html')582- value, options = \583- parse_options_header(rv.headers['Content-Disposition'])584- assert value == 'attachment'585- assert options['filename'] == 'index.html'586- assert 'filename*' not in rv.headers['Content-Disposition']587- rv.close()542 589- with app.test_request_context():590- rv = flask.send_file('static/index.html', as_attachment=True)591- value, options = parse_options_header(rv.headers['Content-Disposition'])543+ with open(os.path.join(app.root_path, 'static/index.html')) as f:544+ rv = flask.send_file(f, as_attachment=True,545+ attachment_filename='index.html')546+ value, options = \547+ parse_options_header(rv.headers['Content-Disposition'])548 assert value == 'attachment'549 assert options['filename'] == 'index.html'550+ assert 'filename*' not in rv.headers['Content-Disposition']551 rv.close()552 596- with app.test_request_context():597- rv = flask.send_file(StringIO('Test'), as_attachment=True,598- attachment_filename='index.txt',599- add_etags=False)600- assert rv.mimetype == 'text/plain'601- value, options = parse_options_header(rv.headers['Content-Disposition'])602- assert value == 'attachment'603- assert options['filename'] == 'index.txt'604- rv.close()553+ rv = flask.send_file('static/index.html', as_attachment=True)554+ value, options = parse_options_header(rv.headers['Content-Disposition'])555+ assert value == 'attachment'556+ assert options['filename'] == 'index.html'557+ rv.close()558 606- def test_attachment_with_utf8_filename(self):607- app = flask.Flask(__name__)559+ rv = flask.send_file(StringIO('Test'), as_attachment=True,560+ attachment_filename='index.txt',561+ add_etags=False)562+ assert rv.mimetype == 'text/plain'563+ value, options = parse_options_header(rv.headers['Content-Disposition'])564+ assert value == 'attachment'565+ assert options['filename'] == 'index.txt'566+ rv.close()567 609- with app.test_request_context():610- rv = flask.send_file('static/index.html', as_attachment=True, attachment_filename=u'Ñandú/pingüino.txt')611- content_disposition = set(rv.headers['Content-Disposition'].split('; '))612- assert content_disposition == set((613- 'attachment',614- 'filename="Nandu/pinguino.txt"',615- "filename*=UTF-8''%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt"616- ))617- rv.close()568+ def test_attachment_with_utf8_filename(self, app, req_ctx):569+ rv = flask.send_file('static/index.html', as_attachment=True, attachment_filename=u'Ñandú/pingüino.txt')570+ content_disposition = set(rv.headers['Content-Disposition'].split('; '))571+ assert content_disposition == set((572+ 'attachment',573+ 'filename="Nandu/pinguino.txt"',574+ "filename*=UTF-8''%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt"575+ ))576+ rv.close()577 619- def test_static_file(self):620- app = flask.Flask(__name__)578+ def test_static_file(self, app, req_ctx):579 # default cache timeout is 12 hours622- with app.test_request_context():623- # Test with static file handler.624- rv = app.send_static_file('index.html')625- cc = parse_cache_control_header(rv.headers['Cache-Control'])626- assert cc.max_age == 12 * 60 * 60627- rv.close()628- # Test again with direct use of send_file utility.629- rv = flask.send_file('static/index.html')630- cc = parse_cache_control_header(rv.headers['Cache-Control'])631- assert cc.max_age == 12 * 60 * 60632- rv.close()580+581+ # Test with static file handler.582+ rv = app.send_static_file('index.html')583+ cc = parse_cache_control_header(rv.headers['Cache-Control'])584+ assert cc.max_age == 12 * 60 * 60585+ rv.close()586+ # Test again with direct use of send_file utility.587+ rv = flask.send_file('static/index.html')588+ cc = parse_cache_control_header(rv.headers['Cache-Control'])589+ assert cc.max_age == 12 * 60 * 60590+ rv.close()591 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600634- with app.test_request_context():635- # Test with static file handler.636- rv = app.send_static_file('index.html')637- cc = parse_cache_control_header(rv.headers['Cache-Control'])638- assert cc.max_age == 3600639- rv.close()640- # Test again with direct use of send_file utility.641- rv = flask.send_file('static/index.html')642- cc = parse_cache_control_header(rv.headers['Cache-Control'])643- assert cc.max_age == 3600644- rv.close()592+593+ # Test with static file handler.594+ rv = app.send_static_file('index.html')595+ cc = parse_cache_control_header(rv.headers['Cache-Control'])596+ assert cc.max_age == 3600597+ rv.close()598+ # Test again with direct use of send_file utility.599+ rv = flask.send_file('static/index.html')600+ cc = parse_cache_control_header(rv.headers['Cache-Control'])601+ assert cc.max_age == 3600602+ rv.close()603+604 class StaticFileApp(flask.Flask):605 def get_send_file_max_age(self, filename):606 return 10607+608 app = StaticFileApp(__name__)609 with app.test_request_context():610 # Test with static file handler.611 rv = app.send_static_file('index.html')5 unmodified lines617 cc = parse_cache_control_header(rv.headers['Cache-Control'])618 assert cc.max_age == 10619 rv.close()620 661- def test_send_from_directory(self):662- app = flask.Flask(__name__)621+ def test_send_from_directory(self, app, req_ctx):622 app.testing = True623 app.root_path = os.path.join(os.path.dirname(__file__),624 'test_apps', 'subdomaintestmodule')666- with app.test_request_context():667- rv = flask.send_from_directory('static', 'hello.txt')668- rv.direct_passthrough = False669- assert rv.data.strip() == b'Hello Subdomain'670- rv.close()625+ rv = flask.send_from_directory('static', 'hello.txt')626+ rv.direct_passthrough = False627+ assert rv.data.strip() == b'Hello Subdomain'628+ rv.close()629 672- def test_send_from_directory_bad_request(self):673- app = flask.Flask(__name__)630+ def test_send_from_directory_bad_request(self, app, req_ctx):631 app.testing = True632 app.root_path = os.path.join(os.path.dirname(__file__),633 'test_apps', 'subdomaintestmodule')677- with app.test_request_context():678- with pytest.raises(BadRequest):679- flask.send_from_directory('static', 'bad\x00')634 681-class TestLogging(object):635+ with pytest.raises(BadRequest):636+ flask.send_from_directory('static', 'bad\x00')637 638+639+class TestLogging(object):640 def test_logger_cache(self):641 app = flask.Flask(__name__)642 logger1 = app.logger643 assert app.logger is logger125 unmodified lines669 670 with pytest.raises(ZeroDivisionError):671 c.get('/exc')672 716- def test_debug_log_override(self):717- app = flask.Flask(__name__)673+ def test_debug_log_override(self, app):674 app.debug = True675 app.logger_name = 'flask_tests/test_debug_log_override'676 app.logger.level = 10677 assert app.logger.level == 10678 723- def test_exception_logging(self):679+ def test_exception_logging(self, app):680 out = StringIO()725- app = flask.Flask(__name__)681 app.config['LOGGER_HANDLER_POLICY'] = 'never'682 app.logger_name = 'flask_tests/test_exception_logging'683 app.logger.addHandler(StreamHandler(out))684+ app.testing = False685 686 @app.route('/')687 def index():688 1 // 07 unmodified lines696 assert 'Traceback (most recent call last):' in err697 assert '1 // 0' in err698 assert 'ZeroDivisionError:' in err699 744- def test_processor_exceptions(self):745- app = flask.Flask(__name__)700+ def test_processor_exceptions(self, app, client):701 app.config['LOGGER_HANDLER_POLICY'] = 'never'702+ app.testing = False703+704 @app.before_request705 def before_request():706 if trigger == 'before':707 1 // 0708+709 @app.after_request710 def after_request(response):711 if trigger == 'after':712 1 // 0713 return response714+715 @app.route('/')716 def index():717 return 'Foo'718+719 @app.errorhandler(500)720 def internal_server_error(e):721 return 'Hello Server Error', 500722+723 for trigger in 'before', 'after':763- rv = app.test_client().get('/')724+ rv = client.get('/')725 assert rv.status_code == 500726 assert rv.data == b'Hello Server Error'727 767- def test_url_for_with_anchor(self):768- app = flask.Flask(__name__)728+ def test_url_for_with_anchor(self, app, req_ctx):729+730 @app.route('/')731 def index():732 return '42'772- with app.test_request_context():773- assert flask.url_for('index', _anchor='x y') == '/#x%20y'733 775- def test_url_for_with_scheme(self):776- app = flask.Flask(__name__)734+ assert flask.url_for('index', _anchor='x y') == '/#x%20y'735+736+ def test_url_for_with_scheme(self, app, req_ctx):737+738 @app.route('/')739 def index():740 return '42'780- with app.test_request_context():781- assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'741 783- def test_url_for_with_scheme_not_external(self):784- app = flask.Flask(__name__)742+ assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'743+744+ def test_url_for_with_scheme_not_external(self, app, req_ctx):745+746 @app.route('/')747 def index():748 return '42'788- with app.test_request_context():789- pytest.raises(ValueError,790- flask.url_for,791- 'index',792- _scheme='https')749 794- def test_url_for_with_alternating_schemes(self):795- app = flask.Flask(__name__)750+ pytest.raises(ValueError,751+ flask.url_for,752+ 'index',753+ _scheme='https')754+755+ def test_url_for_with_alternating_schemes(self, app, req_ctx):756+757 @app.route('/')758 def index():759 return '42'799- with app.test_request_context():800- assert flask.url_for('index', _external=True) == 'http://localhost/'801- assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'802- assert flask.url_for('index', _external=True) == 'http://localhost/'760 761+ assert flask.url_for('index', _external=True) == 'http://localhost/'762+ assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'763+ assert flask.url_for('index', _external=True) == 'http://localhost/'764+804- def test_url_with_method(self):765+ def test_url_with_method(self, app, req_ctx):766 from flask.views import MethodView806- app = flask.Flask(__name__)767+768 class MyView(MethodView):769 def get(self, id=None):770 if id is None:771 return 'List'772 return 'Get %d' % id773+774 def post(self):775 return 'Create'776+777 myview = MyView.as_view('myview')778 app.add_url_rule('/myview/', methods=['GET'],779 view_func=myview)780 app.add_url_rule('/myview/<int:id>', methods=['GET'],781 view_func=myview)782 app.add_url_rule('/myview/create', methods=['POST'],783 view_func=myview)784 822- with app.test_request_context():823- assert flask.url_for('myview', _method='GET') == '/myview/'824- assert flask.url_for('myview', id=42, _method='GET') == '/myview/42'825- assert flask.url_for('myview', _method='POST') == '/myview/create'785+ assert flask.url_for('myview', _method='GET') == '/myview/'786+ assert flask.url_for('myview', id=42, _method='GET') == '/myview/42'787+ assert flask.url_for('myview', _method='POST') == '/myview/create'788 789 790 class TestNoImports(object):791 """Test Flasks are created without import.14 unmodified lines806 assert False, 'Flask(import_name) is importing import_name.'807 808 809 class TestStreaming(object):848-849- def test_streaming_with_context(self):810+ def test_streaming_with_context(self, app, client):850- app = flask.Flask(__name__)811 app.testing = True812+813 @app.route('/')814 def index():815 def generate():816 yield 'Hello '817 yield flask.request.args['name']818 yield '!'819+820 return flask.Response(flask.stream_with_context(generate()))859- c = app.test_client()860- rv = c.get('/?name=World')821+822+ rv = client.get('/?name=World')823 assert rv.data == b'Hello World!'824 863- def test_streaming_with_context_as_decorator(self):864- app = flask.Flask(__name__)825+ def test_streaming_with_context_as_decorator(self, app, client):826 app.testing = True827+828 @app.route('/')829 def index():830 @flask.stream_with_context831 def generate(hello):832 yield hello833 yield flask.request.args['name']834 yield '!'835+836 return flask.Response(generate('Hello '))874- c = app.test_client()875- rv = c.get('/?name=World')837+838+ rv = client.get('/?name=World')839 assert rv.data == b'Hello World!'840 878- def test_streaming_with_context_and_custom_close(self):879- app = flask.Flask(__name__)841+ def test_streaming_with_context_and_custom_close(self, app, client):842 app.testing = True843 called = []844+845 class Wrapper(object):846 def __init__(self, gen):847 self._gen = gen848+849 def __iter__(self):850 return self851+852 def close(self):853 called.append(42)854+855 def __next__(self):856 return next(self._gen)857+858 next = __next__859+860 @app.route('/')861 def index():862 def generate():863 yield 'Hello '864 yield flask.request.args['name']865 yield '!'866+867 return flask.Response(flask.stream_with_context(868 Wrapper(generate())))900- c = app.test_client()901- rv = c.get('/?name=World')869+870+ rv = client.get('/?name=World')871 assert rv.data == b'Hello World!'872 assert called == [42]873 874 13 unmodified lines888 (('/a/b/c', './'), '/a/b/c/.'),889 (('a/b/c', 'X/..'), 'a/b/c/.'),890 # Base directory is always considered safe891 (('../', 'a/b/c'), '../a/b/c'),923- (('/..', ), '/..'),892+ (('/..',), '/..'),893 )894 895 for args, expected in passing:896 assert flask.safe_join(*args) == expected46 unmodified linesmodified:tests/test_regression.py+3 added-4 removed
7 unmodified lines8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12-import pytest13-14-import os12 import gc13 import sys17-import flask14 import threading15+16+import pytest17 from werkzeug.exceptions import NotFound18 19+import flask20 21 _gc_lock = threading.Lock()22 23 78 unmodified linesmodified:tests/test_reqctx.py+29 added-22 removed
18 unmodified lines19 except ImportError:20 greenlet = None21 22 23-def test_teardown_on_pop():23+def test_teardown_on_pop(app):24 buffer = []25- app = flask.Flask(__name__)25+26 @app.teardown_request27 def end_of_request(exception):28 buffer.append(exception)29 2 unmodified lines32 assert buffer == []33 ctx.pop()34 assert buffer == [None]35 36+36-def test_teardown_with_previous_exception():37+def test_teardown_with_previous_exception(app):38 buffer = []38- app = flask.Flask(__name__)39+40 @app.teardown_request41 def end_of_request(exception):42 buffer.append(exception)43 5 unmodified lines49 with app.test_request_context():50 assert buffer == []51 assert buffer == [None]52 53+52-def test_teardown_with_handled_exception():54+def test_teardown_with_handled_exception(app):55 buffer = []54- app = flask.Flask(__name__)56+57 @app.teardown_request58 def end_of_request(exception):59 buffer.append(exception)60 4 unmodified lines65 except Exception:66 pass67 assert buffer == [None]68 67-def test_proper_test_request_context():68- app = flask.Flask(__name__)69+70+def test_proper_test_request_context(app):71 app.config.update(72 SERVER_NAME='localhost.localdomain:5000'73 )74 6 unmodified lines81 return None82 83 with app.test_request_context('/'):84 assert flask.url_for('index', _external=True) == \83- 'http://localhost.localdomain:5000/'85+ 'http://localhost.localdomain:5000/'86 87 with app.test_request_context('/'):88 assert flask.url_for('sub', _external=True) == \87- 'http://foo.localhost.localdomain:5000/'89+ 'http://foo.localhost.localdomain:5000/'90 91 try:92 with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}):93 pass11 unmodified lines105 app.config.update(SERVER_NAME='localhost:80')106 with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}):107 pass108 107-def test_context_binding():108- app = flask.Flask(__name__)109+110+def test_context_binding(app):111 @app.route('/')112 def index():113 return 'Hello %s!' % flask.request.args['name']114+115 @app.route('/meh')116 def meh():117 return flask.request.url118 2 unmodified lines121 with app.test_request_context('/meh'):122 assert meh() == 'http://localhost/meh'123 assert flask._request_ctx_stack.top is None124 122-def test_context_test():123- app = flask.Flask(__name__)125+126+def test_context_test(app):127 assert not flask.request128 assert not flask.has_request_context()129 ctx = app.test_request_context()130 ctx.push()2 unmodified lines133 assert flask.has_request_context()134 finally:135 ctx.pop()136 134-def test_manual_context_binding():135- app = flask.Flask(__name__)137+138+def test_manual_context_binding(app):139 @app.route('/')140 def index():141 return 'Hello %s!' % flask.request.args['name']142 3 unmodified lines146 ctx.pop()147 with pytest.raises(RuntimeError):148 index()149 150+151 @pytest.mark.skipif(greenlet is None, reason='greenlet not installed')148-def test_greenlet_context_copying():149- app = flask.Flask(__name__)152+def test_greenlet_context_copying(app, client):153 greenlets = []154 155 @app.route('/')156 def index():157 reqctx = flask._request_ctx_stack.top.copy()158+159 def g():160 assert not flask.request161 assert not flask.current_app162 with reqctx:2 unmodified lines165 assert flask.request.path == '/'166 assert flask.request.args['foo'] == 'bar'167 assert not flask.request168 return 42169+170 greenlets.append(greenlet(g))171 return 'Hello World!'172 168- rv = app.test_client().get('/?foo=bar')173+ rv = client.get('/?foo=bar')174 assert rv.data == b'Hello World!'175 176 result = greenlets[0].run()177 assert result == 42178 179+180 @pytest.mark.skipif(greenlet is None, reason='greenlet not installed')175-def test_greenlet_context_copying_api():176- app = flask.Flask(__name__)181+def test_greenlet_context_copying_api(app, client):182 greenlets = []183 184 @app.route('/')185 def index():186 reqctx = flask._request_ctx_stack.top.copy()187+188 @flask.copy_current_request_context189 def g():190 assert flask.request191 assert flask.current_app == app192 assert flask.request.path == '/'193 assert flask.request.args['foo'] == 'bar'194 return 42195+196 greenlets.append(greenlet(g))197 return 'Hello World!'198 192- rv = app.test_client().get('/?foo=bar')199+ rv = client.get('/?foo=bar')200 assert rv.data == b'Hello World!'201 202 result = greenlets[0].run()203 assert result == 4224 unmodified linesmodified:tests/test_templating.py+126 added-84 removed
14 unmodified lines15 import logging16 from jinja2 import TemplateNotFound17 18 19-def test_context_processing():20- app = flask.Flask(__name__)19+def test_context_processing(app):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('/')29 assert rv.data == b'<p>23|42'30 30-def test_original_win():31- app = flask.Flask(__name__)31+32+def test_original_win(app, client):33 @app.route('/')34 def index():35 return flask.render_template_string('{{ config }}', config=42)35- rv = app.test_client().get('/')36+37+ rv = client.get('/')38 assert rv.data == b'42'39 38-def test_request_less_rendering():39- app = flask.Flask(__name__)40+41+def test_request_less_rendering(app, app_ctx):42 app.config['WORLD_NAME'] = 'Special World'43+44 @app.context_processor45 def context_processor():46 return dict(foo=42)47 45- with app.app_context():46- rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} '47- '{{ foo }}')48- assert rv == 'Hello Special World 42'48+ rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} '49+ '{{ foo }}')50+ assert rv == 'Hello Special World 42'51 50-def test_standard_context():51- app = flask.Flask(__name__)52+53+def test_standard_context(app, client):54 app.secret_key = 'development key'55+56 @app.route('/')57 def index():58 flask.g.foo = 2359 flask.session['test'] = 'aha'2 unmodified lines62 {{ g.foo }}63 {{ config.DEBUG }}64 {{ session.test }}65 ''')66+63- rv = app.test_client().get('/?foo=42')67+ rv = client.get('/?foo=42')68 assert rv.data.split() == [b'42', b'23', b'False', b'aha']69 70+66-def test_escaping():71+def test_escaping(app, client):72 text = '<p>Hello World!'68- app = flask.Flask(__name__)73+74 @app.route('/')75 def index():76 return flask.render_template('escaping_template.html', text=text,77 html=flask.Markup(text))78+73- lines = app.test_client().get('/').data.splitlines()79+ lines = client.get('/').data.splitlines()80 assert lines == [81 b'<p>Hello World!',82 b'<p>Hello World!',83 b'<p>Hello World!',1 unmodified line85 b'<p>Hello World!',86 b'<p>Hello World!'87 ]88 89+83-def test_no_escaping():90+def test_no_escaping(app, client):91 text = '<p>Hello World!'85- app = flask.Flask(__name__)92+93 @app.route('/')94 def index():95 return flask.render_template('non_escaping_template.txt', text=text,96 html=flask.Markup(text))97+90- lines = app.test_client().get('/').data.splitlines()98+ lines = client.get('/').data.splitlines()99 assert lines == [100 b'<p>Hello World!',101 b'<p>Hello World!',102 b'<p>Hello World!',3 unmodified lines106 b'<p>Hello World!',107 b'<p>Hello World!'108 ]109 102-def test_escaping_without_template_filename():103- app = flask.Flask(__name__)104- with app.test_request_context():105- assert flask.render_template_string(106- '{{ foo }}', foo='<test>') == '<test>'107- assert flask.render_template('mail.txt', foo='<test>') == \108- '<test> Mail'110 110-def test_macros():111- app = flask.Flask(__name__)112- with app.test_request_context():113- macro = flask.get_template_attribute('_macro.html', 'hello')114- assert macro('World') == 'Hello World!'111+def test_escaping_without_template_filename(app, client, req_ctx):112+ assert flask.render_template_string(113+ '{{ foo }}', foo='<test>') == '<test>'114+ assert flask.render_template('mail.txt', foo='<test>') == '<test> Mail'115 116-def test_template_filter():117- app = flask.Flask(__name__)116+117+def test_macros(app, req_ctx):118+ macro = flask.get_template_attribute('_macro.html', 'hello')119+ assert macro('World') == 'Hello World!'120+121+122+def test_template_filter(app):123 @app.template_filter()124 def my_reverse(s):125 return s[::-1]126+127 assert 'my_reverse' in app.jinja_env.filters.keys()128 assert app.jinja_env.filters['my_reverse'] == my_reverse129 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'130 125-def test_add_template_filter():126- app = flask.Flask(__name__)131+132+def test_add_template_filter(app):133 def my_reverse(s):134 return s[::-1]135+136 app.add_template_filter(my_reverse)137 assert 'my_reverse' in app.jinja_env.filters.keys()138 assert app.jinja_env.filters['my_reverse'] == my_reverse139 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'140 134-def test_template_filter_with_name():135- app = flask.Flask(__name__)141+142+def test_template_filter_with_name(app):143 @app.template_filter('strrev')144 def my_reverse(s):145 return s[::-1]146+147 assert 'strrev' in app.jinja_env.filters.keys()148 assert app.jinja_env.filters['strrev'] == my_reverse149 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'150 143-def test_add_template_filter_with_name():144- app = flask.Flask(__name__)151+152+def test_add_template_filter_with_name(app):153 def my_reverse(s):154 return s[::-1]155+156 app.add_template_filter(my_reverse, 'strrev')157 assert 'strrev' in app.jinja_env.filters.keys()158 assert app.jinja_env.filters['strrev'] == my_reverse159 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'160 152-def test_template_filter_with_template():153- app = flask.Flask(__name__)161+162+def test_template_filter_with_template(app, client):163 @app.template_filter()164 def super_reverse(s):165 return s[::-1]166+167 @app.route('/')168 def index():169 return flask.render_template('template_filter.html', value='abcd')160- rv = app.test_client().get('/')170+171+ rv = client.get('/')172 assert rv.data == b'dcba'173 163-def test_add_template_filter_with_template():164- app = flask.Flask(__name__)174+175+def test_add_template_filter_with_template(app, client):176 def super_reverse(s):177 return s[::-1]178+179 app.add_template_filter(super_reverse)180+181 @app.route('/')182 def index():183 return flask.render_template('template_filter.html', value='abcd')171- rv = app.test_client().get('/')184+185+ rv = client.get('/')186 assert rv.data == b'dcba'187 174-def test_template_filter_with_name_and_template():175- app = flask.Flask(__name__)188+189+def test_template_filter_with_name_and_template(app, client):190 @app.template_filter('super_reverse')191 def my_reverse(s):192 return s[::-1]193+194 @app.route('/')195 def index():196 return flask.render_template('template_filter.html', value='abcd')182- rv = app.test_client().get('/')197+198+ rv = client.get('/')199 assert rv.data == b'dcba'200 185-def test_add_template_filter_with_name_and_template():186- app = flask.Flask(__name__)201+202+def test_add_template_filter_with_name_and_template(app, client):203 def my_reverse(s):204 return s[::-1]205+206 app.add_template_filter(my_reverse, 'super_reverse')207+208 @app.route('/')209 def index():210 return flask.render_template('template_filter.html', value='abcd')193- rv = app.test_client().get('/')211+212+ rv = client.get('/')213 assert rv.data == b'dcba'214 196-def test_template_test():197- app = flask.Flask(__name__)215+216+def test_template_test(app):217 @app.template_test()218 def boolean(value):219 return isinstance(value, bool)220+221 assert 'boolean' in app.jinja_env.tests.keys()222 assert app.jinja_env.tests['boolean'] == boolean223 assert app.jinja_env.tests['boolean'](False)224 205-def test_add_template_test():206- app = flask.Flask(__name__)225+226+def test_add_template_test(app):227 def boolean(value):228 return isinstance(value, bool)229+230 app.add_template_test(boolean)231 assert 'boolean' in app.jinja_env.tests.keys()232 assert app.jinja_env.tests['boolean'] == boolean233 assert app.jinja_env.tests['boolean'](False)234 214-def test_template_test_with_name():215- app = flask.Flask(__name__)235+236+def test_template_test_with_name(app):237 @app.template_test('boolean')238 def is_boolean(value):239 return isinstance(value, bool)240+241 assert 'boolean' in app.jinja_env.tests.keys()242 assert app.jinja_env.tests['boolean'] == is_boolean243 assert app.jinja_env.tests['boolean'](False)244 223-def test_add_template_test_with_name():224- app = flask.Flask(__name__)245+246+def test_add_template_test_with_name(app):247 def is_boolean(value):248 return isinstance(value, bool)249+250 app.add_template_test(is_boolean, 'boolean')251 assert 'boolean' in app.jinja_env.tests.keys()252 assert app.jinja_env.tests['boolean'] == is_boolean253 assert app.jinja_env.tests['boolean'](False)254 232-def test_template_test_with_template():233- app = flask.Flask(__name__)255+256+def test_template_test_with_template(app):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('/')266 assert b'Success!' in rv.data267 243-def test_add_template_test_with_template():244- app = flask.Flask(__name__)268+269+def test_add_template_test_with_template(app, client):270 def boolean(value):271 return isinstance(value, bool)272+273 app.add_template_test(boolean)274+275 @app.route('/')276 def index():277 return flask.render_template('template_test.html', value=False)251- rv = app.test_client().get('/')278+279+ rv = client.get('/')280 assert b'Success!' in rv.data281 254-def test_template_test_with_name_and_template():255- app = flask.Flask(__name__)282+283+def test_template_test_with_name_and_template(app, client):284 @app.template_test('boolean')285 def is_boolean(value):286 return isinstance(value, bool)287+288 @app.route('/')289 def index():290 return flask.render_template('template_test.html', value=False)262- rv = app.test_client().get('/')291+292+ rv = client.get('/')293 assert b'Success!' in rv.data294 265-def test_add_template_test_with_name_and_template():266- app = flask.Flask(__name__)295+296+def test_add_template_test_with_name_and_template(app, client):297 def is_boolean(value):298 return isinstance(value, bool)299+300 app.add_template_test(is_boolean, 'boolean')301+302 @app.route('/')303 def index():304 return flask.render_template('template_test.html', value=False)273- rv = app.test_client().get('/')305+306+ rv = client.get('/')307 assert b'Success!' in rv.data308 276-def test_add_template_global():277- app = flask.Flask(__name__)309+310+def test_add_template_global(app, app_ctx):311 @app.template_global()312 def get_stuff():313 return 42314+315 assert 'get_stuff' in app.jinja_env.globals.keys()316 assert app.jinja_env.globals['get_stuff'] == get_stuff317 assert app.jinja_env.globals['get_stuff'](), 42284- with app.app_context():285- rv = flask.render_template_string('{{ get_stuff() }}')286- assert rv == '42'318 319+ rv = flask.render_template_string('{{ get_stuff() }}')320+ assert rv == '42'321+322+288-def test_custom_template_loader():323+def test_custom_template_loader(client):324 class MyFlask(flask.Flask):325 def create_global_jinja_loader(self):326 from jinja2 import DictLoader327 return DictLoader({'index.html': 'Hello Custom World!'})328+329 app = MyFlask(__name__)330+331 @app.route('/')332 def index():333 return flask.render_template('index.html')334+335 c = app.test_client()336 rv = c.get('/')337 assert rv.data == b'Hello Custom World!'338 301-def test_iterable_loader():302- app = flask.Flask(__name__)339+340+def test_iterable_loader(app, client):341 @app.context_processor342 def context_processor():343 return {'whiskey': 'Jameson'}344+345 @app.route('/')346 def index():347 return flask.render_template(348 ['no_template.xml', # should skip this one310- 'simple_template.html', # should render this311- 'context_template.html'],349+ 'simple_template.html', # should render this350+ 'context_template.html'],351 value=23)352 314- rv = app.test_client().get('/')353+ rv = client.get('/')354 assert rv.data == b'<h1>Jameson</h1>'355 356+317-def test_templates_auto_reload():357+def test_templates_auto_reload(app):358 # debug is False, config option is None319- app = flask.Flask(__name__)359 assert app.debug is False360 assert app.config['TEMPLATES_AUTO_RELOAD'] is None361 assert app.jinja_env.auto_reload is False362 # debug is False, config option is False21 unmodified lines384 app.config['DEBUG'] = True385 app.config['TEMPLATES_AUTO_RELOAD'] = True386 assert app.jinja_env.auto_reload is True387 388+389 def test_template_loader_debugging(test_apps):390 from blueprintapp import app391 392 called = []393+394 class _TestHandler(logging.Handler):395 def handle(x, record):396 called.append(True)397 text = str(record.msg)23 unmodified lines421 app.config['EXPLAIN_TEMPLATE_LOADING'] = old_load_setting422 423 assert len(called) == 1424 425+426 def test_custom_jinja_env():427 class CustomEnvironment(flask.templating.Environment):428 pass429 5 unmodified linesmodified:tests/test_testing.py+49 added-47 removed
14 unmodified lines15 16 from flask._compat import text_type17 18 19-def test_environ_defaults_from_config():20- app = flask.Flask(__name__)21- app.testing = True19+def test_environ_defaults_from_config(app, client):20 app.config['SERVER_NAME'] = 'example.com:1234'21 app.config['APPLICATION_ROOT'] = '/foo'22+23 @app.route('/')24 def index():25 return flask.request.url26 27 ctx = app.test_request_context()28 assert ctx.request.url == 'http://example.com:1234/foo/'30- with app.test_client() as c:31- rv = c.get('/')32- assert rv.data == b'http://example.com:1234/foo/'29 34-def test_environ_defaults():35- app = flask.Flask(__name__)36- app.testing = True30+ rv = client.get('/')31+ assert rv.data == b'http://example.com:1234/foo/'32+33+34+def test_environ_defaults(app, client, app_ctx, req_ctx):35 @app.route('/')36 def index():37 return flask.request.url38 2 unmodified lines41 with app.test_client() as c:42 rv = c.get('/')43 assert rv.data == b'http://localhost/'44 47-def test_environ_base_default():48- app = flask.Flask(__name__)45+46+def test_environ_base_default(app, client, app_ctx):47 app.testing = True48+49 @app.route('/')50 def index():51 flask.g.user_agent = flask.request.headers["User-Agent"]52 return flask.request.remote_addr53 55- with app.test_client() as c:56- rv = c.get('/')57- assert rv.data == b'127.0.0.1'58- assert flask.g.user_agent == 'werkzeug/' + werkzeug.__version__54+ rv = client.get('/')55+ assert rv.data == b'127.0.0.1'56+ assert flask.g.user_agent == 'werkzeug/' + werkzeug.__version__57 60-def test_environ_base_modified():61- app = flask.Flask(__name__)62- app.testing = True58+59+def test_environ_base_modified(app, client, app_ctx):60 @app.route('/')61 def index():62 flask.g.user_agent = flask.request.headers["User-Agent"]63 return flask.request.remote_addr64 68- with app.test_client() as c:69- c.environ_base['REMOTE_ADDR'] = '0.0.0.0'70- c.environ_base['HTTP_USER_AGENT'] = 'Foo'71- rv = c.get('/')72- assert rv.data == b'0.0.0.0'73- assert flask.g.user_agent == 'Foo'65+ client.environ_base['REMOTE_ADDR'] = '0.0.0.0'66+ client.environ_base['HTTP_USER_AGENT'] = 'Foo'67+ rv = client.get('/')68+ assert rv.data == b'0.0.0.0'69+ assert flask.g.user_agent == 'Foo'70 75- c.environ_base['REMOTE_ADDR'] = '0.0.0.1'76- c.environ_base['HTTP_USER_AGENT'] = 'Bar'77- rv = c.get('/')78- assert rv.data == b'0.0.0.1'79- assert flask.g.user_agent == 'Bar'71+ client.environ_base['REMOTE_ADDR'] = '0.0.0.1'72+ client.environ_base['HTTP_USER_AGENT'] = 'Bar'73+ rv = client.get('/')74+ assert rv.data == b'0.0.0.1'75+ assert flask.g.user_agent == 'Bar'76 81-def test_redirect_keep_session():82- app = flask.Flask(__name__)77+78+def test_redirect_keep_session(app, client, app_ctx):79 app.secret_key = 'testing'80 81 @app.route('/', methods=['GET', 'POST'])82 def index():5 unmodified lines88 @app.route('/getsession')89 def get_session():90 return flask.session.get('data', '<missing>')91 96- with app.test_client() as c:92+ with client as c:93 rv = c.get('/getsession')94 assert rv.data == b'<missing>'95 96 rv = c.get('/')8 unmodified lines105 106 rv = c.get('/getsession')107 assert rv.data == b'foo'108 113-def test_session_transactions():114- app = flask.Flask(__name__)115- app.testing = True109+110+def test_session_transactions(app):111 app.secret_key = 'testing'112 113 @app.route('/')114 def index():9 unmodified lines124 with c.session_transaction() as sess:125 assert len(sess) == 1126 assert sess['foo'] == [42]127 128+129 def test_session_transactions_no_null_sessions():130 app = flask.Flask(__name__)131 app.testing = True132 2 unmodified lines135 with c.session_transaction() as sess:136 pass137 assert 'Session backend did not open a session' in str(e.value)138 143-def test_session_transactions_keep_context():144- app = flask.Flask(__name__)145- app.testing = True139+140+def test_session_transactions_keep_context(app, client, req_ctx):141 app.secret_key = 'testing'142 148- with app.test_client() as c:149- rv = c.get('/')150- req = flask.request._get_current_object()151- assert req is not None152- with c.session_transaction():153- assert req is flask.request._get_current_object()143+ rv = client.get('/')144+ req = flask.request._get_current_object()145+ assert req is not None146+ with client.session_transaction():147+ assert req is flask.request._get_current_object()148 155-def test_session_transaction_needs_cookies():156- app = flask.Flask(__name__)157- app.testing = True149+def test_session_transaction_needs_cookies(app):150 c = app.test_client(use_cookies=False)151 with pytest.raises(RuntimeError) as e:152 with c.session_transaction() as s:153 pass154 assert 'cookies' in str(e.value)155 156+157 def test_test_client_context_binding():158 app = flask.Flask(__name__)159 app.config['LOGGER_HANDLER_POLICY'] = 'never'160+161 @app.route('/')162 def index():163 flask.g.value = 42164 return 'Hello World!'20 unmodified lines185 pass186 else:187 raise AssertionError('some kind of exception expected')188 189+190 def test_reuse_client():191 app = flask.Flask(__name__)192 c = app.test_client()193 2 unmodified lines196 197 with c:198 assert c.get('/').status_code == 404199 200+201 def test_test_client_calls_teardown_handlers():202 app = flask.Flask(__name__)203 called = []204+205 @app.teardown_request206 def remember(error):207 called.append(error)208 11 unmodified lines220 c.get('/')221 assert called == [None]222 assert called == [None, None]223 224+225 def test_full_url_request():226 app = flask.Flask(__name__)227 app.testing = True228 6 unmodified lines235 assert rv.status_code == 200236 assert 'gin' in flask.request.form237 assert 'vodka' in flask.request.args238 239+240 def test_subdomain():241 app = flask.Flask(__name__)242 app.config['SERVER_NAME'] = 'example.com'243+244 @app.route('/', subdomain='<company_id>')245 def view(company_id):246 return company_id247 5 unmodified lines253 254 assert 200 == response.status_code255 assert b'xxx' == response.data256 257+258 def test_nosubdomain():259 app = flask.Flask(__name__)260 app.config['SERVER_NAME'] = 'example.com'261+262 @app.route('/<company_id>')263 def view(company_id):264 return company_id265 8 unmodified linesmodified:tests/test_user_error_handler.py+7 added-15 removed
6 unmodified lines7 )8 import flask9 10 11-def test_error_handler_no_match():12- app = flask.Flask(__name__)11+def test_error_handler_no_match(app, client):12 13 class CustomException(Exception):14 pass15 13 unmodified lines29 @app.route('/keyerror')30 def key_error():31 raise KeyError()32 34- c = app.test_client()33+ app.testing = False34+ assert client.get('/custom').data == b'custom'35+ assert client.get('/keyerror').data == b'KeyError'36 36- assert c.get('/custom').data == b'custom'37- assert c.get('/keyerror').data == b'KeyError'37 39-40-def test_error_handler_subclass():38+def test_error_handler_subclass(app):41- app = flask.Flask(__name__)42-39 class ParentException(Exception):40 pass41 42 class ChildExceptionUnregistered(ParentException):30 unmodified lines73 assert c.get('/child-unregistered').data == b'parent'74 assert c.get('/child-registered').data == b'child-registered'75 76 81-def test_error_handler_http_subclass():82- app = flask.Flask(__name__)83-77+def test_error_handler_http_subclass(app):78 class ForbiddenSubclassRegistered(Forbidden):79 pass80 81 class ForbiddenSubclassUnregistered(Forbidden):27 unmodified lines109 assert c.get('/forbidden-unregistered').data == b'forbidden'110 assert c.get('/forbidden-registered').data == b'forbidden-registered'111 112 119-def test_error_handler_blueprint():113+def test_error_handler_blueprint(app):114 bp = flask.Blueprint('bp', __name__)115 116 @bp.errorhandler(500)117 def bp_exception_handler(e):2 unmodified lines120 @bp.route('/error')121 def bp_test():122 raise InternalServerError()123 130- app = flask.Flask(__name__)131-124 @app.errorhandler(500)125 def app_exception_handler(e):126 return 'app-error'127 60 unmodified linesmodified:tests/test_views.py+24 added-20 removed
14 unmodified lines15 import flask.views16 17 from werkzeug.http import parse_set_header18 19+20 def common_test(app):21 c = app.test_client()22 23 assert c.get('/').data == b'GET'1 unmodified line25 assert c.put('/').status_code == 40526 meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])27 assert sorted(meths) == ['GET', 'HEAD', 'OPTIONS', 'POST']28 28-def test_basic_view():29- app = flask.Flask(__name__)29 30+def test_basic_view(app):31 class Index(flask.views.View):32 methods = ['GET', 'POST']33+34 def dispatch_request(self):35 return flask.request.method36 37 app.add_url_rule('/', view_func=Index.as_view('index'))38 common_test(app)39 39-def test_method_based_view():40- app = flask.Flask(__name__)40 41+def test_method_based_view(app):42 class Index(flask.views.MethodView):43 def get(self):44 return 'GET'45+46 def post(self):47 return 'POST'48 49 app.add_url_rule('/', view_func=Index.as_view('index'))50 51 common_test(app)52 52-def test_view_patching():53- app = flask.Flask(__name__)53 54+def test_view_patching(app):55 class Index(flask.views.MethodView):56 def get(self):57 1 // 058+59 def post(self):60 1 // 061 62 class Other(Index):63 def get(self):64 return 'GET'65+66 def post(self):67 return 'POST'68 69 view = Index.as_view('index')70 view.view_class = Other71 app.add_url_rule('/', view_func=view)72 common_test(app)73 72-def test_view_inheritance():73- app = flask.Flask(__name__)74 75+def test_view_inheritance(app):76 class Index(flask.views.MethodView):77 def get(self):78 return 'GET'79+80 def post(self):81 return 'POST'82 83 class BetterIndex(Index):5 unmodified lines89 90 meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])91 assert sorted(meths) == ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST']92 91-def test_view_decorators():92- app = flask.Flask(__name__)93 94+def test_view_decorators(app):95 def add_x_parachute(f):96 def new_function(*args, **kwargs):97 resp = flask.make_response(f(*args, **kwargs))98 resp.headers['X-Parachute'] = 'awesome'99 return resp100+101 return new_function102 103 class Index(flask.views.View):104 decorators = [add_x_parachute]105+106 def dispatch_request(self):107 return 'Awesome'108 109 app.add_url_rule('/', view_func=Index.as_view('index'))1 unmodified line111 rv = c.get('/')112 assert rv.headers['X-Parachute'] == 'awesome'113 assert rv.data == b'Awesome'114 115+116 def test_view_provide_automatic_options_attr():117 app = flask.Flask(__name__)118 119 class Index1(flask.views.View):120 provide_automatic_options = False121+122 def dispatch_request(self):123 return 'Hello World!'124 125 app.add_url_rule('/', view_func=Index1.as_view('index'))5 unmodified lines131 132 class Index2(flask.views.View):133 methods = ['OPTIONS']134 provide_automatic_options = True135+136 def dispatch_request(self):137 return 'Hello World!'138 139 app.add_url_rule('/', view_func=Index2.as_view('index'))11 unmodified lines151 c = app.test_client()152 rv = c.open('/', method='OPTIONS')153 assert 'OPTIONS' in rv.allow154 149-def test_implicit_head():150- app = flask.Flask(__name__)155 156+def test_implicit_head(app):157 class Index(flask.views.MethodView):158 def get(self):159 return flask.Response('Blub', headers={160 'X-Method': flask.request.method7 unmodified lines168 rv = c.head('/')169 assert rv.data == b''170 assert rv.headers['X-Method'] == 'HEAD'171 167-def test_explicit_head():168- app = flask.Flask(__name__)172 173+def test_explicit_head(app):174 class Index(flask.views.MethodView):175 def get(self):176 return 'GET'177+178 def head(self):179 return flask.Response('', headers={'X-Method': 'HEAD'})180 181 app.add_url_rule('/', view_func=Index.as_view('index'))3 unmodified lines185 rv = c.head('/')186 assert rv.data == b''187 assert rv.headers['X-Method'] == 'HEAD'188 184-def test_endpoint_override():185- app = flask.Flask(__name__)189+190+def test_endpoint_override(app):191 app.debug = True192 193 class Index(flask.views.View):194 methods = ['GET', 'POST']195+196 def dispatch_request(self):197 return flask.request.method198 199 app.add_url_rule('/', view_func=Index.as_view('index'))3 unmodified lines203 204 # But these tests should still pass. We just log a warning.205 common_test(app)206 201-def test_multiple_inheritance():202- app = flask.Flask(__name__)207 208+def test_multiple_inheritance(app):209 class GetView(flask.views.MethodView):210 def get(self):211 return 'GET'212 10 unmodified lines223 assert c.get('/').data == b'GET'224 assert c.delete('/').data == b'DELETE'225 assert sorted(GetDeleteView.methods) == ['DELETE', 'GET']226 222-def test_remove_method_from_parent():223- app = flask.Flask(__name__)227 228+def test_remove_method_from_parent(app):229 class GetView(flask.views.MethodView):230 def get(self):231 return 'GET'232 13 unmodified lines