Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

1,948 lines · 51.8 KiB · Python

Last changed by

standardize license and copyrightDavid Lordbefore adoptione666f7a

History of this file

Take it

The walk stopped after 200 commits: lines older than 8207b15 point at it.

fix formattingDavid Lordbefore adoption8207b15

lines 1–7why, one step back
1# -*- coding: utf-8 -*-
2"""3 tests.basic4 ~~~~~~~~~~~~~~~~~~~~~56 The basic functionality.7

standardize license and copyrightDavid Lordbefore adoptione666f7a

lines 8–9why, one step back
8 :copyright: 2010 Pallets
9 :license: BSD-3-Clause

fix formattingDavid Lordbefore adoption8207b15

lines 10–223why, one step back
10"""
1112import re13import time14import uuid15from datetime import datetime16from threading import Thread1718import pytest19import werkzeug.serving20from werkzeug.exceptions import BadRequest, Forbidden, NotFound21from werkzeug.http import parse_date22from werkzeug.routing import BuildError2324import flask25from flask._compat import text_type262728def test_options_work(app, client):29 @app.route('/', methods=['GET', 'POST'])30 def index():31 return 'Hello World'3233 rv = client.open('/', method='OPTIONS')34 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']35 assert rv.data == b''363738def 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!'4647 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 == 4056162 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(app, client):74 def index():75 return flask.request.method7677 def more():78 return flask.request.method7980 app.add_url_rule('/', view_func=index, provide_automatic_options=False)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'8687 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 method92 if hasattr(client, 'options'):93 rv = client.options('/')94 else:95 rv = client.open('/', method='OPTIONS')9697 assert rv.status_code == 4059899 rv = client.head('/')100 assert rv.status_code == 200101 assert not rv.data # head truncates102 assert client.post('/more').data == b'POST'103 assert client.get('/more').data == b'GET'104105 rv = client.delete('/more')106 assert rv.status_code == 405107 assert sorted(rv.allow) == ['GET', 'HEAD', 'POST']108109 if hasattr(client, 'options'):110 rv = client.options('/more')111 else:112 rv = client.open('/more', method='OPTIONS')113114 assert rv.status_code == 405115116117def 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.method125126 assert client.get('/').data == b'GET'127 rv = client.post('/')128 assert rv.status_code == 405129 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']130 rv = client.head('/')131 assert rv.status_code == 200132 assert not rv.data # head truncates133 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']138139140def test_disallow_string_for_allowed_methods(app):141 with pytest.raises(TypeError):142 @app.route('/', methods='GET POST')143 def index():144 return "Hey"145146147def test_url_mapping(app, client):148 random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"149150 def index():151 return flask.request.method152153 def more():154 return flask.request.method155156 def options():157 return random_uuid4158159 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'])164165 assert client.get('/').data == b'GET'166 rv = client.post('/')167 assert rv.status_code == 405168 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']169 rv = client.head('/')170 assert rv.status_code == 200171 assert not rv.data # head truncates172 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']177 rv = client.open('/options', method='OPTIONS')178 assert rv.status_code == 200179 assert random_uuid4 in rv.data.decode("utf-8")180181182def test_werkzeug_routing(app, client):183 from werkzeug.routing import Submount, Rule184 app.url_map.add(Submount('/foo', [185 Rule('/bar', endpoint='bar'),186 Rule('/', endpoint='index')187 ]))188189 def bar():190 return 'bar'191192 def index():193 return 'index'194195 app.view_functions['bar'] = bar196 app.view_functions['index'] = index197198 assert client.get('/foo/').data == b'index'199 assert client.get('/foo/bar').data == b'bar'200201202def test_endpoint_decorator(app, client):203 from werkzeug.routing import Submount, Rule204 app.url_map.add(Submount('/foo', [205 Rule('/bar', endpoint='bar'),206 Rule('/', endpoint='index')207 ]))208209 @app.endpoint('bar')210 def bar():211 return 'bar'212213 @app.endpoint('index')214 def index():215 return 'index'216217 assert client.get('/foo/').data == b'index'218 assert client.get('/foo/bar').data == b'bar'219220221def test_session(app, client):222 @app.route('/set', methods=['POST'])223 def set():

Merge pull request #2580 from pallets/session-attrsDavid Lordbefore adoption26f413e

lines 224–225why, one step back
224 assert not flask.session.accessed
225 assert not flask.session.modified

fix formattingDavid Lordbefore adoption8207b15

line 226why, one step back
226 flask.session['value'] = flask.request.form['value']

Merge pull request #2580 from pallets/session-attrsDavid Lordbefore adoption26f413e

lines 227–228why, one step back
227 assert flask.session.accessed
228 assert flask.session.modified

fix formattingDavid Lordbefore adoption8207b15

lines 229–232why, one step back
229 return 'value set'
230231 @app.route('/get')232 def get():

Merge pull request #2580 from pallets/session-attrsDavid Lordbefore adoption26f413e

lines 233–238why, one step back
233 assert not flask.session.accessed
234 assert not flask.session.modified235 v = flask.session.get('value', 'None')236 assert flask.session.accessed237 assert not flask.session.modified238 return v

fix formattingDavid Lordbefore adoption8207b15

lines 239–321why, one step back
239
240 assert client.post('/set', data={'value': '42'}).data == b'value set'241 assert client.get('/get').data == b'42'242243244def test_session_using_server_name(app, client):245 app.config.update(246 SERVER_NAME='example.com'247 )248249 @app.route('/')250 def index():251 flask.session['testing'] = 42252 return 'Hello World'253254 rv = client.get('/', 'http://example.com/')255 assert 'domain=.example.com' in rv.headers['set-cookie'].lower()256 assert 'httponly' in rv.headers['set-cookie'].lower()257258259def test_session_using_server_name_and_port(app, client):260 app.config.update(261 SERVER_NAME='example.com:8080'262 )263264 @app.route('/')265 def index():266 flask.session['testing'] = 42267 return 'Hello World'268269 rv = client.get('/', 'http://example.com:8080/')270 assert 'domain=.example.com' in rv.headers['set-cookie'].lower()271 assert 'httponly' in rv.headers['set-cookie'].lower()272273274def test_session_using_server_name_port_and_path(app, client):275 app.config.update(276 SERVER_NAME='example.com:8080',277 APPLICATION_ROOT='/foo'278 )279280 @app.route('/')281 def index():282 flask.session['testing'] = 42283 return 'Hello World'284285 rv = client.get('/', 'http://example.com:8080/foo')286 assert 'domain=example.com' in rv.headers['set-cookie'].lower()287 assert 'path=/foo' in rv.headers['set-cookie'].lower()288 assert 'httponly' in rv.headers['set-cookie'].lower()289290291def test_session_using_application_root(app, client):292 class PrefixPathMiddleware(object):293 def __init__(self, app, prefix):294 self.app = app295 self.prefix = prefix296297 def __call__(self, environ, start_response):298 environ['SCRIPT_NAME'] = self.prefix299 return self.app(environ, start_response)300301 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar')302 app.config.update(303 APPLICATION_ROOT='/bar'304 )305306 @app.route('/')307 def index():308 flask.session['testing'] = 42309 return 'Hello World'310311 rv = client.get('/', 'http://example.com:8080/')312 assert 'path=/bar' in rv.headers['set-cookie'].lower()313314315def test_session_using_session_settings(app, client):316 app.config.update(317 SERVER_NAME='www.example.com:8080',318 APPLICATION_ROOT='/test',319 SESSION_COOKIE_DOMAIN='.example.com',320 SESSION_COOKIE_HTTPONLY=False,321 SESSION_COOKIE_SECURE=True,

