Skip to content
Myr

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

authored by Christian Stade-Schuldt · committed by David Lord · parent 81c2440 · Browse files · 12 files+997 added−972 removed
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

12 files+997 added−972 removed

modified:tests/conftest.py+45 added-7 removed
11 unmodified lines
12import sys13import pkgutil14import pytest15import textwrap16from flask import Flask as _Flask171819class Flask(_Flask):20 testing = True21 secret_key = __name__2223 def make_response(self, rv):24 if rv is None:25 rv = ''26 return super(Flask, self).make_response(rv)272829@pytest.fixture30def app():31 app = Flask(__name__)32 return app333435@pytest.fixture36def app_ctx(app):37 with app.app_context() as ctx:38 yield ctx394041@pytest.fixture42def req_ctx(app):43 with app.test_request_context() as ctx:44 yield ctx454647@pytest.fixture48def client(app):49 return app.test_client()505152@pytest.fixture53def test_apps(monkeypatch):54 monkeypatch.syspath_prepend(55 os.path.abspath(os.path.join(56 os.path.dirname(__file__), 'test_apps'))
39 unmodified lines
96 old_get_loader = pkgutil.get_loader9798 def get_loader(*args, **kwargs):99 return LimitedLoader(old_get_loader(*args, **kwargs))100101 monkeypatch.setattr(pkgutil, 'get_loader', get_loader)102103104@pytest.fixture105def 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 lines
116117118@pytest.fixture119def 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 rv127128129@pytest.fixture130def 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."""133134 def inner(name, base=modules_tmpdir):135 if not isinstance(name, str):136 raise ValueError(name)137 base.join(name).ensure_dir()
15 unmodified lines
153 )154 egg_path, = modules_tmpdir.join('dist/').listdir()155 monkeypatch.syspath_prepend(str(egg_path))156 return egg_path157158 return inner159160161@pytest.fixture162def purge_module(request):163 def inner(name):164 request.addfinalizer(lambda: sys.modules.pop(name, None))165166 return inner167168169@pytest.yield_fixture(autouse=True)170def 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 lines
1314import flask151617def test_basic_url_generation():18 app = flask.Flask(__name__)17def test_basic_url_generation(app):18 app.config['SERVER_NAME'] = 'localhost'19 app.config['PREFERRED_URL_SCHEME'] = 'https'2021 @app.route('/')
3 unmodified lines
25 with app.app_context():26 rv = flask.url_for('index')27 assert rv == 'https://localhost/'2830def test_url_generation_requires_server_name():31 app = flask.Flask(__name__)2930def test_url_generation_requires_server_name(app):31 with app.app_context():32 with pytest.raises(RuntimeError):33 flask.url_for('index')343536def test_url_generation_without_context_fails():37 with pytest.raises(RuntimeError):38 flask.url_for('index')3940def test_request_context_means_app_context():41 app = flask.Flask(__name__)4041def 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 None4546def test_app_context_provides_current_app():47 app = flask.Flask(__name__)4647def 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 None515252def test_app_tearing_down():53def test_app_tearing_down(app):54 cleanup_stuff = []54 app = flask.Flask(__name__)5556 @app.teardown_appcontext57 def cleanup(exception):58 cleanup_stuff.append(exception)59
1 unmodified line
61 pass6263 assert cleanup_stuff == [None]646564def test_app_tearing_down_with_previous_exception():66def test_app_tearing_down_with_previous_exception(app):67 cleanup_stuff = []66 app = flask.Flask(__name__)6869 @app.teardown_appcontext70 def cleanup(exception):71 cleanup_stuff.append(exception)72
6 unmodified lines
79 pass8081 assert cleanup_stuff == [None]828381def test_app_tearing_down_with_handled_exception():84def test_app_tearing_down_with_handled_exception(app):85 cleanup_stuff = []83 app = flask.Flask(__name__)8687 @app.teardown_appcontext88 def cleanup(exception):89 cleanup_stuff.append(exception)90
4 unmodified lines
95 pass9697 assert cleanup_stuff == [None]9896def 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']99100def 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']119120118def test_custom_app_ctx_globals_class():121def test_custom_app_ctx_globals_class(app):122 class CustomRequestGlobals(object):123 def __init__(self):124 self.spam = 'eggs'122 app = flask.Flask(__name__)125126 app.app_ctx_globals_class = CustomRequestGlobals127 with app.app_context():128 assert flask.render_template_string('{{ g.spam }}') == 'eggs'129130127def test_context_refcounts():131def test_context_refcounts(app, client):132 called = []129 app = flask.Flask(__name__)133134 @app.teardown_request135 def teardown_req(error=None):136 called.append('request')137138 @app.teardown_appcontext139 def teardown_app(error=None):140 called.append('app')141142 @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('/')150151 res = client.get('/')152 assert res.status_code == 200153 assert res.data == b''154 assert called == ['request', 'app']155156151def test_clean_pop():157def test_clean_pop(app):158 app.testing = False159 called = []153 app = flask.Flask(__name__)160161 @app.teardown_request162 def teardown_req(error=None):163 1 / 0
7 unmodified lines
171 called.append(flask.current_app.name)172 except ZeroDivisionError:173 pass174169 assert called == ['test_appctx', 'TEARDOWN']175 assert called == ['conftest', 'TEARDOWN']176 assert not flask.current_app
modified:tests/test_basic.py+207 added-280 removed
23 unmodified lines
24from werkzeug.routing import BuildError25import werkzeug.serving262728def test_options_work():29 app = flask.Flask(__name__)3028def test_options_work(app, client):29 @app.route('/', methods=['GET', 'POST'])30 def index():31 return 'Hello World'3234 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''363739def test_options_on_multiple_rules():40 app = flask.Flask(__name__)4138def test_options_on_multiple_rules(app, client):39 @app.route('/', methods=['GET', 'POST'])40 def index():41 return 'Hello World'4243 @app.route('/', methods=['PUT'])44 def index_put():45 return 'Aha!'4649 rv = app.test_client().open('/', method='OPTIONS')47 rv = client.open('/', method='OPTIONS')48 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']495051def test_provide_automatic_options_attr():52 app = flask.Flask(__name__)5354 def index():55 return 'Hello World!'5657 index.provide_automatic_options = False58 app.route('/')(index)59 rv = app.test_client().open('/', method='OPTIONS')60 assert rv.status_code == 405
1 unmodified line
62 app = flask.Flask(__name__)6364 def index2():65 return 'Hello World!'6667 index2.provide_automatic_options = True68 app.route('/', methods=['OPTIONS'])(index2)69 rv = app.test_client().open('/', method='OPTIONS')70 assert sorted(rv.allow) == ['OPTIONS']717273def test_provide_automatic_options_kwarg():74 app = flask.Flask(__name__)7573def test_provide_automatic_options_kwarg(app, client):74 def index():75 return flask.request.method7677 def more():
3 unmodified lines
81 app.add_url_rule(82 '/more', view_func=more, methods=['GET', 'POST'],83 provide_automatic_options=False84 )85 assert client.get('/').data == b'GET'8688 c = app.test_client()89 assert c.get('/').data == b'GET'9091 rv = c.post('/')87 rv = client.post('/')88 assert rv.status_code == 40589 assert sorted(rv.allow) == ['GET', 'HEAD']9091 # 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')9697 assert rv.status_code == 40598103 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'104109 rv = c.delete('/more')105 rv = client.delete('/more')106 assert rv.status_code == 405107 assert sorted(rv.allow) == ['GET', 'HEAD', 'POST']108113 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')113114 assert rv.status_code == 405115116121def test_request_dispatching():122 app = flask.Flask(__name__)123117def test_request_dispatching(app, client):118 @app.route('/')119 def index():120 return flask.request.method121122 @app.route('/more', methods=['GET', 'POST'])123 def more():124 return flask.request.method125132 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']138139147def test_disallow_string_for_allowed_methods():148 app = flask.Flask(__name__)140def test_disallow_string_for_allowed_methods(app):141 with pytest.raises(TypeError):142 @app.route('/', methods='GET POST')143 def index():144 return "Hey"145146155def test_url_mapping():156 app = flask.Flask(__name__)157147def test_url_mapping(app, client):148 random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"149150 def index():151 return flask.request.method
3 unmodified lines
155156 def options():157 return random_uuid4158169159 app.add_url_rule('/', 'index', index)160 app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])161162 # Issue 1288: Test that automatic options are not added when non-uppercase 'options' in methods163 app.add_url_rule('/options', 'options', options, methods=['options'])164176 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")180181194def test_werkzeug_routing():182def 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 lines
190 return 'bar'191192 def index():193 return 'index'194195 app.view_functions['bar'] = bar196 app.view_functions['index'] = index197210 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'200201215def test_endpoint_decorator():202def 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 lines
213 @app.endpoint('index')214 def index():215 return 'index'216231 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'219220236def test_session():237 app = flask.Flask(__name__)221def test_session(app, client):222 app.secret_key = 'testkey'223224 @app.route('/set', methods=['POST'])225 def set():
3 unmodified lines
229 @app.route('/get')230 def get():231 return flask.session['value']232249 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'235236254def test_session_using_server_name():255 app = flask.Flask(__name__)237def test_session_using_server_name(app, client):238 app.config.update(239 SECRET_KEY='foo',240 SERVER_NAME='example.com'241 )
1 unmodified line
243 @app.route('/')244 def index():245 flask.session['testing'] = 42246 return 'Hello World'247265 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()251252270def test_session_using_server_name_and_port():271 app = flask.Flask(__name__)253def 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 line
259 @app.route('/')260 def index():261 flask.session['testing'] = 42262 return 'Hello World'263281 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()267268286def test_session_using_server_name_port_and_path():287 app = flask.Flask(__name__)269def 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 lines
276 @app.route('/')277 def index():278 flask.session['testing'] = 42279 return 'Hello World'280298 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()285286304def test_session_using_application_root():287def test_session_using_application_root(app, client):288 class PrefixPathMiddleware(object):306289 def __init__(self, app, prefix):290 self.app = app291 self.prefix = prefix292293 def __call__(self, environ, start_response):294 environ['SCRIPT_NAME'] = self.prefix295 return self.app(environ, start_response)296315 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 lines
303 @app.route('/')304 def index():305 flask.session['testing'] = 42306 return 'Hello World'307326 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()310311330def test_session_using_session_settings():331 app = flask.Flask(__name__)312def 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 lines
323 @app.route('/')324 def index():325 flask.session['testing'] = 42326 return 'Hello World'327346 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 cookie334335354def test_session_localhost_warning(recwarn):355 app = flask.Flask(__name__)336def test_session_localhost_warning(recwarn, app, client):337 app.config.update(338 SECRET_KEY='testing',339 SERVER_NAME='localhost:5000',340 )
2 unmodified lines
343 def index():344 flask.session['testing'] = 42345 return 'testing'346366 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)351352372def test_session_ip_warning(recwarn):373 app = flask.Flask(__name__)353def 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 lines
360 def index():361 flask.session['testing'] = 42362 return 'testing'363384 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 lines
372373 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]376377 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')381382402def test_session_expiration():383def test_session_expiration(app, client):384 permanent = True404 app = flask.Flask(__name__)385 app.secret_key = 'testkey'386387 @app.route('/')388 def index():
4 unmodified lines
393 @app.route('/test')394 def test():395 return text_type(flask.session.permanent)396417 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 lines
406 rv = client.get('/test')407 assert rv.data == b'True'408409 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 None414415437def test_session_stored_last():438 app = flask.Flask(__name__)416def test_session_stored_last(app, client):417 app.secret_key = 'development-key'440 app.testing = True418419 @app.after_request420 def modify_session(response):421 flask.session['foo'] = 42
2 unmodified lines
424 @app.route('/')425 def dump_session_contents():426 return repr(flask.session.get('foo'))427451 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'430431456def test_session_special_types():457 app = flask.Flask(__name__)432def 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()436437 @app.after_request
8 unmodified lines
446 @app.route('/')447 def dump_session_contents():448 return pickle.dumps(dict(flask.session))449476 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_uuid
1 unmodified line
457 assert type(rv['b']) == bytes458 assert rv['t'] == (1, 2, 3)459460488def test_session_cookie_setting():489 app = flask.Flask(__name__)490 app.testing = True461def test_session_cookie_setting(app):462 app.secret_key = 'dev key'463 is_permanent = True464465 @app.route('/bump')
33 unmodified lines
499 app.config['SESSION_REFRESH_EACH_REQUEST'] = False500 run_test(expect_header=False)501502532def test_session_vary_cookie():533 app = flask.Flask(__name__)503def test_session_vary_cookie(app, client):504 app.secret_key = 'testkey'505506 @app.route('/set')507 def set_session():
15 unmodified lines
523 @app.route('/no-vary-header')524 def no_vary_header():525 return ''526557 c = app.test_client()558527 def expect(path, header=True):560 rv = c.get(path)528 rv = client.get(path)529530 if header:531 assert rv.headers['Vary'] == 'Cookie'532 else:
5 unmodified lines
538 expect('/setdefault')539 expect('/no-vary-header', False)540541574def test_flashes():575 app = flask.Flask(__name__)542def test_flashes(app, req_ctx):543 app.secret_key = 'testkey'544578 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']551552587def test_extended_flashing():553def 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.559594 app = flask.Flask(__name__)560 app.secret_key = 'testkey'596 app.testing = True561562 @app.route('/')563 def index():564 flask.flash(u'Hello World')
49 unmodified lines
614 return ''615616 # Create new test client on each test to clean flashed messages.617654 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/')621658 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/')625662 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/')629666 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/')633670 c = app.test_client()671 c.get('/')672 c.get('/test_filters_without_returning_categories/')634674675def test_request_processing():635def test_request_processing(app, client):676 app = flask.Flask(__name__)636 evts = []637638 @app.before_request639 def before_request():
9 unmodified lines
649 def index():650 assert 'before' in evts651 assert 'after' not in evts652 return 'request'653654 assert 'after' not in evts695 rv = app.test_client().get('/').data655 rv = client.get('/').data656 assert 'after' in evts657 assert rv == b'request|after'658659700def test_request_preprocessing_early_return():701 app = flask.Flask(__name__)660def test_request_preprocessing_early_return(app, client):661 evts = []662663 @app.before_request664 def before_request1():
13 unmodified lines
678 def index():679 evts.append('index')680 return "damnit"681723 rv = app.test_client().get('/').data.strip()682 rv = client.get('/').data.strip()683 assert rv == b'hello'684 assert evts == [1, 2]685686728def test_after_request_processing():729 app = flask.Flask(__name__)730 app.testing = True731687def 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 response694695 return 'Test'739 c = app.test_client()740 resp = c.get('/')696697 resp = client.get('/')698 assert resp.status_code == 200699 assert resp.headers['X-Foo'] == 'a header'700701745def test_teardown_request_handler():702def test_teardown_request_handler(app, client):703 called = []747 app = flask.Flask(__name__)704705 @app.teardown_request706 def teardown_request(exc):707 called.append(True)
1 unmodified line
709710 @app.route('/')711 def root():712 return "Response"757 rv = app.test_client().get('/')713714 rv = client.get('/')715 assert rv.status_code == 200716 assert b'Response' in rv.data717 assert len(called) == 1718719763def test_teardown_request_handler_debug_mode():720def test_teardown_request_handler_debug_mode(app, client):721 called = []765 app = flask.Flask(__name__)766 app.testing = True722723 @app.teardown_request724 def teardown_request(exc):725 called.append(True)
1 unmodified line
727728 @app.route('/')729 def root():730 return "Response"776 rv = app.test_client().get('/')731732 rv = client.get('/')733 assert rv.status_code == 200734 assert b'Response' in rv.data735 assert len(called) == 1736737782def test_teardown_request_handler_error():738def test_teardown_request_handler_error(app, client):739 called = []784 app = flask.Flask(__name__)740 app.config['LOGGER_HANDLER_POLICY'] = 'never'741 app.testing = False742743 @app.teardown_request744 def teardown_request1(exc):745 assert type(exc) == ZeroDivisionError
20 unmodified lines
766767 @app.route('/')768 def fails():769 1 // 0814 rv = app.test_client().get('/')770771 rv = client.get('/')772 assert rv.status_code == 500773 assert b'Internal Server Error' in rv.data774 assert len(called) == 2775776820def test_before_after_request_order():777def test_before_after_request_order(app, client):778 called = []822 app = flask.Flask(__name__)779780 @app.before_request781 def before1():782 called.append(1)
22 unmodified lines
805806 @app.route('/')807 def index():808 return '42'853 rv = app.test_client().get('/')809810 rv = client.get('/')811 assert rv.data == b'42'812 assert called == [1, 2, 3, 4, 5, 6]813814858def test_error_handling():859 app = flask.Flask(__name__)815def test_error_handling(app, client):816 app.config['LOGGER_HANDLER_POLICY'] = 'never'817 app.testing = False818819 @app.errorhandler(404)820 def not_found(e):821 return 'not found', 404
16 unmodified lines
838839 @app.route('/forbidden')840 def error2():841 flask.abort(403)885 c = app.test_client()886 rv = c.get('/')842843 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.data852853897def test_error_handling_processing():898 app = flask.Flask(__name__)854def test_error_handling_processing(app, client):855 app.config['LOGGER_HANDLER_POLICY'] = 'never'856 app.testing = False857858 @app.errorhandler(500)859 def internal_server_error(e):860 return 'internal server error', 500
6 unmodified lines
867 def after_request(resp):868 resp.mimetype = 'text/x-special'869 return resp870914 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'874875920def test_baseexception_error_handling():921 app = flask.Flask(__name__)876def test_baseexception_error_handling(app, client):877 app.config['LOGGER_HANDLER_POLICY'] = 'never'878 app.testing = False879880 @app.route('/')881 def broken_func():882 raise KeyboardInterrupt()883928 with app.test_client() as c:929 with pytest.raises(KeyboardInterrupt):930 c.get('/')884 with pytest.raises(KeyboardInterrupt):885 client.get('/')886887 ctx = flask._request_ctx_stack.top888 assert ctx.preserved889 assert type(ctx._preserved_exc) is KeyboardInterrupt890891937def test_before_request_and_routing_errors():938 app = flask.Flask(__name__)939892def test_before_request_and_routing_errors(app, client):893 @app.before_request894 def attach_something():895 flask.g.something = 'value'896897 @app.errorhandler(404)898 def return_something(error):899 return flask.g.something, 404947 rv = app.test_client().get('/')900901 rv = client.get('/')902 assert rv.status_code == 404903 assert rv.data == b'value'904905952def test_user_error_handling():906def test_user_error_handling(app, client):907 class MyException(Exception):908 pass909956 app = flask.Flask(__name__)957910 @app.errorhandler(MyException)911 def handle_my_exception(e):912 assert isinstance(e, MyException)913 return '42'
1 unmodified line
915 @app.route('/')916 def index():917 raise MyException()918967 c = app.test_client()968 assert c.get('/').data == b'42'919 assert client.get('/').data == b'42'920921971def test_http_error_subclass_handling():922def test_http_error_subclass_handling(app, client):923 class ForbiddenSubclass(Forbidden):924 pass925975 app = flask.Flask(__name__)976926 @app.errorhandler(ForbiddenSubclass)927 def handle_forbidden_subclass(e):928 assert isinstance(e, ForbiddenSubclass)929 return 'banana'
15 unmodified lines
945 @app.route('/3')946 def index3():947 raise Forbidden()9481000 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'9529531006def test_trapping_of_bad_request_key_errors():1007 app = flask.Flask(__name__)1008 app.testing = True1009954def test_trapping_of_bad_request_key_errors(app):955 @app.route('/fail')956 def fail():957 flask.request.form['missing_key']958959 c = app.test_client()960 assert c.get('/fail').status_code == 400961962 app.config['TRAP_BAD_REQUEST_ERRORS'] = True
2 unmodified lines
965 c.get("/fail")966 assert e.errisinstance(BadRequest)9679681023def test_trapping_of_all_http_exceptions():1024 app = flask.Flask(__name__)1025 app.testing = True969def test_trapping_of_all_http_exceptions(app, client):970 app.config['TRAP_HTTP_EXCEPTIONS'] = True971972 @app.route('/fail')973 def fail():974 flask.abort(404)9751032 c = app.test_client()976 with pytest.raises(NotFound):1034 c.get('/fail')977 client.get('/fail')9789791037def test_enctype_debug_helper():980def test_enctype_debug_helper(app, client):981 from flask.debughelpers import DebugFilesKeyError1039 app = flask.Flask(__name__)982 app.debug = True983984 @app.route('/fail', methods=['POST'])985 def index():
1 unmodified line
987988 # 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 lines
1171 "msg": {1172 "submsg": "W00t"1173 },1174 "msg2": "foobar"1233 }1175 }11761177 rv = flask.make_response(1178 flask.jsonify(uncompressed_msg), 200)1179 assert rv.data == compressed_msg
2 unmodified lines
1182def 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'11891190 rv = flask.make_response(1191 flask.jsonify(compressed_msg), 200)
25 unmodified lines
12171218 @app.route('/hello/<name>', methods=['POST'])1219 def hello():1220 pass12211222 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'122612271228def test_build_error_handler():1229 app = flask.Flask(__name__)
17 unmodified lines
1247 # Test a custom handler.1248 def handler(error, endpoint, values):1249 # Just a test.1250 return '/test_handler/'12511252 app.url_build_error_handlers.append(handler)1253 with app.test_request_context():1254 assert flask.url_for('spam') == '/test_handler/'1255
3 unmodified lines
12591260 # Test a custom handler which reraises the BuildError1261 def handler_raises_build_error(error, endpoint, values):1262 raise error12631264 app.url_build_error_handlers.append(handler_raises_build_error)12651266 with app.test_request_context():1267 pytest.raises(BuildError, flask.url_for, 'not.existing')
19 unmodified lines
1287def test_custom_converters():1288 from werkzeug.routing import BaseConverter12891290 class ListConverter(BaseConverter):13461291 def to_python(self, value):1292 return value.split(',')12931294 def to_url(self, value):1295 base_to_url = super(ListConverter, self).to_url1296 return ','.join(base_to_url(x) for x in value)12971298 app = flask.Flask(__name__)1299 app.url_map.converters['list'] = ListConverter13001301 @app.route('/<list:args>')1302 def index(args):1303 return '|'.join(args)13041305 c = app.test_client()1306 assert c.get('/1,2,3').data == b'1|2|3'13071308
4 unmodified lines
1313 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()131913201321def test_static_path_deprecated(recwarn):
26 unmodified lines
1348 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 lines
14301431 @app.route('/')1432 def index():1433 1 // 014341435 c = app.test_client()1436 if config_key is not None:1437 app.config[config_key] = True1438 with pytest.raises(Exception):
57 unmodified lines
14961497 @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)15021503 @app.url_value_preprocessor1504 def pull_lang_code(endpoint, values):
63 unmodified lines
15681569 @app.route('/')1570 def index():1571 return 'Awesome'15721573 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 lines
15821583 @app.route('/foo')1584 def working():1585 return 'Meh'15861587 assert app.test_client().get('/foo').data == b'Meh'1588 assert app.got_first_request15891590
3 unmodified lines
15941595 @app.before_first_request1596 def foo():1597 got.append(42)15981599 c = app.test_client()1600 c.get('/')1601 assert got == [42]1602 c.get('/')
29 unmodified lines
16321633 @app.route('/foo/', methods=['GET', 'POST'])1634 def foo():1635 return 'success'16361637 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 lines
1697 assert flask._request_ctx_stack.top is None1698 assert flask._app_ctx_stack.top is None169917001750def test_preserve_remembers_exception():1751 app = flask.Flask(__name__)1701def test_preserve_remembers_exception(app, client):1702 app.debug = True1703 errors = []17041705 @app.route('/fail')
7 unmodified lines
1713 @app.teardown_request1714 def teardown_handler(exc):1715 errors.append(exc)17161767 c = app.test_client()17681717 # 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 == []17211722 # 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)17261727 # At this point another request does nothing.1780 c.get('/success')1728 client.get('/success')1729 assert len(errors) == 31730 assert errors[1] is None173117321785def test_get_method_on_g():1786 app = flask.Flask(__name__)1787 app.testing = True1733def 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 == 4217391789 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 == 4217401741def 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']17471797def test_g_iteration_protocol():1798 app = flask.Flask(__name__)1799 app.testing = True17481801 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']1749def test_subdomain_basic_support(app, client):1750 app.config['SERVER_NAME'] = 'localhost.localdomain'175118081809def test_subdomain_basic_support():1810 app = flask.Flask(__name__)1811 app.config['SERVER_NAME'] = 'localhost'18121752 @app.route('/')1753 def normal_index():1754 return 'normal index'17551756 @app.route('/', subdomain='test')1757 def test_index():1758 return 'test index'17591821 c = app.test_client()1822 rv = c.get('/', 'http://localhost/')1760 rv = client.get('/', 'http://localhost.localdomain/')1761 assert rv.data == b'normal index'17621825 rv = c.get('/', 'http://test.localhost/')1763 rv = client.get('/', 'http://test.localhost.localdomain/')1764 assert rv.data == b'test index'176517661829def test_subdomain_matching():1830 app = flask.Flask(__name__)1831 app.config['SERVER_NAME'] = 'localhost'1767def test_subdomain_matching(app, client):1768 app.config['SERVER_NAME'] = 'localhost.localdomain'17691770 @app.route('/', subdomain='<user>')1771 def index(user):1772 return 'index for %s' % user17731837 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'177617771842def test_subdomain_matching_with_ports():1843 app = flask.Flask(__name__)1844 app.config['SERVER_NAME'] = 'localhost:3000'1778def test_subdomain_matching_with_ports(app, client):1779 app.config['SERVER_NAME'] = 'localhost.localdomain:3000'17801781 @app.route('/', subdomain='<user>')1782 def index(user):1783 return 'index for %s' % user17841850 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'178717881855def test_multi_route_rules():1856 app = flask.Flask(__name__)18571789def test_multi_route_rules(app, client):1790 @app.route('/')1791 @app.route('/<test>/')1792 def index(test='a'):1793 return test17941863 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'179918001869def test_multi_route_class_views():1801def test_multi_route_class_views(app, client):1802 class View(object):18711803 def __init__(self, app):1804 app.add_url_rule('/', 'index', self.index)1805 app.add_url_rule('/<test>/', 'index', self.index)18061807 def index(self, test='a'):1808 return test18091879 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'181518161887def test_run_defaults(monkeypatch):1817def test_run_defaults(monkeypatch, app):1818 rv = {}18191820 # Mocks werkzeug.serving.run_simple method1821 def run_simple_mock(*args, **kwargs):1822 rv['result'] = 'running...'18231894 app = flask.Flask(__name__)1824 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1825 app.run()1826 assert rv['result'] == 'running...'182718281900def test_run_server_port(monkeypatch):1829def test_run_server_port(monkeypatch, app):1830 rv = {}18311832 # Mocks werkzeug.serving.run_simple method1833 def run_simple_mock(hostname, port, application, *args, **kwargs):1834 rv['result'] = 'running on %s:%s ...' % (hostname, port)18351907 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)184018411842@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))1920def test_run_from_config(monkeypatch, host, port, expect_host, expect_port):1848def 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_port18521853 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 lines
17from werkzeug.http import parse_cache_control_header18from jinja2 import TemplateNotFound192021def test_blueprint_specific_error_handling():21def 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 lines
42 @sideend.route('/what-is-a-sideend')43 def sideend_no():44 flask.abort(403)4546 app = flask.Flask(__name__)46 app.register_blueprint(frontend)47 app.register_blueprint(backend)48 app.register_blueprint(sideend)4950 @app.errorhandler(403)51 def app_forbidden(e):52 return 'application itself says no', 4035355 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'5757 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'5861def test_blueprint_specific_user_error_handling():59def test_blueprint_specific_user_error_handling(app, client):60 class MyDecoratorException(Exception):61 pass6263 class MyFunctionException(Exception):64 pass6566 blue = flask.Blueprint('blue', __name__)
5 unmodified lines
7273 def my_function_exception_handler(e):74 assert isinstance(e, MyFunctionException)75 return 'bam'7677 blue.register_error_handler(MyFunctionException, my_function_exception_handler)7879 @blue.route('/decorator')80 def blue_deco_test():81 raise MyDecoratorException()8283 @blue.route('/function')84 def blue_func_test():85 raise MyFunctionException()8686 app = flask.Flask(__name__)87 app.register_blueprint(blue)8889 c = app.test_client()89 assert client.get('/decorator').data == b'boom'90 assert client.get('/function').data == b'bam'9191 assert c.get('/decorator').data == b'boom'92 assert c.get('/function').data == b'bam'9294def test_blueprint_app_error_handling():93def test_blueprint_app_error_handling(app, client):94 errors = flask.Blueprint('errors', __name__)9596 @errors.app_errorhandler(403)97 def forbidden_handler(e):98 return 'you shall not pass', 40399101 app = flask.Flask(__name__)102100 @app.route('/forbidden')101 def app_forbidden():102 flask.abort(403)103
5 unmodified lines
109110 app.register_blueprint(errors)111 app.register_blueprint(forbidden_bp)112116 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'115118 assert c.get('/forbidden').data == b'you shall not pass'119 assert c.get('/nope').data == b'you shall not pass'116121def test_blueprint_url_definitions():117def test_blueprint_url_definitions(app, client):118 bp = flask.Blueprint('test', __name__)119120 @bp.route('/foo', defaults={'baz': 42})121 def foo(bar, baz):
2 unmodified lines
124 @bp.route('/bar')125 def bar(bar):126 return text_type(bar)127132 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})130136 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'135136142def test_blueprint_url_processors():137def test_blueprint_url_processors(app, client):138 bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')139140 @bp.url_defaults141 def add_language_code(endpoint, values):
10 unmodified lines
152 @bp.route('/about')153 def about():154 return flask.url_for('.index')155161 app = flask.Flask(__name__)156 app.register_blueprint(bp)157164 c = app.test_client()158 assert client.get('/de/').data == b'/de/about'159 assert client.get('/de/about').data == b'/de/'160166 assert c.get('/de/').data == b'/de/about'167 assert c.get('/de/about').data == b'/de/'161162def test_templates_and_static(test_apps):163 from blueprintapp import app171 c = app.test_client()164 client = app.test_client()165173 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()178179 # try/finally, in case other tests use this app for Blueprint tests.
2 unmodified lines
182 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 lines
200201 with flask.Flask(__name__).test_request_context():202 assert flask.render_template('nested/nested.txt') == 'I\'m nested'203204205def test_default_static_cache_timeout():206 app = flask.Flask(__name__)207208 class MyBlueprint(flask.Blueprint):209 def get_send_file_max_age(self, filename):210 return 100211
14 unmodified lines
226 rv.close()227 finally:228 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default229230231def 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']235236240def test_dotted_names():237def test_dotted_names(app, client):238 frontend = flask.Blueprint('myapp.frontend', __name__)239 backend = flask.Blueprint('myapp.backend', __name__)240241 @frontend.route('/fe')
7 unmodified lines
249 @backend.route('/be')250 def backend_index():251 return flask.url_for('myapp.frontend.frontend_index')252256 app = flask.Flask(__name__)253 app.register_blueprint(frontend)254 app.register_blueprint(backend)255260 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'259265def test_dotted_names_from_app():266 app = flask.Flask(__name__)267 app.testing = True260261def test_dotted_names_from_app(app, client):262 test = flask.Blueprint('test', __name__)263264 @app.route('/')265 def app_index():
4 unmodified lines
270 return flask.url_for('app_index')271272 app.register_blueprint(test)273280 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/'276277284def test_empty_url_defaults():278def test_empty_url_defaults(app, client):279 bp = flask.Blueprint('bp', __name__)280281 @bp.route('/', defaults={'page': 1})282 @bp.route('/page/<int:page>')283 def something(page):284 return str(page)285292 app = flask.Flask(__name__)286 app.register_blueprint(bp)287295 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'290299def test_route_decorator_custom_endpoint():291292def test_route_decorator_custom_endpoint(app, client):293 bp = flask.Blueprint('bp', __name__)294295 @bp.route('/foo')296 def foo():
10 unmodified lines
307 @bp.route('/bar/foo')308 def bar_foo():309 return flask.request.endpoint310319 app = flask.Flask(__name__)311 app.register_blueprint(bp, url_prefix='/py')312313 @app.route('/')314 def index():315 return flask.request.endpoint316326 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'322323333def test_route_decorator_custom_endpoint_with_dots():324def test_route_decorator_custom_endpoint_with_dots(app, client):325 bp = flask.Blueprint('bp', __name__)326327 @bp.route('/foo')328 def foo():
32 unmodified lines
361 bp.route('/bar/123', endpoint='bar.123'),362 lambda: None363 )364374 app = flask.Flask(__name__)365 app.register_blueprint(bp, url_prefix='/py')366377 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 == 404373374386def test_endpoint_decorator():375def test_endpoint_decorator(app, client):376 from werkzeug.routing import Rule388 app = flask.Flask(__name__)377 app.url_map.add(Rule('/foo', endpoint='bar'))378379 bp = flask.Blueprint('bp', __name__)380
2 unmodified lines
383 return flask.request.endpoint384385 app.register_blueprint(bp, url_prefix='/bp_prefix')386399 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 == 404389390404def test_template_filter():391def test_template_filter(app):392 bp = flask.Blueprint('bp', __name__)393394 @bp.app_template_filter()395 def my_reverse(s):396 return s[::-1]409 app = flask.Flask(__name__)397398 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'402403415def test_add_template_filter():404def test_add_template_filter(app):405 bp = flask.Blueprint('bp', __name__)406407 def my_reverse(s):408 return s[::-1]409410 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'415416426def test_template_filter_with_name():417def test_template_filter_with_name(app):418 bp = flask.Blueprint('bp', __name__)419420 @bp.app_template_filter('strrev')421 def my_reverse(s):422 return s[::-1]431 app = flask.Flask(__name__)423424 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'428429437def test_add_template_filter_with_name():430def test_add_template_filter_with_name(app):431 bp = flask.Blueprint('bp', __name__)432433 def my_reverse(s):434 return s[::-1]435436 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'441442448def test_template_filter_with_template():443def test_template_filter_with_template(app, client):444 bp = flask.Blueprint('bp', __name__)445446 @bp.app_template_filter()447 def super_reverse(s):448 return s[::-1]453 app = flask.Flask(__name__)449450 app.register_blueprint(bp, url_prefix='/py')451452 @app.route('/')453 def index():454 return flask.render_template('template_filter.html', value='abcd')458 rv = app.test_client().get('/')455456 rv = client.get('/')457 assert rv.data == b'dcba'458461def test_template_filter_after_route_with_template():462 app = flask.Flask(__name__)459460def 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')464465 bp = flask.Blueprint('bp', __name__)466467 @bp.app_template_filter()468 def super_reverse(s):469 return s[::-1]470471 app.register_blueprint(bp, url_prefix='/py')471 rv = app.test_client().get('/')472 rv = client.get('/')473 assert rv.data == b'dcba'474475474def test_add_template_filter_with_template():476def test_add_template_filter_with_template(app, client):477 bp = flask.Blueprint('bp', __name__)478479 def super_reverse(s):480 return s[::-1]481482 bp.add_app_template_filter(super_reverse)479 app = flask.Flask(__name__)483 app.register_blueprint(bp, url_prefix='/py')484485 @app.route('/')486 def index():487 return flask.render_template('template_filter.html', value='abcd')484 rv = app.test_client().get('/')488489 rv = client.get('/')490 assert rv.data == b'dcba'491492487def test_template_filter_with_name_and_template():493def test_template_filter_with_name_and_template(app, client):494 bp = flask.Blueprint('bp', __name__)495496 @bp.app_template_filter('super_reverse')497 def my_reverse(s):498 return s[::-1]492 app = flask.Flask(__name__)499500 app.register_blueprint(bp, url_prefix='/py')501502 @app.route('/')503 def index():504 return flask.render_template('template_filter.html', value='abcd')497 rv = app.test_client().get('/')505506 rv = client.get('/')507 assert rv.data == b'dcba'508509500def test_add_template_filter_with_name_and_template():510def test_add_template_filter_with_name_and_template(app, client):511 bp = flask.Blueprint('bp', __name__)512513 def my_reverse(s):514 return s[::-1]515516 bp.add_app_template_filter(my_reverse, 'super_reverse')505 app = flask.Flask(__name__)517 app.register_blueprint(bp, url_prefix='/py')518519 @app.route('/')520 def index():521 return flask.render_template('template_filter.html', value='abcd')510 rv = app.test_client().get('/')522523 rv = client.get('/')524 assert rv.data == b'dcba'525526513def test_template_test():527def test_template_test(app):528 bp = flask.Blueprint('bp', __name__)529530 @bp.app_template_test()531 def is_boolean(value):532 return isinstance(value, bool)518 app = flask.Flask(__name__)533534 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)538539524def test_add_template_test():540def test_add_template_test(app):541 bp = flask.Blueprint('bp', __name__)542543 def is_boolean(value):544 return isinstance(value, bool)545546 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)551552535def test_template_test_with_name():553def test_template_test_with_name(app):554 bp = flask.Blueprint('bp', __name__)555556 @bp.app_template_test('boolean')557 def is_boolean(value):558 return isinstance(value, bool)540 app = flask.Flask(__name__)559560 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)564565546def test_add_template_test_with_name():566def test_add_template_test_with_name(app):567 bp = flask.Blueprint('bp', __name__)568569 def is_boolean(value):570 return isinstance(value, bool)571572 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)577578557def test_template_test_with_template():579def test_template_test_with_template(app, client):580 bp = flask.Blueprint('bp', __name__)581582 @bp.app_template_test()583 def boolean(value):584 return isinstance(value, bool)562 app = flask.Flask(__name__)585586 app.register_blueprint(bp, url_prefix='/py')587588 @app.route('/')589 def index():590 return flask.render_template('template_test.html', value=False)567 rv = app.test_client().get('/')591592 rv = client.get('/')593 assert b'Success!' in rv.data594570def test_template_test_after_route_with_template():571 app = flask.Flask(__name__)595596def 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)600601 bp = flask.Blueprint('bp', __name__)602603 @bp.app_template_test()604 def boolean(value):605 return isinstance(value, bool)606607 app.register_blueprint(bp, url_prefix='/py')580 rv = app.test_client().get('/')608 rv = client.get('/')609 assert b'Success!' in rv.data610611583def test_add_template_test_with_template():612def test_add_template_test_with_template(app, client):613 bp = flask.Blueprint('bp', __name__)614615 def boolean(value):616 return isinstance(value, bool)617618 bp.add_app_template_test(boolean)588 app = flask.Flask(__name__)619 app.register_blueprint(bp, url_prefix='/py')620621 @app.route('/')622 def index():623 return flask.render_template('template_test.html', value=False)593 rv = app.test_client().get('/')624625 rv = client.get('/')626 assert b'Success!' in rv.data627628596def test_template_test_with_name_and_template():629def test_template_test_with_name_and_template(app, client):630 bp = flask.Blueprint('bp', __name__)631632 @bp.app_template_test('boolean')633 def is_boolean(value):634 return isinstance(value, bool)601 app = flask.Flask(__name__)635636 app.register_blueprint(bp, url_prefix='/py')637638 @app.route('/')639 def index():640 return flask.render_template('template_test.html', value=False)606 rv = app.test_client().get('/')641642 rv = client.get('/')643 assert b'Success!' in rv.data644645609def test_add_template_test_with_name_and_template():646def test_add_template_test_with_name_and_template(app, client):647 bp = flask.Blueprint('bp', __name__)648649 def is_boolean(value):650 return isinstance(value, bool)651652 bp.add_app_template_test(is_boolean, 'boolean')614 app = flask.Flask(__name__)653 app.register_blueprint(bp, url_prefix='/py')654655 @app.route('/')656 def index():657 return flask.render_template('template_test.html', value=False)619 rv = app.test_client().get('/')658659 rv = client.get('/')660 assert b'Success!' in rv.data661662663def test_context_processing():664 app = flask.Flask(__name__)665 answer_bp = flask.Blueprint('answer_bp', __name__)666
34 unmodified lines
701702 assert b'42' in answer_page_bytes703 assert b'43' in answer_page_bytes704705706def test_template_global():707 app = flask.Flask(__name__)708 bp = flask.Blueprint('bp', __name__)709710 @bp.app_template_global()711 def get_answer():712 return 42713714 # 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 lines
modified:tests/test_deprecations.py+4 added-9 removed
13 unmodified lines
14import flask151617class TestRequestDeprecation(object):1819 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 = True2122 @app.route('/', methods=['POST'])23 def index():24 assert flask.request.json == {'spam': 42}25 print(flask.request.json)26 return 'OK'2730 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)3034 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 = True3435 @app.route('/')36 def index():37 assert flask.request.module is None38 return 'OK'3944 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 lines
34 return False353637class TestJSON(object):3839 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)4447 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'] = True4748 @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')5253 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.data5659 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'] = False5960 @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')6465 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.data6871 def test_json_bad_requests(self):72 app = flask.Flask(__name__)69 def test_json_bad_requests(self, app, client):7071 @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')7475 rv = client.post('/json', data='malformed', content_type='application/json')76 assert rv.status_code == 4007780 def test_json_custom_mimetypes(self):81 app = flask.Flask(__name__)78 def test_json_custom_mimetypes(self, app, client):7980 @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')8384 rv = client.post('/json', data='"foo"', content_type='application/x+json')85 assert rv.data == b'foo'8689 def test_json_body_encoding(self):90 app = flask.Flask(__name__)87 def test_json_body_encoding(self, app, client):88 app.testing = True8990 @app.route('/')91 def index():92 return flask.request.get_json()9396 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')97101 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):100104 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 == expected104109 app.config['JSON_AS_ASCII'] = False110 with app.app_context():111 rv = flask.json.dumps(u'\N{SNOWMAN}')112 assert rv == u'"\u2603"'113114 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()108119 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_data113114 @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()117118 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_value123137 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'}}130131 @app.route('/kw')132 def return_kwargs():133 return flask.jsonify(**d)134135 @app.route('/dict')136 def return_dict():137 return flask.jsonify(d)151 c = app.test_client()138139 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) == d143157 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__)151152 @app.route('/args_unpack')153 def return_args_unpack():154 return flask.jsonify(*l)155156 @app.route('/array')157 def return_array():158 return flask.jsonify(l)171 c = app.test_client()159160 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) == l164177 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()171172 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())178193 def test_jsonify_uuid_types(self):179 def test_jsonify_uuid_types(self, app, client):180 """Test jsonify with uuid.UUID types"""181182 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))185201 c = app.test_client()202 rv = c.get(url)186 rv = client.get(url)187188 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_uuid192209 def test_json_attr(self):210 app = flask.Flask(__name__)193 def test_json_attr(self, app, client):194195 @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')199200 rv = client.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),201 content_type='application/json')202 assert rv.data == b'3'203220 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>'222241 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 = val227228 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)233234 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)238239 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__)243244 app.testing = True245 app.json_encoder = MyEncoder246 app.json_decoder = MyDecoder247248 @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({251252 rv = client.post('/', data=flask.json.dumps({253 'x': {'_foo': 42}254 }), content_type='application/json')255 assert rv.data == b'"<42>"'256271 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 lines
284 @bp.route('/bp', methods=['POST'])285 def index():286 return flask.json.dumps(flask.request.get_json()['x'])287302 app = flask.Flask(__name__)288 app.testing = True289 app.register_blueprint(bp)290306 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>"'295312 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__)299300 app.testing = True301 app.request_class = ModifiedRequest302 app.url_map.charset = 'euc-kr'303
7 unmodified lines
311312 if not has_encoding('euc-kr'):313 test_modified_url_encoding = None314331 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 = True318319 assert app.config['JSON_SORT_KEYS'] == True
2 unmodified lines
322 @app.route('/')323 def index():324 return flask.jsonify(values=d)325343 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 lines
382 assert lines == sorted_by_int383 except AssertionError:384 assert lines == sorted_by_str385386387class 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()396406 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()416417 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()406429 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)409410 @app.route('/')411 def index():412 return flask.send_file(StringIO("party like it's"),413 last_modified=last_modified,414 mimetype='text/plain')415439 c = app.test_client()440 rv = c.get('/')416 rv = client.get('/')417 assert rv.last_modified == last_modified418443 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)424446 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)426452 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()435455 def test_send_file_object(self):456 app = flask.Flask(__name__)457458 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()466436 app.use_x_sendfile = True437469 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()443444 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()451485 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)455498 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)458459 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()466467 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()473474 app.use_x_sendfile = True475507 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()480481 @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__)519485 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)489524 c = app.test_client()525526 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()495532 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()501538 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()507544 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()513550 rv = c.get('/', headers={'Range': 'bytes=1000-'})514 rv = client.get('/', headers={'Range': 'bytes=1000-'})515 assert rv.status_code == 416516 rv.close()517554 rv = c.get('/', headers={'Range': 'bytes=-'})518 rv = client.get('/', headers={'Range': 'bytes=-'})519 assert rv.status_code == 416520 rv.close()521558 rv = c.get('/', headers={'Range': 'somethingsomething'})522 rv = client.get('/', headers={'Range': 'somethingsomething'})523 assert rv.status_code == 416524 rv.close()525526 last_modified = datetime.datetime.utcfromtimestamp(os.path.getmtime(527 os.path.join(app.root_path, 'static/index.html'))).replace(528 microsecond=0)529566 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()534571 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()539576 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()542589 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()552596 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()558606 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()567609 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()577619 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()580581 # 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()592593 # 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()603604 class StaticFileApp(flask.Flask):605 def get_send_file_max_age(self, filename):606 return 10607608 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 lines
617 cc = parse_cache_control_header(rv.headers['Cache-Control'])618 assert cc.max_age == 10619 rv.close()620661 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()629672 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')634681class TestLogging(object):635 with pytest.raises(BadRequest):636 flask.send_from_directory('static', 'bad\x00')637638639class TestLogging(object):640 def test_logger_cache(self):641 app = flask.Flask(__name__)642 logger1 = app.logger643 assert app.logger is logger1
25 unmodified lines
669670 with pytest.raises(ZeroDivisionError):671 c.get('/exc')672716 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 == 10678723 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 = False685686 @app.route('/')687 def index():688 1 // 0
7 unmodified lines
696 assert 'Traceback (most recent call last):' in err697 assert '1 // 0' in err698 assert 'ZeroDivisionError:' in err699744 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 = False703704 @app.before_request705 def before_request():706 if trigger == 'before':707 1 // 0708709 @app.after_request710 def after_request(response):711 if trigger == 'after':712 1 // 0713 return response714715 @app.route('/')716 def index():717 return 'Foo'718719 @app.errorhandler(500)720 def internal_server_error(e):721 return 'Hello Server Error', 500722723 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'727767 def test_url_for_with_anchor(self):768 app = flask.Flask(__name__)728 def test_url_for_with_anchor(self, app, req_ctx):729730 @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'733775 def test_url_for_with_scheme(self):776 app = flask.Flask(__name__)734 assert flask.url_for('index', _anchor='x y') == '/#x%20y'735736 def test_url_for_with_scheme(self, app, req_ctx):737738 @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/'741783 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/'743744 def test_url_for_with_scheme_not_external(self, app, req_ctx):745746 @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')749794 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')754755 def test_url_for_with_alternating_schemes(self, app, req_ctx):756757 @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/'760761 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/'764804 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__)767768 class MyView(MethodView):769 def get(self, id=None):770 if id is None:771 return 'List'772 return 'Get %d' % id773774 def post(self):775 return 'Create'776777 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)784822 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'788789790class TestNoImports(object):791 """Test Flasks are created without import.
14 unmodified lines
806 assert False, 'Flask(import_name) is importing import_name.'807808809class TestStreaming(object):848849 def test_streaming_with_context(self):810 def test_streaming_with_context(self, app, client):850 app = flask.Flask(__name__)811 app.testing = True812813 @app.route('/')814 def index():815 def generate():816 yield 'Hello '817 yield flask.request.args['name']818 yield '!'819820 return flask.Response(flask.stream_with_context(generate()))859 c = app.test_client()860 rv = c.get('/?name=World')821822 rv = client.get('/?name=World')823 assert rv.data == b'Hello World!'824863 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 = True827828 @app.route('/')829 def index():830 @flask.stream_with_context831 def generate(hello):832 yield hello833 yield flask.request.args['name']834 yield '!'835836 return flask.Response(generate('Hello '))874 c = app.test_client()875 rv = c.get('/?name=World')837838 rv = client.get('/?name=World')839 assert rv.data == b'Hello World!'840878 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 = []844845 class Wrapper(object):846 def __init__(self, gen):847 self._gen = gen848849 def __iter__(self):850 return self851852 def close(self):853 called.append(42)854855 def __next__(self):856 return next(self._gen)857858 next = __next__859860 @app.route('/')861 def index():862 def generate():863 yield 'Hello '864 yield flask.request.args['name']865 yield '!'866867 return flask.Response(flask.stream_with_context(868 Wrapper(generate())))900 c = app.test_client()901 rv = c.get('/?name=World')869870 rv = client.get('/?name=World')871 assert rv.data == b'Hello World!'872 assert called == [42]873874
13 unmodified lines
888 (('/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 )894895 for args, expected in passing:896 assert flask.safe_join(*args) == expected
46 unmodified lines
modified:tests/test_regression.py+3 added-4 removed
7 unmodified lines
8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314import os12import gc13import sys17import flask14import threading1516import pytest17from werkzeug.exceptions import NotFound1819import flask2021_gc_lock = threading.Lock()2223
78 unmodified lines
modified:tests/test_reqctx.py+29 added-22 removed
18 unmodified lines
19except ImportError:20 greenlet = None212223def test_teardown_on_pop():23def test_teardown_on_pop(app):24 buffer = []25 app = flask.Flask(__name__)2526 @app.teardown_request27 def end_of_request(exception):28 buffer.append(exception)29
2 unmodified lines
32 assert buffer == []33 ctx.pop()34 assert buffer == [None]353636def test_teardown_with_previous_exception():37def test_teardown_with_previous_exception(app):38 buffer = []38 app = flask.Flask(__name__)3940 @app.teardown_request41 def end_of_request(exception):42 buffer.append(exception)43
5 unmodified lines
49 with app.test_request_context():50 assert buffer == []51 assert buffer == [None]525352def test_teardown_with_handled_exception():54def test_teardown_with_handled_exception(app):55 buffer = []54 app = flask.Flask(__name__)5657 @app.teardown_request58 def end_of_request(exception):59 buffer.append(exception)60
4 unmodified lines
65 except Exception:66 pass67 assert buffer == [None]6867def test_proper_test_request_context():68 app = flask.Flask(__name__)6970def test_proper_test_request_context(app):71 app.config.update(72 SERVER_NAME='localhost.localdomain:5000'73 )74
6 unmodified lines
81 return None8283 with app.test_request_context('/'):84 assert flask.url_for('index', _external=True) == \83 'http://localhost.localdomain:5000/'85 'http://localhost.localdomain:5000/'8687 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/'9091 try:92 with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}):93 pass
11 unmodified lines
105 app.config.update(SERVER_NAME='localhost:80')106 with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}):107 pass108107def test_context_binding():108 app = flask.Flask(__name__)109110def test_context_binding(app):111 @app.route('/')112 def index():113 return 'Hello %s!' % flask.request.args['name']114115 @app.route('/meh')116 def meh():117 return flask.request.url118
2 unmodified lines
121 with app.test_request_context('/meh'):122 assert meh() == 'http://localhost/meh'123 assert flask._request_ctx_stack.top is None124122def test_context_test():123 app = flask.Flask(__name__)125126def 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 lines
133 assert flask.has_request_context()134 finally:135 ctx.pop()136134def test_manual_context_binding():135 app = flask.Flask(__name__)137138def test_manual_context_binding(app):139 @app.route('/')140 def index():141 return 'Hello %s!' % flask.request.args['name']142
3 unmodified lines
146 ctx.pop()147 with pytest.raises(RuntimeError):148 index()149150151@pytest.mark.skipif(greenlet is None, reason='greenlet not installed')148def test_greenlet_context_copying():149 app = flask.Flask(__name__)152def test_greenlet_context_copying(app, client):153 greenlets = []154155 @app.route('/')156 def index():157 reqctx = flask._request_ctx_stack.top.copy()158159 def g():160 assert not flask.request161 assert not flask.current_app162 with reqctx:
2 unmodified lines
165 assert flask.request.path == '/'166 assert flask.request.args['foo'] == 'bar'167 assert not flask.request168 return 42169170 greenlets.append(greenlet(g))171 return 'Hello World!'172168 rv = app.test_client().get('/?foo=bar')173 rv = client.get('/?foo=bar')174 assert rv.data == b'Hello World!'175176 result = greenlets[0].run()177 assert result == 42178179180@pytest.mark.skipif(greenlet is None, reason='greenlet not installed')175def test_greenlet_context_copying_api():176 app = flask.Flask(__name__)181def test_greenlet_context_copying_api(app, client):182 greenlets = []183184 @app.route('/')185 def index():186 reqctx = flask._request_ctx_stack.top.copy()187188 @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 42195196 greenlets.append(greenlet(g))197 return 'Hello World!'198192 rv = app.test_client().get('/?foo=bar')199 rv = client.get('/?foo=bar')200 assert rv.data == b'Hello World!'201202 result = greenlets[0].run()203 assert result == 42
24 unmodified lines
modified:tests/test_templating.py+126 added-84 removed
14 unmodified lines
15import logging16from jinja2 import TemplateNotFound171819def test_context_processing():20 app = flask.Flask(__name__)19def test_context_processing(app):20 @app.context_processor21 def context_processor():22 return {'injected_value': 42}2324 @app.route('/')25 def index():26 return flask.render_template('context_template.html', value=23)2728 rv = app.test_client().get('/')29 assert rv.data == b'<p>23|42'3030def test_original_win():31 app = flask.Flask(__name__)3132def 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('/')3637 rv = client.get('/')38 assert rv.data == b'42'3938def test_request_less_rendering():39 app = flask.Flask(__name__)4041def test_request_less_rendering(app, app_ctx):42 app.config['WORLD_NAME'] = 'Special World'4344 @app.context_processor45 def context_processor():46 return dict(foo=42)4745 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'5150def test_standard_context():51 app = flask.Flask(__name__)5253def test_standard_context(app, client):54 app.secret_key = 'development key'5556 @app.route('/')57 def index():58 flask.g.foo = 2359 flask.session['test'] = 'aha'
2 unmodified lines
62 {{ g.foo }}63 {{ config.DEBUG }}64 {{ session.test }}65 ''')6663 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']697066def test_escaping():71def test_escaping(app, client):72 text = '<p>Hello World!'68 app = flask.Flask(__name__)7374 @app.route('/')75 def index():76 return flask.render_template('escaping_template.html', text=text,77 html=flask.Markup(text))7873 lines = app.test_client().get('/').data.splitlines()79 lines = client.get('/').data.splitlines()80 assert lines == [81 b'&lt;p&gt;Hello World!',82 b'<p>Hello World!',83 b'<p>Hello World!',
1 unmodified line
85 b'&lt;p&gt;Hello World!',86 b'<p>Hello World!'87 ]888983def test_no_escaping():90def test_no_escaping(app, client):91 text = '<p>Hello World!'85 app = flask.Flask(__name__)9293 @app.route('/')94 def index():95 return flask.render_template('non_escaping_template.txt', text=text,96 html=flask.Markup(text))9790 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 lines
106 b'<p>Hello World!',107 b'<p>Hello World!'108 ]109102def 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>') == '&lt;test&gt;'107 assert flask.render_template('mail.txt', foo='<test>') == \108 '<test> Mail'110110def 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!'111def test_escaping_without_template_filename(app, client, req_ctx):112 assert flask.render_template_string(113 '{{ foo }}', foo='<test>') == '&lt;test&gt;'114 assert flask.render_template('mail.txt', foo='<test>') == '<test> Mail'115116def test_template_filter():117 app = flask.Flask(__name__)116117def test_macros(app, req_ctx):118 macro = flask.get_template_attribute('_macro.html', 'hello')119 assert macro('World') == 'Hello World!'120121122def test_template_filter(app):123 @app.template_filter()124 def my_reverse(s):125 return s[::-1]126127 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'130125def test_add_template_filter():126 app = flask.Flask(__name__)131132def test_add_template_filter(app):133 def my_reverse(s):134 return s[::-1]135136 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'140134def test_template_filter_with_name():135 app = flask.Flask(__name__)141142def test_template_filter_with_name(app):143 @app.template_filter('strrev')144 def my_reverse(s):145 return s[::-1]146147 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'150143def test_add_template_filter_with_name():144 app = flask.Flask(__name__)151152def test_add_template_filter_with_name(app):153 def my_reverse(s):154 return s[::-1]155156 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'160152def test_template_filter_with_template():153 app = flask.Flask(__name__)161162def test_template_filter_with_template(app, client):163 @app.template_filter()164 def super_reverse(s):165 return s[::-1]166167 @app.route('/')168 def index():169 return flask.render_template('template_filter.html', value='abcd')160 rv = app.test_client().get('/')170171 rv = client.get('/')172 assert rv.data == b'dcba'173163def test_add_template_filter_with_template():164 app = flask.Flask(__name__)174175def test_add_template_filter_with_template(app, client):176 def super_reverse(s):177 return s[::-1]178179 app.add_template_filter(super_reverse)180181 @app.route('/')182 def index():183 return flask.render_template('template_filter.html', value='abcd')171 rv = app.test_client().get('/')184185 rv = client.get('/')186 assert rv.data == b'dcba'187174def test_template_filter_with_name_and_template():175 app = flask.Flask(__name__)188189def test_template_filter_with_name_and_template(app, client):190 @app.template_filter('super_reverse')191 def my_reverse(s):192 return s[::-1]193194 @app.route('/')195 def index():196 return flask.render_template('template_filter.html', value='abcd')182 rv = app.test_client().get('/')197198 rv = client.get('/')199 assert rv.data == b'dcba'200185def test_add_template_filter_with_name_and_template():186 app = flask.Flask(__name__)201202def test_add_template_filter_with_name_and_template(app, client):203 def my_reverse(s):204 return s[::-1]205206 app.add_template_filter(my_reverse, 'super_reverse')207208 @app.route('/')209 def index():210 return flask.render_template('template_filter.html', value='abcd')193 rv = app.test_client().get('/')211212 rv = client.get('/')213 assert rv.data == b'dcba'214196def test_template_test():197 app = flask.Flask(__name__)215216def test_template_test(app):217 @app.template_test()218 def boolean(value):219 return isinstance(value, bool)220221 assert 'boolean' in app.jinja_env.tests.keys()222 assert app.jinja_env.tests['boolean'] == boolean223 assert app.jinja_env.tests['boolean'](False)224205def test_add_template_test():206 app = flask.Flask(__name__)225226def test_add_template_test(app):227 def boolean(value):228 return isinstance(value, bool)229230 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)234214def test_template_test_with_name():215 app = flask.Flask(__name__)235236def test_template_test_with_name(app):237 @app.template_test('boolean')238 def is_boolean(value):239 return isinstance(value, bool)240241 assert 'boolean' in app.jinja_env.tests.keys()242 assert app.jinja_env.tests['boolean'] == is_boolean243 assert app.jinja_env.tests['boolean'](False)244223def test_add_template_test_with_name():224 app = flask.Flask(__name__)245246def test_add_template_test_with_name(app):247 def is_boolean(value):248 return isinstance(value, bool)249250 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)254232def test_template_test_with_template():233 app = flask.Flask(__name__)255256def test_template_test_with_template(app):257 @app.template_test()258 def boolean(value):259 return isinstance(value, bool)260261 @app.route('/')262 def index():263 return flask.render_template('template_test.html', value=False)264265 rv = app.test_client().get('/')266 assert b'Success!' in rv.data267243def test_add_template_test_with_template():244 app = flask.Flask(__name__)268269def test_add_template_test_with_template(app, client):270 def boolean(value):271 return isinstance(value, bool)272273 app.add_template_test(boolean)274275 @app.route('/')276 def index():277 return flask.render_template('template_test.html', value=False)251 rv = app.test_client().get('/')278279 rv = client.get('/')280 assert b'Success!' in rv.data281254def test_template_test_with_name_and_template():255 app = flask.Flask(__name__)282283def test_template_test_with_name_and_template(app, client):284 @app.template_test('boolean')285 def is_boolean(value):286 return isinstance(value, bool)287288 @app.route('/')289 def index():290 return flask.render_template('template_test.html', value=False)262 rv = app.test_client().get('/')291292 rv = client.get('/')293 assert b'Success!' in rv.data294265def test_add_template_test_with_name_and_template():266 app = flask.Flask(__name__)295296def test_add_template_test_with_name_and_template(app, client):297 def is_boolean(value):298 return isinstance(value, bool)299300 app.add_template_test(is_boolean, 'boolean')301302 @app.route('/')303 def index():304 return flask.render_template('template_test.html', value=False)273 rv = app.test_client().get('/')305306 rv = client.get('/')307 assert b'Success!' in rv.data308276def test_add_template_global():277 app = flask.Flask(__name__)309310def test_add_template_global(app, app_ctx):311 @app.template_global()312 def get_stuff():313 return 42314315 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'318319 rv = flask.render_template_string('{{ get_stuff() }}')320 assert rv == '42'321322288def test_custom_template_loader():323def 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!'})328329 app = MyFlask(__name__)330331 @app.route('/')332 def index():333 return flask.render_template('index.html')334335 c = app.test_client()336 rv = c.get('/')337 assert rv.data == b'Hello Custom World!'338301def test_iterable_loader():302 app = flask.Flask(__name__)339340def test_iterable_loader(app, client):341 @app.context_processor342 def context_processor():343 return {'whiskey': 'Jameson'}344345 @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)352314 rv = app.test_client().get('/')353 rv = client.get('/')354 assert rv.data == b'<h1>Jameson</h1>'355356317def test_templates_auto_reload():357def 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 False
21 unmodified lines
384 app.config['DEBUG'] = True385 app.config['TEMPLATES_AUTO_RELOAD'] = True386 assert app.jinja_env.auto_reload is True387388389def test_template_loader_debugging(test_apps):390 from blueprintapp import app391392 called = []393394 class _TestHandler(logging.Handler):395 def handle(x, record):396 called.append(True)397 text = str(record.msg)
23 unmodified lines
421 app.config['EXPLAIN_TEMPLATE_LOADING'] = old_load_setting422423 assert len(called) == 1424425426def test_custom_jinja_env():427 class CustomEnvironment(flask.templating.Environment):428 pass429
5 unmodified lines
modified:tests/test_testing.py+49 added-47 removed
14 unmodified lines
1516from flask._compat import text_type171819def test_environ_defaults_from_config():20 app = flask.Flask(__name__)21 app.testing = True19def test_environ_defaults_from_config(app, client):20 app.config['SERVER_NAME'] = 'example.com:1234'21 app.config['APPLICATION_ROOT'] = '/foo'2223 @app.route('/')24 def index():25 return flask.request.url2627 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/'2934def 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/'323334def test_environ_defaults(app, client, app_ctx, req_ctx):35 @app.route('/')36 def index():37 return flask.request.url38
2 unmodified lines
41 with app.test_client() as c:42 rv = c.get('/')43 assert rv.data == b'http://localhost/'4447def test_environ_base_default():48 app = flask.Flask(__name__)4546def test_environ_base_default(app, client, app_ctx):47 app.testing = True4849 @app.route('/')50 def index():51 flask.g.user_agent = flask.request.headers["User-Agent"]52 return flask.request.remote_addr5355 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__5760def test_environ_base_modified():61 app = flask.Flask(__name__)62 app.testing = True5859def 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_addr6468 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'7075 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'7681def test_redirect_keep_session():82 app = flask.Flask(__name__)7778def test_redirect_keep_session(app, client, app_ctx):79 app.secret_key = 'testing'8081 @app.route('/', methods=['GET', 'POST'])82 def index():
5 unmodified lines
88 @app.route('/getsession')89 def get_session():90 return flask.session.get('data', '<missing>')9196 with app.test_client() as c:92 with client as c:93 rv = c.get('/getsession')94 assert rv.data == b'<missing>'9596 rv = c.get('/')
8 unmodified lines
105106 rv = c.get('/getsession')107 assert rv.data == b'foo'108113def test_session_transactions():114 app = flask.Flask(__name__)115 app.testing = True109110def test_session_transactions(app):111 app.secret_key = 'testing'112113 @app.route('/')114 def index():
9 unmodified lines
124 with c.session_transaction() as sess:125 assert len(sess) == 1126 assert sess['foo'] == [42]127128129def test_session_transactions_no_null_sessions():130 app = flask.Flask(__name__)131 app.testing = True132
2 unmodified lines
135 with c.session_transaction() as sess:136 pass137 assert 'Session backend did not open a session' in str(e.value)138143def test_session_transactions_keep_context():144 app = flask.Flask(__name__)145 app.testing = True139140def test_session_transactions_keep_context(app, client, req_ctx):141 app.secret_key = 'testing'142148 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()148155def test_session_transaction_needs_cookies():156 app = flask.Flask(__name__)157 app.testing = True149def 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)155156157def test_test_client_context_binding():158 app = flask.Flask(__name__)159 app.config['LOGGER_HANDLER_POLICY'] = 'never'160161 @app.route('/')162 def index():163 flask.g.value = 42164 return 'Hello World!'
20 unmodified lines
185 pass186 else:187 raise AssertionError('some kind of exception expected')188189190def test_reuse_client():191 app = flask.Flask(__name__)192 c = app.test_client()193
2 unmodified lines
196197 with c:198 assert c.get('/').status_code == 404199200201def test_test_client_calls_teardown_handlers():202 app = flask.Flask(__name__)203 called = []204205 @app.teardown_request206 def remember(error):207 called.append(error)208
11 unmodified lines
220 c.get('/')221 assert called == [None]222 assert called == [None, None]223224225def test_full_url_request():226 app = flask.Flask(__name__)227 app.testing = True228
6 unmodified lines
235 assert rv.status_code == 200236 assert 'gin' in flask.request.form237 assert 'vodka' in flask.request.args238239240def test_subdomain():241 app = flask.Flask(__name__)242 app.config['SERVER_NAME'] = 'example.com'243244 @app.route('/', subdomain='<company_id>')245 def view(company_id):246 return company_id247
5 unmodified lines
253254 assert 200 == response.status_code255 assert b'xxx' == response.data256257258def test_nosubdomain():259 app = flask.Flask(__name__)260 app.config['SERVER_NAME'] = 'example.com'261262 @app.route('/<company_id>')263 def view(company_id):264 return company_id265
8 unmodified lines
modified:tests/test_user_error_handler.py+7 added-15 removed
6 unmodified lines
7 )8import flask91011def test_error_handler_no_match():12 app = flask.Flask(__name__)11def test_error_handler_no_match(app, client):1213 class CustomException(Exception):14 pass15
13 unmodified lines
29 @app.route('/keyerror')30 def key_error():31 raise KeyError()3234 c = app.test_client()33 app.testing = False34 assert client.get('/custom').data == b'custom'35 assert client.get('/keyerror').data == b'KeyError'3636 assert c.get('/custom').data == b'custom'37 assert c.get('/keyerror').data == b'KeyError'373940def test_error_handler_subclass():38def test_error_handler_subclass(app):41 app = flask.Flask(__name__)4239 class ParentException(Exception):40 pass4142 class ChildExceptionUnregistered(ParentException):
30 unmodified lines
73 assert c.get('/child-unregistered').data == b'parent'74 assert c.get('/child-registered').data == b'child-registered'757681def test_error_handler_http_subclass():82 app = flask.Flask(__name__)8377def test_error_handler_http_subclass(app):78 class ForbiddenSubclassRegistered(Forbidden):79 pass8081 class ForbiddenSubclassUnregistered(Forbidden):
27 unmodified lines
109 assert c.get('/forbidden-unregistered').data == b'forbidden'110 assert c.get('/forbidden-registered').data == b'forbidden-registered'111112119def test_error_handler_blueprint():113def test_error_handler_blueprint(app):114 bp = flask.Blueprint('bp', __name__)115116 @bp.errorhandler(500)117 def bp_exception_handler(e):
2 unmodified lines
120 @bp.route('/error')121 def bp_test():122 raise InternalServerError()123130 app = flask.Flask(__name__)131124 @app.errorhandler(500)125 def app_exception_handler(e):126 return 'app-error'127
60 unmodified lines
modified:tests/test_views.py+24 added-20 removed
14 unmodified lines
15import flask.views1617from werkzeug.http import parse_set_header181920def common_test(app):21 c = app.test_client()2223 assert c.get('/').data == b'GET'
1 unmodified line
25 assert c.put('/').status_code == 40526 meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])27 assert sorted(meths) == ['GET', 'HEAD', 'OPTIONS', 'POST']2828def test_basic_view():29 app = flask.Flask(__name__)2930def test_basic_view(app):31 class Index(flask.views.View):32 methods = ['GET', 'POST']3334 def dispatch_request(self):35 return flask.request.method3637 app.add_url_rule('/', view_func=Index.as_view('index'))38 common_test(app)3939def test_method_based_view():40 app = flask.Flask(__name__)4041def test_method_based_view(app):42 class Index(flask.views.MethodView):43 def get(self):44 return 'GET'4546 def post(self):47 return 'POST'4849 app.add_url_rule('/', view_func=Index.as_view('index'))5051 common_test(app)5252def test_view_patching():53 app = flask.Flask(__name__)5354def test_view_patching(app):55 class Index(flask.views.MethodView):56 def get(self):57 1 // 05859 def post(self):60 1 // 06162 class Other(Index):63 def get(self):64 return 'GET'6566 def post(self):67 return 'POST'6869 view = Index.as_view('index')70 view.view_class = Other71 app.add_url_rule('/', view_func=view)72 common_test(app)7372def test_view_inheritance():73 app = flask.Flask(__name__)7475def test_view_inheritance(app):76 class Index(flask.views.MethodView):77 def get(self):78 return 'GET'7980 def post(self):81 return 'POST'8283 class BetterIndex(Index):
5 unmodified lines
8990 meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])91 assert sorted(meths) == ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST']9291def test_view_decorators():92 app = flask.Flask(__name__)9394def 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 resp100101 return new_function102103 class Index(flask.views.View):104 decorators = [add_x_parachute]105106 def dispatch_request(self):107 return 'Awesome'108109 app.add_url_rule('/', view_func=Index.as_view('index'))
1 unmodified line
111 rv = c.get('/')112 assert rv.headers['X-Parachute'] == 'awesome'113 assert rv.data == b'Awesome'114115116def test_view_provide_automatic_options_attr():117 app = flask.Flask(__name__)118119 class Index1(flask.views.View):120 provide_automatic_options = False121122 def dispatch_request(self):123 return 'Hello World!'124125 app.add_url_rule('/', view_func=Index1.as_view('index'))
5 unmodified lines
131132 class Index2(flask.views.View):133 methods = ['OPTIONS']134 provide_automatic_options = True135136 def dispatch_request(self):137 return 'Hello World!'138139 app.add_url_rule('/', view_func=Index2.as_view('index'))
11 unmodified lines
151 c = app.test_client()152 rv = c.open('/', method='OPTIONS')153 assert 'OPTIONS' in rv.allow154149def test_implicit_head():150 app = flask.Flask(__name__)155156def 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.method
7 unmodified lines
168 rv = c.head('/')169 assert rv.data == b''170 assert rv.headers['X-Method'] == 'HEAD'171167def test_explicit_head():168 app = flask.Flask(__name__)172173def test_explicit_head(app):174 class Index(flask.views.MethodView):175 def get(self):176 return 'GET'177178 def head(self):179 return flask.Response('', headers={'X-Method': 'HEAD'})180181 app.add_url_rule('/', view_func=Index.as_view('index'))
3 unmodified lines
185 rv = c.head('/')186 assert rv.data == b''187 assert rv.headers['X-Method'] == 'HEAD'188184def test_endpoint_override():185 app = flask.Flask(__name__)189190def test_endpoint_override(app):191 app.debug = True192193 class Index(flask.views.View):194 methods = ['GET', 'POST']195196 def dispatch_request(self):197 return flask.request.method198199 app.add_url_rule('/', view_func=Index.as_view('index'))
3 unmodified lines
203204 # But these tests should still pass. We just log a warning.205 common_test(app)206201def test_multiple_inheritance():202 app = flask.Flask(__name__)207208def test_multiple_inheritance(app):209 class GetView(flask.views.MethodView):210 def get(self):211 return 'GET'212
10 unmodified lines
223 assert c.get('/').data == b'GET'224 assert c.delete('/').data == b'DELETE'225 assert sorted(GetDeleteView.methods) == ['DELETE', 'GET']226222def test_remove_method_from_parent():223 app = flask.Flask(__name__)227228def test_remove_method_from_parent(app):229 class GetView(flask.views.MethodView):230 def get(self):231 return 'GET'232
13 unmodified lines