Merge pull request #2607 from FadhelC/SameSite-cookie-featureDavid Lordbefore adoptione21abd9

line 322why, one step back
322 SESSION_COOKIE_SAMESITE='Lax',

fix formattingDavid Lordbefore adoption8207b15

lines 323–336why, one step back
323 SESSION_COOKIE_PATH='/'
324 )325326 @app.route('/')327 def index():328 flask.session['testing'] = 42329 return 'Hello World'330331 rv = client.get('/', 'http://www.example.com:8080/test/')332 cookie = rv.headers['set-cookie'].lower()333 assert 'domain=.example.com' in cookie334 assert 'path=/' in cookie335 assert 'secure' in cookie336 assert 'httponly' not in cookie

Merge pull request #2607 from FadhelC/SameSite-cookie-featureDavid Lordbefore adoptione21abd9

lines 337–364why, one step back
337 assert 'samesite' in cookie
338339340def test_session_using_samesite_attribute(app, client):341 @app.route('/')342 def index():343 flask.session['testing'] = 42344 return 'Hello World'345346 app.config.update(SESSION_COOKIE_SAMESITE='invalid')347348 with pytest.raises(ValueError):349 client.get('/')350351 app.config.update(SESSION_COOKIE_SAMESITE=None)352 rv = client.get('/')353 cookie = rv.headers['set-cookie'].lower()354 assert 'samesite' not in cookie355356 app.config.update(SESSION_COOKIE_SAMESITE='Strict')357 rv = client.get('/')358 cookie = rv.headers['set-cookie'].lower()359 assert 'samesite=strict' in cookie360361 app.config.update(SESSION_COOKIE_SAMESITE='Lax')362 rv = client.get('/')363 cookie = rv.headers['set-cookie'].lower()364 assert 'samesite=lax' in cookie

fix formattingDavid Lordbefore adoption8207b15

lines 365–1029why, one step back
365
366367def test_session_localhost_warning(recwarn, app, client):368 app.config.update(369 SERVER_NAME='localhost:5000',370 )371372 @app.route('/')373 def index():374 flask.session['testing'] = 42375 return 'testing'376377 rv = client.get('/', 'http://localhost:5000/')378 assert 'domain' not in rv.headers['set-cookie'].lower()379 w = recwarn.pop(UserWarning)380 assert '"localhost" is not a valid cookie domain' in str(w.message)381382383def test_session_ip_warning(recwarn, app, client):384 app.config.update(385 SERVER_NAME='127.0.0.1:5000',386 )387388 @app.route('/')389 def index():390 flask.session['testing'] = 42391 return 'testing'392393 rv = client.get('/', 'http://127.0.0.1:5000/')394 assert 'domain=127.0.0.1' in rv.headers['set-cookie'].lower()395 w = recwarn.pop(UserWarning)396 assert 'cookie domain is an IP' in str(w.message)397398399def test_missing_session(app):400 app.secret_key = None401402 def expect_exception(f, *args, **kwargs):403 e = pytest.raises(RuntimeError, f, *args, **kwargs)404 assert e.value.args and 'session is unavailable' in e.value.args[0]405406 with app.test_request_context():407 assert flask.session.get('missing_key') is None408 expect_exception(flask.session.__setitem__, 'foo', 42)409 expect_exception(flask.session.pop, 'foo')410411412def test_session_expiration(app, client):413 permanent = True414415 @app.route('/')416 def index():417 flask.session['test'] = 42418 flask.session.permanent = permanent419 return ''420421 @app.route('/test')422 def test():423 return text_type(flask.session.permanent)424425 rv = client.get('/')426 assert 'set-cookie' in rv.headers427 match = re.search(r'(?i)\bexpires=([^;]+)', rv.headers['set-cookie'])428 expires = parse_date(match.group())429 expected = datetime.utcnow() + app.permanent_session_lifetime430 assert expires.year == expected.year431 assert expires.month == expected.month432 assert expires.day == expected.day433434 rv = client.get('/test')435 assert rv.data == b'True'436437 permanent = False438 rv = client.get('/')439 assert 'set-cookie' in rv.headers440 match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])441 assert match is None442443444def test_session_stored_last(app, client):445 @app.after_request446 def modify_session(response):447 flask.session['foo'] = 42448 return response449450 @app.route('/')451 def dump_session_contents():452 return repr(flask.session.get('foo'))453454 assert client.get('/').data == b'None'455 assert client.get('/').data == b'42'456457458def test_session_special_types(app, client):459 now = datetime.utcnow().replace(microsecond=0)460 the_uuid = uuid.uuid4()461462 @app.route('/')463 def dump_session_contents():464 flask.session['t'] = (1, 2, 3)465 flask.session['b'] = b'\xff'466 flask.session['m'] = flask.Markup('<html>')467 flask.session['u'] = the_uuid468 flask.session['d'] = now469 flask.session['t_tag'] = {' t': 'not-a-tuple'}470 flask.session['di_t_tag'] = {' t__': 'not-a-tuple'}471 flask.session['di_tag'] = {' di': 'not-a-dict'}472 return '', 204473474 with client:475 client.get('/')476 s = flask.session477 assert s['t'] == (1, 2, 3)478 assert type(s['b']) == bytes479 assert s['b'] == b'\xff'480 assert type(s['m']) == flask.Markup481 assert s['m'] == flask.Markup('<html>')482 assert s['u'] == the_uuid483 assert s['d'] == now484 assert s['t_tag'] == {' t': 'not-a-tuple'}485 assert s['di_t_tag'] == {' t__': 'not-a-tuple'}486 assert s['di_tag'] == {' di': 'not-a-dict'}487488489def test_session_cookie_setting(app):490 is_permanent = True491492 @app.route('/bump')493 def bump():494 rv = flask.session['foo'] = flask.session.get('foo', 0) + 1495 flask.session.permanent = is_permanent496 return str(rv)497498 @app.route('/read')499 def read():500 return str(flask.session.get('foo', 0))501502 def run_test(expect_header):503 with app.test_client() as c:504 assert c.get('/bump').data == b'1'505 assert c.get('/bump').data == b'2'506 assert c.get('/bump').data == b'3'507508 rv = c.get('/read')509 set_cookie = rv.headers.get('set-cookie')510 assert (set_cookie is not None) == expect_header511 assert rv.data == b'3'512513 is_permanent = True514 app.config['SESSION_REFRESH_EACH_REQUEST'] = True515 run_test(expect_header=True)516517 is_permanent = True518 app.config['SESSION_REFRESH_EACH_REQUEST'] = False519 run_test(expect_header=False)520521 is_permanent = False522 app.config['SESSION_REFRESH_EACH_REQUEST'] = True523 run_test(expect_header=False)524525 is_permanent = False526 app.config['SESSION_REFRESH_EACH_REQUEST'] = False527 run_test(expect_header=False)528529530def test_session_vary_cookie(app, client):531 @app.route('/set')532 def set_session():533 flask.session['test'] = 'test'534 return ''535536 @app.route('/get')537 def get():538 return flask.session.get('test')539540 @app.route('/getitem')541 def getitem():542 return flask.session['test']543544 @app.route('/setdefault')545 def setdefault():546 return flask.session.setdefault('test', 'default')547548 @app.route('/vary-cookie-header-set')549 def vary_cookie_header_set():550 response = flask.Response()551 response.vary.add('Cookie')552 flask.session['test'] = 'test'553 return response554555 @app.route('/vary-header-set')556 def vary_header_set():557 response = flask.Response()558 response.vary.update(('Accept-Encoding', 'Accept-Language'))559 flask.session['test'] = 'test'560 return response561562 @app.route('/no-vary-header')563 def no_vary_header():564 return ''565566 def expect(path, header_value='Cookie'):567 rv = client.get(path)568569 if header_value:570 # The 'Vary' key should exist in the headers only once.571 assert len(rv.headers.get_all('Vary')) == 1572 assert rv.headers['Vary'] == header_value573 else:574 assert 'Vary' not in rv.headers575576 expect('/set')577 expect('/get')578 expect('/getitem')579 expect('/setdefault')580 expect('/vary-cookie-header-set')581 expect('/vary-header-set', 'Accept-Encoding, Accept-Language, Cookie')582 expect('/no-vary-header', None)583584585def test_flashes(app, req_ctx):586 assert not flask.session.modified587 flask.flash('Zap')588 flask.session.modified = False589 flask.flash('Zip')590 assert flask.session.modified591 assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']592593594def test_extended_flashing(app):595 # Be sure app.testing=True below, else tests can fail silently.596 #597 # Specifically, if app.testing is not set to True, the AssertionErrors598 # in the view functions will cause a 500 response to the test client599 # instead of propagating exceptions.600601 @app.route('/')602 def index():603 flask.flash(u'Hello World')604 flask.flash(u'Hello World', 'error')605 flask.flash(flask.Markup(u'<em>Testing</em>'), 'warning')606 return ''607608 @app.route('/test/')609 def test():610 messages = flask.get_flashed_messages()611 assert list(messages) == [612 u'Hello World',613 u'Hello World',614 flask.Markup(u'<em>Testing</em>')615 ]616 return ''617618 @app.route('/test_with_categories/')619 def test_with_categories():620 messages = flask.get_flashed_messages(with_categories=True)621 assert len(messages) == 3622 assert list(messages) == [623 ('message', u'Hello World'),624 ('error', u'Hello World'),625 ('warning', flask.Markup(u'<em>Testing</em>'))626 ]627 return ''628629 @app.route('/test_filter/')630 def test_filter():631 messages = flask.get_flashed_messages(632 category_filter=['message'], with_categories=True)633 assert list(messages) == [('message', u'Hello World')]634 return ''635636 @app.route('/test_filters/')637 def test_filters():638 messages = flask.get_flashed_messages(639 category_filter=['message', 'warning'], with_categories=True)640 assert list(messages) == [641 ('message', u'Hello World'),642 ('warning', flask.Markup(u'<em>Testing</em>'))643 ]644 return ''645646 @app.route('/test_filters_without_returning_categories/')647 def test_filters2():648 messages = flask.get_flashed_messages(649 category_filter=['message', 'warning'])650 assert len(messages) == 2651 assert messages[0] == u'Hello World'652 assert messages[1] == flask.Markup(u'<em>Testing</em>')653 return ''654655 # Create new test client on each test to clean flashed messages.656657 client = app.test_client()658 client.get('/')659 client.get('/test_with_categories/')660661 client = app.test_client()662 client.get('/')663 client.get('/test_filter/')664665 client = app.test_client()666 client.get('/')667 client.get('/test_filters/')668669 client = app.test_client()670 client.get('/')671 client.get('/test_filters_without_returning_categories/')672673674def test_request_processing(app, client):675 evts = []676677 @app.before_request678 def before_request():679 evts.append('before')680681 @app.after_request682 def after_request(response):683 response.data += b'|after'684 evts.append('after')685 return response686687 @app.route('/')688 def index():689 assert 'before' in evts690 assert 'after' not in evts691 return 'request'692693 assert 'after' not in evts694 rv = client.get('/').data695 assert 'after' in evts696 assert rv == b'request|after'697698699def test_request_preprocessing_early_return(app, client):700 evts = []701702 @app.before_request703 def before_request1():704 evts.append(1)705706 @app.before_request707 def before_request2():708 evts.append(2)709 return "hello"710711 @app.before_request712 def before_request3():713 evts.append(3)714 return "bye"715716 @app.route('/')717 def index():718 evts.append('index')719 return "damnit"720721 rv = client.get('/').data.strip()722 assert rv == b'hello'723 assert evts == [1, 2]724725726def test_after_request_processing(app, client):727 @app.route('/')728 def index():729 @flask.after_this_request730 def foo(response):731 response.headers['X-Foo'] = 'a header'732 return response733734 return 'Test'735736 resp = client.get('/')737 assert resp.status_code == 200738 assert resp.headers['X-Foo'] == 'a header'739740741def test_teardown_request_handler(app, client):742 called = []743744 @app.teardown_request745 def teardown_request(exc):746 called.append(True)747 return "Ignored"748749 @app.route('/')750 def root():751 return "Response"752753 rv = client.get('/')754 assert rv.status_code == 200755 assert b'Response' in rv.data756 assert len(called) == 1757758759def test_teardown_request_handler_debug_mode(app, client):760 called = []761762 @app.teardown_request763 def teardown_request(exc):764 called.append(True)765 return "Ignored"766767 @app.route('/')768 def root():769 return "Response"770771 rv = client.get('/')772 assert rv.status_code == 200773 assert b'Response' in rv.data774 assert len(called) == 1775776777def test_teardown_request_handler_error(app, client):778 called = []779 app.testing = False780781 @app.teardown_request782 def teardown_request1(exc):783 assert type(exc) == ZeroDivisionError784 called.append(True)785 # This raises a new error and blows away sys.exc_info(), so we can786 # test that all teardown_requests get passed the same original787 # exception.788 try:789 raise TypeError()790 except:791 pass792793 @app.teardown_request794 def teardown_request2(exc):795 assert type(exc) == ZeroDivisionError796 called.append(True)797 # This raises a new error and blows away sys.exc_info(), so we can798 # test that all teardown_requests get passed the same original799 # exception.800 try:801 raise TypeError()802 except:803 pass804805 @app.route('/')806 def fails():807 1 // 0808809 rv = client.get('/')810 assert rv.status_code == 500811 assert b'Internal Server Error' in rv.data812 assert len(called) == 2813814815def test_before_after_request_order(app, client):816 called = []817818 @app.before_request819 def before1():820 called.append(1)821822 @app.before_request823 def before2():824 called.append(2)825826 @app.after_request827 def after1(response):828 called.append(4)829 return response830831 @app.after_request832 def after2(response):833 called.append(3)834 return response835836 @app.teardown_request837 def finish1(exc):838 called.append(6)839840 @app.teardown_request841 def finish2(exc):842 called.append(5)843844 @app.route('/')845 def index():846 return '42'847848 rv = client.get('/')849 assert rv.data == b'42'850 assert called == [1, 2, 3, 4, 5, 6]851852853def test_error_handling(app, client):854 app.testing = False855856 @app.errorhandler(404)857 def not_found(e):858 return 'not found', 404859860 @app.errorhandler(500)861 def internal_server_error(e):862 return 'internal server error', 500863864 @app.errorhandler(Forbidden)865 def forbidden(e):866 return 'forbidden', 403867868 @app.route('/')869 def index():870 flask.abort(404)871872 @app.route('/error')873 def error():874 1 // 0875876 @app.route('/forbidden')877 def error2():878 flask.abort(403)879880 rv = client.get('/')881 assert rv.status_code == 404882 assert rv.data == b'not found'883 rv = client.get('/error')884 assert rv.status_code == 500885 assert b'internal server error' == rv.data886 rv = client.get('/forbidden')887 assert rv.status_code == 403888 assert b'forbidden' == rv.data889890891def test_error_handler_unknown_code(app):892 with pytest.raises(KeyError) as exc_info:893 app.register_error_handler(999, lambda e: ('999', 999))894895 assert 'Use a subclass' in exc_info.value.args[0]896897898def test_error_handling_processing(app, client):899 app.testing = False900901 @app.errorhandler(500)902 def internal_server_error(e):903 return 'internal server error', 500904905 @app.route('/')906 def broken_func():907 1 // 0908909 @app.after_request910 def after_request(resp):911 resp.mimetype = 'text/x-special'912 return resp913914 resp = client.get('/')915 assert resp.mimetype == 'text/x-special'916 assert resp.data == b'internal server error'917918919def test_baseexception_error_handling(app, client):920 app.testing = False921922 @app.route('/')923 def broken_func():924 raise KeyboardInterrupt()925926 with pytest.raises(KeyboardInterrupt):927 client.get('/')928929 ctx = flask._request_ctx_stack.top930 assert ctx.preserved931 assert type(ctx._preserved_exc) is KeyboardInterrupt932933934def test_before_request_and_routing_errors(app, client):935 @app.before_request936 def attach_something():937 flask.g.something = 'value'938939 @app.errorhandler(404)940 def return_something(error):941 return flask.g.something, 404942943 rv = client.get('/')944 assert rv.status_code == 404945 assert rv.data == b'value'946947948def test_user_error_handling(app, client):949 class MyException(Exception):950 pass951952 @app.errorhandler(MyException)953 def handle_my_exception(e):954 assert isinstance(e, MyException)955 return '42'956957 @app.route('/')958 def index():959 raise MyException()960961 assert client.get('/').data == b'42'962963964def test_http_error_subclass_handling(app, client):965 class ForbiddenSubclass(Forbidden):966 pass967968 @app.errorhandler(ForbiddenSubclass)969 def handle_forbidden_subclass(e):970 assert isinstance(e, ForbiddenSubclass)971 return 'banana'972973 @app.errorhandler(403)974 def handle_forbidden_subclass(e):975 assert not isinstance(e, ForbiddenSubclass)976 assert isinstance(e, Forbidden)977 return 'apple'978979 @app.route('/1')980 def index1():981 raise ForbiddenSubclass()982983 @app.route('/2')984 def index2():985 flask.abort(403)986987 @app.route('/3')988 def index3():989 raise Forbidden()990991 assert client.get('/1').data == b'banana'992 assert client.get('/2').data == b'apple'993 assert client.get('/3').data == b'apple'994995996def test_errorhandler_precedence(app, client):997 class E1(Exception):998 pass9991000 class E2(Exception):1001 pass10021003 class E3(E1, E2):1004 pass10051006 @app.errorhandler(E2)1007 def handle_e2(e):1008 return 'E2'10091010 @app.errorhandler(Exception)1011 def handle_exception(e):1012 return 'Exception'10131014 @app.route('/E1')1015 def raise_e1():1016 raise E110171018 @app.route('/E3')1019 def raise_e3():1020 raise E310211022 rv = client.get('/E1')1023 assert rv.data == b'Exception'10241025 rv = client.get('/E3')1026 assert rv.data == b'E2'102710281029def test_trapping_of_bad_request_key_errors(app, client):

Merge pull request #2739 from pallets/2735-abort-debugDavid Lordbefore adoption4c8ec8f

line 1030why, one step back
1030 @app.route('/key')

fix formattingDavid Lordbefore adoption8207b15

lines 1031–1033why, one step back
1031 def fail():
1032 flask.request.form['missing_key']1033

Merge pull request #2739 from pallets/2735-abort-debugDavid Lordbefore adoption4c8ec8f

lines 1034–1038why, one step back
1034 @app.route('/abort')
1035 def allow_abort():1036 flask.abort(400)10371038 rv = client.get('/key')

fix formattingDavid Lordbefore adoption8207b15

lines 1039–1040why, one step back
1039 assert rv.status_code == 400
1040 assert b'missing_key' not in rv.data

Merge pull request #2739 from pallets/2735-abort-debugDavid Lordbefore adoption4c8ec8f

lines 1041–1042why, one step back
1041 rv = client.get('/abort')
1042 assert rv.status_code == 400

fix formattingDavid Lordbefore adoption8207b15

line 1043why, one step back
1043

Merge pull request #2739 from pallets/2735-abort-debugDavid Lordbefore adoption4c8ec8f

line 1044why, one step back
1044 app.debug = True

fix formattingDavid Lordbefore adoption8207b15

line 1045why, one step back
1045 with pytest.raises(KeyError) as e:

Merge pull request #2739 from pallets/2735-abort-debugDavid Lordbefore adoption4c8ec8f

line 1046why, one step back
1046 client.get("/key")

fix formattingDavid Lordbefore adoption8207b15

line 1047why, one step back
1047 assert e.errisinstance(BadRequest)

Merge pull request #3063 from pallets/key-errorDavid Lordbefore adoption15c079f

line 1048why, one step back
1048 assert 'missing_key' in e.value.get_description()

Merge pull request #2739 from pallets/2735-abort-debugDavid Lordbefore adoption4c8ec8f

lines 1049–1057why, one step back
1049 rv = client.get('/abort')
1050 assert rv.status_code == 40010511052 app.debug = False1053 app.config['TRAP_BAD_REQUEST_ERRORS'] = True1054 with pytest.raises(KeyError):1055 client.get('/key')1056 with pytest.raises(BadRequest):1057 client.get('/abort')

fix formattingDavid Lordbefore adoption8207b15

lines 1058–1070why, one step back
1058
10591060def test_trapping_of_all_http_exceptions(app, client):1061 app.config['TRAP_HTTP_EXCEPTIONS'] = True10621063 @app.route('/fail')1064 def fail():1065 flask.abort(404)10661067 with pytest.raises(NotFound):1068 client.get('/fail')10691070

Merge pull request #2436 from davidism/loggingDavid Lordbefore adoptionc74f469

lines 1071–1098why, one step back
1071def test_error_handler_after_processor_error(app, client):
1072 app.testing = False10731074 @app.before_request1075 def before_request():1076 if trigger == 'before':1077 1 // 010781079 @app.after_request1080 def after_request(response):1081 if trigger == 'after':1082 1 // 01083 return response10841085 @app.route('/')1086 def index():1087 return 'Foo'10881089 @app.errorhandler(500)1090 def internal_server_error(e):1091 return 'Hello Server Error', 50010921093 for trigger in 'before', 'after':1094 rv = client.get('/')1095 assert rv.status_code == 5001096 assert rv.data == b'Hello Server Error'10971098

fix formattingDavid Lordbefore adoption8207b15

lines 1099–1444why, one step back
1099def test_enctype_debug_helper(app, client):
1100 from flask.debughelpers import DebugFilesKeyError1101 app.debug = True11021103 @app.route('/fail', methods=['POST'])1104 def index():1105 return flask.request.files['foo'].filename11061107 # with statement is important because we leave an exception on the1108 # stack otherwise and we want to ensure that this is not the case1109 # to not negatively affect other tests.1110 with client:1111 with pytest.raises(DebugFilesKeyError) as e:1112 client.post('/fail', data={'foo': 'index.txt'})1113 assert 'no file contents were transmitted' in str(e.value)1114 assert 'This was submitted: "index.txt"' in str(e.value)111511161117def test_response_types(app, client):1118 @app.route('/text')1119 def from_text():1120 return u'Hällo Wörld'11211122 @app.route('/bytes')1123 def from_bytes():1124 return u'Hällo Wörld'.encode('utf-8')11251126 @app.route('/full_tuple')1127 def from_full_tuple():1128 return 'Meh', 400, {1129 'X-Foo': 'Testing',1130 'Content-Type': 'text/plain; charset=utf-8'1131 }11321133 @app.route('/text_headers')1134 def from_text_headers():1135 return 'Hello', {1136 'X-Foo': 'Test',1137 'Content-Type': 'text/plain; charset=utf-8'1138 }11391140 @app.route('/text_status')1141 def from_text_status():1142 return 'Hi, status!', 40011431144 @app.route('/response_headers')1145 def from_response_headers():1146 return flask.Response('Hello world', 404, {'X-Foo': 'Baz'}), {1147 "X-Foo": "Bar",1148 "X-Bar": "Foo"1149 }11501151 @app.route('/response_status')1152 def from_response_status():1153 return app.response_class('Hello world', 400), 50011541155 @app.route('/wsgi')1156 def from_wsgi():1157 return NotFound()11581159 assert client.get('/text').data == u'Hällo Wörld'.encode('utf-8')1160 assert client.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')11611162 rv = client.get('/full_tuple')1163 assert rv.data == b'Meh'1164 assert rv.headers['X-Foo'] == 'Testing'1165 assert rv.status_code == 4001166 assert rv.mimetype == 'text/plain'11671168 rv = client.get('/text_headers')1169 assert rv.data == b'Hello'1170 assert rv.headers['X-Foo'] == 'Test'1171 assert rv.status_code == 2001172 assert rv.mimetype == 'text/plain'11731174 rv = client.get('/text_status')1175 assert rv.data == b'Hi, status!'1176 assert rv.status_code == 4001177 assert rv.mimetype == 'text/html'11781179 rv = client.get('/response_headers')1180 assert rv.data == b'Hello world'1181 assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar']1182 assert rv.headers['X-Bar'] == 'Foo'1183 assert rv.status_code == 40411841185 rv = client.get('/response_status')1186 assert rv.data == b'Hello world'1187 assert rv.status_code == 50011881189 rv = client.get('/wsgi')1190 assert b'Not Found' in rv.data1191 assert rv.status_code == 404119211931194def test_response_type_errors():1195 app = flask.Flask(__name__)1196 app.testing = True11971198 @app.route('/none')1199 def from_none():1200 pass12011202 @app.route('/small_tuple')1203 def from_small_tuple():1204 return 'Hello',12051206 @app.route('/large_tuple')1207 def from_large_tuple():1208 return 'Hello', 234, {'X-Foo': 'Bar'}, '???'12091210 @app.route('/bad_type')1211 def from_bad_type():1212 return True12131214 @app.route('/bad_wsgi')1215 def from_bad_wsgi():1216 return lambda: None12171218 c = app.test_client()12191220 with pytest.raises(TypeError) as e:1221 c.get('/none')1222 assert 'returned None' in str(e)12231224 with pytest.raises(TypeError) as e:1225 c.get('/small_tuple')1226 assert 'tuple must have the form' in str(e)12271228 pytest.raises(TypeError, c.get, '/large_tuple')12291230 with pytest.raises(TypeError) as e:1231 c.get('/bad_type')1232 assert 'it was a bool' in str(e)12331234 pytest.raises(TypeError, c.get, '/bad_wsgi')123512361237def test_make_response(app, req_ctx):1238 rv = flask.make_response()1239 assert rv.status_code == 2001240 assert rv.data == b''1241 assert rv.mimetype == 'text/html'12421243 rv = flask.make_response('Awesome')1244 assert rv.status_code == 2001245 assert rv.data == b'Awesome'1246 assert rv.mimetype == 'text/html'12471248 rv = flask.make_response('W00t', 404)1249 assert rv.status_code == 4041250 assert rv.data == b'W00t'1251 assert rv.mimetype == 'text/html'125212531254def test_make_response_with_response_instance(app, req_ctx):1255 rv = flask.make_response(1256 flask.jsonify({'msg': 'W00t'}), 400)1257 assert rv.status_code == 4001258 assert rv.data == b'{"msg":"W00t"}\n'1259 assert rv.mimetype == 'application/json'12601261 rv = flask.make_response(1262 flask.Response(''), 400)1263 assert rv.status_code == 4001264 assert rv.data == b''1265 assert rv.mimetype == 'text/html'12661267 rv = flask.make_response(1268 flask.Response('', headers={'Content-Type': 'text/html'}),1269 400, [('X-Foo', 'bar')])1270 assert rv.status_code == 4001271 assert rv.headers['Content-Type'] == 'text/html'1272 assert rv.headers['X-Foo'] == 'bar'127312741275def test_jsonify_no_prettyprint(app, req_ctx):1276 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1277 compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1278 uncompressed_msg = {1279 "msg": {1280 "submsg": "W00t"1281 },1282 "msg2": "foobar"1283 }12841285 rv = flask.make_response(1286 flask.jsonify(uncompressed_msg), 200)1287 assert rv.data == compressed_msg128812891290def test_jsonify_prettyprint(app, req_ctx):1291 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1292 compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1293 pretty_response = \1294 b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'12951296 rv = flask.make_response(1297 flask.jsonify(compressed_msg), 200)1298 assert rv.data == pretty_response129913001301def test_jsonify_mimetype(app, req_ctx):1302 app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'})1303 msg = {1304 "msg": {"submsg": "W00t"},1305 }1306 rv = flask.make_response(1307 flask.jsonify(msg), 200)1308 assert rv.mimetype == 'application/vnd.api+json'130913101311def test_jsonify_args_and_kwargs_check(app, req_ctx):1312 with pytest.raises(TypeError) as e:1313 flask.jsonify('fake args', kwargs='fake')1314 assert 'behavior undefined' in str(e.value)131513161317def test_url_generation(app, req_ctx):1318 @app.route('/hello/<name>', methods=['POST'])1319 def hello():1320 pass13211322 assert flask.url_for('hello', name='test x') == '/hello/test%20x'1323 assert flask.url_for('hello', name='test x', _external=True) == \1324 'http://localhost/hello/test%20x'132513261327def test_build_error_handler(app):1328 # Test base case, a URL which results in a BuildError.1329 with app.test_request_context():1330 pytest.raises(BuildError, flask.url_for, 'spam')13311332 # Verify the error is re-raised if not the current exception.1333 try:1334 with app.test_request_context():1335 flask.url_for('spam')1336 except BuildError as err:1337 error = err1338 try:1339 raise RuntimeError('Test case where BuildError is not current.')1340 except RuntimeError:1341 pytest.raises(1342 BuildError, app.handle_url_build_error, error, 'spam', {})13431344 # Test a custom handler.1345 def handler(error, endpoint, values):1346 # Just a test.1347 return '/test_handler/'13481349 app.url_build_error_handlers.append(handler)1350 with app.test_request_context():1351 assert flask.url_for('spam') == '/test_handler/'135213531354def test_build_error_handler_reraise(app):1355 # Test a custom handler which reraises the BuildError1356 def handler_raises_build_error(error, endpoint, values):1357 raise error13581359 app.url_build_error_handlers.append(handler_raises_build_error)13601361 with app.test_request_context():1362 pytest.raises(BuildError, flask.url_for, 'not.existing')136313641365def test_url_for_passes_special_values_to_build_error_handler(app):1366 @app.url_build_error_handlers.append1367 def handler(error, endpoint, values):1368 assert values == {1369 '_external': False,1370 '_anchor': None,1371 '_method': None,1372 '_scheme': None,1373 }1374 return 'handled'13751376 with app.test_request_context():1377 flask.url_for('/')137813791380def test_custom_converters(app, client):1381 from werkzeug.routing import BaseConverter13821383 class ListConverter(BaseConverter):1384 def to_python(self, value):1385 return value.split(',')13861387 def to_url(self, value):1388 base_to_url = super(ListConverter, self).to_url1389 return ','.join(base_to_url(x) for x in value)13901391 app.url_map.converters['list'] = ListConverter13921393 @app.route('/<list:args>')1394 def index(args):1395 return '|'.join(args)13961397 assert client.get('/1,2,3').data == b'1|2|3'139813991400def test_static_files(app, client):1401 rv = client.get('/static/index.html')1402 assert rv.status_code == 2001403 assert rv.data.strip() == b'<h1>Hello World!</h1>'1404 with app.test_request_context():1405 assert flask.url_for('static', filename='index.html') == \1406 '/static/index.html'1407 rv.close()140814091410def test_static_url_path():1411 app = flask.Flask(__name__, static_url_path='/foo')1412 app.testing = True1413 rv = app.test_client().get('/foo/index.html')1414 assert rv.status_code == 2001415 rv.close()14161417 with app.test_request_context():1418 assert flask.url_for('static', filename='index.html') == '/foo/index.html'141914201421def test_static_route_with_host_matching():1422 app = flask.Flask(__name__, host_matching=True, static_host='example.com')1423 c = app.test_client()1424 rv = c.get('http://example.com/static/index.html')1425 assert rv.status_code == 2001426 rv.close()1427 with app.test_request_context():1428 rv = flask.url_for('static', filename='index.html', _external=True)1429 assert rv == 'http://example.com/static/index.html'1430 # Providing static_host without host_matching=True should error.1431 with pytest.raises(Exception):1432 flask.Flask(__name__, static_host='example.com')1433 # Providing host_matching=True with static_folder but without static_host should error.1434 with pytest.raises(Exception):1435 flask.Flask(__name__, host_matching=True)1436 # Providing host_matching=True without static_host but with static_folder=None should not error.1437 flask.Flask(__name__, host_matching=True, static_folder=None)143814391440def test_request_locals():1441 assert repr(flask.g) == '<LocalProxy unbound>'1442 assert not flask.g14431444

Merge pull request #3261 from pallets/fix-server-name-warningsDavid Lordbefore adoption46a67b6

line 1445why, one step back
1445def test_server_name_subdomain():

Merge pull request #2635 from pallets/feature/server-name-routingDavid Lordbefore adoptionf808c20

lines 1446–1447why, one step back
1446 app = flask.Flask(__name__, subdomain_matching=True)
1447 client = app.test_client()

fix formattingDavid Lordbefore adoption8207b15

line 1448why, one step back
1448

Merge pull request #3261 from pallets/fix-server-name-warningsDavid Lordbefore adoption46a67b6

line 1449why, one step back
1449 @app.route("/")

fix formattingDavid Lordbefore adoption8207b15

line 1450why, one step back
1450 def index():

Merge pull request #3261 from pallets/fix-server-name-warningsDavid Lordbefore adoption46a67b6

line 1451why, one step back
1451 return "default"

fix formattingDavid Lordbefore adoption8207b15

line 1452why, one step back
1452

Merge pull request #3261 from pallets/fix-server-name-warningsDavid Lordbefore adoption46a67b6

line 1453why, one step back
1453 @app.route("/", subdomain="foo")

fix formattingDavid Lordbefore adoption8207b15

line 1454why, one step back
1454 def subdomain():

Merge pull request #3261 from pallets/fix-server-name-warningsDavid Lordbefore adoption46a67b6

line 1455why, one step back
1455 return "subdomain"

fix formattingDavid Lordbefore adoption8207b15

line 1456why, one step back
1456

Merge pull request #3261 from pallets/fix-server-name-warningsDavid Lordbefore adoption46a67b6

lines 1457–1459why, one step back
1457 app.config["SERVER_NAME"] = "dev.local:5000"
1458 rv = client.get("/")1459 assert rv.data == b"default"

fix formattingDavid Lordbefore adoption8207b15

line 1460why, one step back
1460

Merge pull request #3261 from pallets/fix-server-name-warningsDavid Lordbefore adoption46a67b6

lines 1461–1462why, one step back
1461 rv = client.get("/", "http://dev.local:5000")
1462 assert rv.data == b"default"

fix formattingDavid Lordbefore adoption8207b15

line 1463why, one step back
1463

Merge pull request #3261 from pallets/fix-server-name-warningsDavid Lordbefore adoption46a67b6

lines 1464–1465why, one step back
1464 rv = client.get("/", "https://dev.local:5000")
1465 assert rv.data == b"default"

fix formattingDavid Lordbefore adoption8207b15

line 1466why, one step back
1466

Merge pull request #3261 from pallets/fix-server-name-warningsDavid Lordbefore adoption46a67b6

lines 1467–1468why, one step back
1467 app.config["SERVER_NAME"] = "dev.local:443"
1468 rv = client.get("/", "https://dev.local")

fix formattingDavid Lordbefore adoption8207b15

line 1469why, one step back
1469

Merge pull request #3261 from pallets/fix-server-name-warningsDavid Lordbefore adoption46a67b6

lines 1470–1472why, one step back
1470 # Werkzeug 1.0 fixes matching https scheme with 443 port
1471 if rv.status_code != 404:1472 assert rv.data == b"default"

fix formattingDavid Lordbefore adoption8207b15

line 1473why, one step back
1473

Merge pull request #3261 from pallets/fix-server-name-warningsDavid Lordbefore adoption46a67b6

lines 1474–1480why, one step back
1474 app.config["SERVER_NAME"] = "dev.local"
1475 rv = client.get("/", "https://dev.local")1476 assert rv.data == b"default"14771478 # suppress Werkzeug 1.0 warning about name mismatch1479 with pytest.warns(None):1480 rv = client.get("/", "http://foo.localhost")

fix formattingDavid Lordbefore adoption8207b15

lines 1481–1482why, one step back
1481 assert rv.status_code == 404
1482

Merge pull request #3261 from pallets/fix-server-name-warningsDavid Lordbefore adoption46a67b6

lines 1483–1484why, one step back
1483 rv = client.get("/", "http://foo.dev.local")
1484 assert rv.data == b"subdomain"

fix formattingDavid Lordbefore adoption8207b15

lines 1485–1784why, one step back
1485
14861487def test_exception_propagation(app, client):1488 def apprunner(config_key):14891490 @app.route('/')1491 def index():1492 1 // 014931494 if config_key is not None:1495 app.config[config_key] = True1496 with pytest.raises(Exception):1497 client.get('/')1498 else:1499 assert client.get('/').status_code == 50015001501 # we have to run this test in an isolated thread because if the1502 # debug flag is set to true and an exception happens the context is1503 # not torn down. This causes other tests that run after this fail1504 # when they expect no exception on the stack.1505 for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None:1506 t = Thread(target=apprunner, args=(config_key,))1507 t.start()1508 t.join()150915101511@pytest.mark.parametrize('debug', [True, False])1512@pytest.mark.parametrize('use_debugger', [True, False])1513@pytest.mark.parametrize('use_reloader', [True, False])1514@pytest.mark.parametrize('propagate_exceptions', [None, True, False])1515def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1516 use_reloader, propagate_exceptions, app):1517 rv = {}15181519 # Mocks werkzeug.serving.run_simple method1520 def run_simple_mock(*args, **kwargs):1521 rv['passthrough_errors'] = kwargs.get('passthrough_errors')15221523 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1524 app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1525 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)152615271528def test_max_content_length(app, client):1529 app.config['MAX_CONTENT_LENGTH'] = 6415301531 @app.before_request1532 def always_first():1533 flask.request.form['myfile']1534 assert False15351536 @app.route('/accept', methods=['POST'])1537 def accept_file():1538 flask.request.form['myfile']1539 assert False15401541 @app.errorhandler(413)1542 def catcher(error):1543 return '42'15441545 rv = client.post('/accept', data={'myfile': 'foo' * 100})1546 assert rv.data == b'42'154715481549def test_url_processors(app, client):15501551 @app.url_defaults1552 def add_language_code(endpoint, values):1553 if flask.g.lang_code is not None and \1554 app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1555 values.setdefault('lang_code', flask.g.lang_code)15561557 @app.url_value_preprocessor1558 def pull_lang_code(endpoint, values):1559 flask.g.lang_code = values.pop('lang_code', None)15601561 @app.route('/<lang_code>/')1562 def index():1563 return flask.url_for('about')15641565 @app.route('/<lang_code>/about')1566 def about():1567 return flask.url_for('something_else')15681569 @app.route('/foo')1570 def something_else():1571 return flask.url_for('about', lang_code='en')15721573 assert client.get('/de/').data == b'/de/about'1574 assert client.get('/de/about').data == b'/foo'1575 assert client.get('/foo').data == b'/en/about'157615771578def test_inject_blueprint_url_defaults(app):1579 bp = flask.Blueprint('foo.bar.baz', __name__,1580 template_folder='template')15811582 @bp.url_defaults1583 def bp_defaults(endpoint, values):1584 values['page'] = 'login'15851586 @bp.route('/<page>')1587 def view(page):1588 pass15891590 app.register_blueprint(bp)15911592 values = dict()1593 app.inject_url_defaults('foo.bar.baz.view', values)1594 expected = dict(page='login')1595 assert values == expected15961597 with app.test_request_context('/somepage'):1598 url = flask.url_for('foo.bar.baz.view')1599 expected = '/login'1600 assert url == expected160116021603def test_nonascii_pathinfo(app, client):1604 @app.route(u'/киртест')1605 def index():1606 return 'Hello World!'16071608 rv = client.get(u'/киртест')1609 assert rv.data == b'Hello World!'161016111612def test_debug_mode_complains_after_first_request(app, client):1613 app.debug = True16141615 @app.route('/')1616 def index():1617 return 'Awesome'16181619 assert not app.got_first_request1620 assert client.get('/').data == b'Awesome'1621 with pytest.raises(AssertionError) as e:1622 @app.route('/foo')1623 def broken():1624 return 'Meh'1625 assert 'A setup function was called' in str(e)16261627 app.debug = False16281629 @app.route('/foo')1630 def working():1631 return 'Meh'16321633 assert client.get('/foo').data == b'Meh'1634 assert app.got_first_request163516361637def test_before_first_request_functions(app, client):1638 got = []16391640 @app.before_first_request1641 def foo():1642 got.append(42)16431644 client.get('/')1645 assert got == [42]1646 client.get('/')1647 assert got == [42]1648 assert app.got_first_request164916501651def test_before_first_request_functions_concurrent(app, client):1652 got = []16531654 @app.before_first_request1655 def foo():1656 time.sleep(0.2)1657 got.append(42)16581659 def get_and_assert():1660 client.get("/")1661 assert got == [42]16621663 t = Thread(target=get_and_assert)1664 t.start()1665 get_and_assert()1666 t.join()1667 assert app.got_first_request166816691670def test_routing_redirect_debugging(app, client):1671 app.debug = True16721673 @app.route('/foo/', methods=['GET', 'POST'])1674 def foo():1675 return 'success'16761677 with client:1678 with pytest.raises(AssertionError) as e:1679 client.post('/foo', data={})1680 assert 'http://localhost/foo/' in str(e)1681 assert ('Make sure to directly send '1682 'your POST-request to this URL') in str(e)16831684 rv = client.get('/foo', data={}, follow_redirects=True)1685 assert rv.data == b'success'16861687 app.debug = False1688 with client:1689 rv = client.post('/foo', data={}, follow_redirects=True)1690 assert rv.data == b'success'169116921693def test_route_decorator_custom_endpoint(app, client):1694 app.debug = True16951696 @app.route('/foo/')1697 def foo():1698 return flask.request.endpoint16991700 @app.route('/bar/', endpoint='bar')1701 def for_bar():1702 return flask.request.endpoint17031704 @app.route('/bar/123', endpoint='123')1705 def for_bar_foo():1706 return flask.request.endpoint17071708 with app.test_request_context():1709 assert flask.url_for('foo') == '/foo/'1710 assert flask.url_for('bar') == '/bar/'1711 assert flask.url_for('123') == '/bar/123'17121713 assert client.get('/foo/').data == b'foo'1714 assert client.get('/bar/').data == b'bar'1715 assert client.get('/bar/123').data == b'123'171617171718def test_preserve_only_once(app, client):1719 app.debug = True17201721 @app.route('/fail')1722 def fail_func():1723 1 // 017241725 for x in range(3):1726 with pytest.raises(ZeroDivisionError):1727 client.get('/fail')17281729 assert flask._request_ctx_stack.top is not None1730 assert flask._app_ctx_stack.top is not None1731 # implicit appctx disappears too1732 flask._request_ctx_stack.top.pop()1733 assert flask._request_ctx_stack.top is None1734 assert flask._app_ctx_stack.top is None173517361737def test_preserve_remembers_exception(app, client):1738 app.debug = True1739 errors = []17401741 @app.route('/fail')1742 def fail_func():1743 1 // 017441745 @app.route('/success')1746 def success_func():1747 return 'Okay'17481749 @app.teardown_request1750 def teardown_handler(exc):1751 errors.append(exc)17521753 # After this failure we did not yet call the teardown handler1754 with pytest.raises(ZeroDivisionError):1755 client.get('/fail')1756 assert errors == []17571758 # But this request triggers it, and it's an error1759 client.get('/success')1760 assert len(errors) == 21761 assert isinstance(errors[0], ZeroDivisionError)17621763 # At this point another request does nothing.1764 client.get('/success')1765 assert len(errors) == 31766 assert errors[1] is None176717681769def test_get_method_on_g(app_ctx):1770 assert flask.g.get('x') is None1771 assert flask.g.get('x', 11) == 111772 flask.g.x = 421773 assert flask.g.get('x') == 421774 assert flask.g.x == 42177517761777def test_g_iteration_protocol(app_ctx):1778 flask.g.foo = 231779 flask.g.bar = 421780 assert 'foo' in flask.g1781 assert 'foos' not in flask.g1782 assert sorted(flask.g) == ['bar', 'foo']17831784

Merge pull request #2635 from pallets/feature/server-name-routingDavid Lordbefore adoptionf808c20

lines 1785–1786why, one step back
1785def test_subdomain_basic_support():
1786 app = flask.Flask(__name__, subdomain_matching=True)

fix formattingDavid Lordbefore adoption8207b15

line 1787why, one step back
1787 app.config['SERVER_NAME'] = 'localhost.localdomain'

Merge pull request #2635 from pallets/feature/server-name-routingDavid Lordbefore adoptionf808c20

line 1788why, one step back
1788 client = app.test_client()

fix formattingDavid Lordbefore adoption8207b15

lines 1789–1804why, one step back
1789
1790 @app.route('/')1791 def normal_index():1792 return 'normal index'17931794 @app.route('/', subdomain='test')1795 def test_index():1796 return 'test index'17971798 rv = client.get('/', 'http://localhost.localdomain/')1799 assert rv.data == b'normal index'18001801 rv = client.get('/', 'http://test.localhost.localdomain/')1802 assert rv.data == b'test index'18031804

Merge pull request #2635 from pallets/feature/server-name-routingDavid Lordbefore adoptionf808c20

lines 1805–1807why, one step back
1805def test_subdomain_matching():
1806 app = flask.Flask(__name__, subdomain_matching=True)1807 client = app.test_client()

fix formattingDavid Lordbefore adoption8207b15

lines 1808–1817why, one step back
1808 app.config['SERVER_NAME'] = 'localhost.localdomain'
18091810 @app.route('/', subdomain='<user>')1811 def index(user):1812 return 'index for %s' % user18131814 rv = client.get('/', 'http://mitsuhiko.localhost.localdomain/')1815 assert rv.data == b'index for mitsuhiko'18161817

Merge pull request #2635 from pallets/feature/server-name-routingDavid Lordbefore adoptionf808c20

lines 1818–1819why, one step back
1818def test_subdomain_matching_with_ports():
1819 app = flask.Flask(__name__, subdomain_matching=True)

fix formattingDavid Lordbefore adoption8207b15

line 1820why, one step back
1820 app.config['SERVER_NAME'] = 'localhost.localdomain:3000'

Merge pull request #2635 from pallets/feature/server-name-routingDavid Lordbefore adoptionf808c20

line 1821why, one step back
1821 client = app.test_client()

fix formattingDavid Lordbefore adoption8207b15

lines 1822–1828why, one step back
1822
1823 @app.route('/', subdomain='<user>')1824 def index(user):1825 return 'index for %s' % user18261827 rv = client.get('/', 'http://mitsuhiko.localhost.localdomain:3000/')1828 assert rv.data == b'index for mitsuhiko'

Merge pull request #2635 from pallets/feature/server-name-routingDavid Lordbefore adoptionf808c20

lines 1829–1840why, one step back
1829
18301831@pytest.mark.parametrize('matching', (False, True))1832def test_subdomain_matching_other_name(matching):1833 app = flask.Flask(__name__, subdomain_matching=matching)1834 app.config['SERVER_NAME'] = 'localhost.localdomain:3000'1835 client = app.test_client()18361837 @app.route('/')1838 def index():1839 return '', 2041840

Merge pull request #3261 from pallets/fix-server-name-warningsDavid Lordbefore adoption46a67b6

lines 1841–1845why, one step back
1841 # suppress Werkzeug 0.15 warning about name mismatch
1842 with pytest.warns(None):1843 # ip address can't match name1844 rv = client.get('/', 'http://127.0.0.1:3000/')1845 assert rv.status_code == 404 if matching else 204

Merge pull request #2635 from pallets/feature/server-name-routingDavid Lordbefore adoptionf808c20

lines 1846–1849why, one step back
1846
1847 # allow all subdomains if matching is disabled1848 rv = client.get('/', 'http://www.localhost.localdomain:3000/')1849 assert rv.status_code == 404 if matching else 204

fix formattingDavid Lordbefore adoption8207b15

lines 1850–1918why, one step back
1850
18511852def test_multi_route_rules(app, client):1853 @app.route('/')1854 @app.route('/<test>/')1855 def index(test='a'):1856 return test18571858 rv = client.open('/')1859 assert rv.data == b'a'1860 rv = client.open('/b/')1861 assert rv.data == b'b'186218631864def test_multi_route_class_views(app, client):1865 class View(object):1866 def __init__(self, app):1867 app.add_url_rule('/', 'index', self.index)1868 app.add_url_rule('/<test>/', 'index', self.index)18691870 def index(self, test='a'):1871 return test18721873 _ = View(app)1874 rv = client.open('/')1875 assert rv.data == b'a'1876 rv = client.open('/b/')1877 assert rv.data == b'b'187818791880def test_run_defaults(monkeypatch, app):1881 rv = {}18821883 # Mocks werkzeug.serving.run_simple method1884 def run_simple_mock(*args, **kwargs):1885 rv['result'] = 'running...'18861887 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1888 app.run()1889 assert rv['result'] == 'running...'189018911892def test_run_server_port(monkeypatch, app):1893 rv = {}18941895 # Mocks werkzeug.serving.run_simple method1896 def run_simple_mock(hostname, port, application, *args, **kwargs):1897 rv['result'] = 'running on %s:%s ...' % (hostname, port)18981899 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1900 hostname, port = 'localhost', 80001901 app.run(hostname, port, debug=True)1902 assert rv['result'] == 'running on %s:%s ...' % (hostname, port)190319041905@pytest.mark.parametrize('host,port,expect_host,expect_port', (1906 (None, None, 'pocoo.org', 8080),1907 ('localhost', None, 'localhost', 8080),1908 (None, 80, 'pocoo.org', 80),1909 ('localhost', 80, 'localhost', 80),1910))1911def test_run_from_config(monkeypatch, host, port, expect_host, expect_port, app):1912 def run_simple_mock(hostname, port, *args, **kwargs):1913 assert hostname == expect_host1914 assert port == expect_port19151916 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1917 app.config['SERVER_NAME'] = 'pocoo.org:8080'1918 app.run(host, port)

Merge pull request #2693 from davidism/max-cookie-sizeDavid Lordbefore adoptiond8bf589

lines 1919–1948why, one step back
1919
19201921def test_max_cookie_size(app, client, recwarn):1922 app.config['MAX_COOKIE_SIZE'] = 10019231924 # outside app context, default to Werkzeug static value,1925 # which is also the default config1926 response = flask.Response()1927 default = flask.Flask.default_config['MAX_COOKIE_SIZE']1928 assert response.max_cookie_size == default19291930 # inside app context, use app config1931 with app.app_context():1932 assert flask.Response().max_cookie_size == 10019331934 @app.route('/')1935 def index():1936 r = flask.Response('', status=204)1937 r.set_cookie('foo', 'bar' * 100)1938 return r19391940 client.get('/')1941 assert len(recwarn) == 11942 w = recwarn.pop()1943 assert 'cookie is too large' in str(w.message)19441945 app.config['MAX_COOKIE_SIZE'] = 019461947 client.get('/')1948 assert len(recwarn) == 0