test_basic.py
This file
Path
tests/test_basic.py
1,962 lines · 52.3 KiB · Python
Last changed by
Merge pull request #2739 from pallets/2735-abort-debugDavid Lordbefore adoption4c8ec8f
History of this fileTake it
1# -*- coding: utf-8 -*-2"""3 tests.basic4 ~~~~~~~~~~~~~~~~~~~~~56 The basic functionality.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.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():224 assert not flask.session.accessed225 assert not flask.session.modified226 flask.session['value'] = flask.request.form['value']227 assert flask.session.accessed228 assert flask.session.modified229 return 'value set'230231 @app.route('/get')232 def get():233 assert not flask.session.accessed234 assert not flask.session.modified235 v = flask.session.get('value', 'None')236 assert flask.session.accessed237 assert not flask.session.modified238 return v239240 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,322 SESSION_COOKIE_SAMESITE='Lax',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 cookie337 assert 'samesite' in cookie338339340def 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 cookie365366367def 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):1030 @app.route('/key')1031 def fail():1032 flask.request.form['missing_key']10331034 @app.route('/abort')1035 def allow_abort():1036 flask.abort(400)10371038 rv = client.get('/key')1039 assert rv.status_code == 4001040 assert b'missing_key' not in rv.data1041 rv = client.get('/abort')1042 assert rv.status_code == 40010431044 app.debug = True1045 with pytest.raises(KeyError) as e:1046 client.get("/key")1047 assert e.errisinstance(BadRequest)1048 assert 'missing_key' in e.value.description1049 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')105810591060def 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')106910701071def 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'109710981099def 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.g144314441445def test_test_app_proper_environ():1446 app = flask.Flask(__name__, subdomain_matching=True)1447 app.config.update(1448 SERVER_NAME='localhost.localdomain:5000'1449 )1450 client = app.test_client()14511452 @app.route('/')1453 def index():1454 return 'Foo'14551456 @app.route('/', subdomain='foo')1457 def subdomain():1458 return 'Foo SubDomain'14591460 rv = client.get('/')1461 assert rv.data == b'Foo'14621463 rv = client.get('/', 'http://localhost.localdomain:5000')1464 assert rv.data == b'Foo'14651466 rv = client.get('/', 'https://localhost.localdomain:5000')1467 assert rv.data == b'Foo'14681469 app.config.update(SERVER_NAME='localhost.localdomain')1470 rv = client.get('/', 'https://localhost.localdomain')1471 assert rv.data == b'Foo'14721473 try:1474 app.config.update(SERVER_NAME='localhost.localdomain:443')1475 rv = client.get('/', 'https://localhost.localdomain')1476 # Werkzeug 0.81477 assert rv.status_code == 4041478 except ValueError as e:1479 # Werkzeug 0.71480 assert str(e) == (1481 "the server name provided "1482 "('localhost.localdomain:443') does not match the "1483 "server name from the WSGI environment ('localhost.localdomain')"1484 )14851486 try:1487 app.config.update(SERVER_NAME='localhost.localdomain')1488 rv = client.get('/', 'http://foo.localhost')1489 # Werkzeug 0.81490 assert rv.status_code == 4041491 except ValueError as e:1492 # Werkzeug 0.71493 assert str(e) == (1494 "the server name provided "1495 "('localhost.localdomain') does not match the "1496 "server name from the WSGI environment ('foo.localhost')"1497 )14981499 rv = client.get('/', 'http://foo.localhost.localdomain')1500 assert rv.data == b'Foo SubDomain'150115021503def test_exception_propagation(app, client):1504 def apprunner(config_key):15051506 @app.route('/')1507 def index():1508 1 // 015091510 if config_key is not None:1511 app.config[config_key] = True1512 with pytest.raises(Exception):1513 client.get('/')1514 else:1515 assert client.get('/').status_code == 50015161517 # we have to run this test in an isolated thread because if the1518 # debug flag is set to true and an exception happens the context is1519 # not torn down. This causes other tests that run after this fail1520 # when they expect no exception on the stack.1521 for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None:1522 t = Thread(target=apprunner, args=(config_key,))1523 t.start()1524 t.join()152515261527@pytest.mark.parametrize('debug', [True, False])1528@pytest.mark.parametrize('use_debugger', [True, False])1529@pytest.mark.parametrize('use_reloader', [True, False])1530@pytest.mark.parametrize('propagate_exceptions', [None, True, False])1531def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1532 use_reloader, propagate_exceptions, app):1533 rv = {}15341535 # Mocks werkzeug.serving.run_simple method1536 def run_simple_mock(*args, **kwargs):1537 rv['passthrough_errors'] = kwargs.get('passthrough_errors')15381539 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1540 app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1541 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)154215431544def test_max_content_length(app, client):1545 app.config['MAX_CONTENT_LENGTH'] = 6415461547 @app.before_request1548 def always_first():1549 flask.request.form['myfile']1550 assert False15511552 @app.route('/accept', methods=['POST'])1553 def accept_file():1554 flask.request.form['myfile']1555 assert False15561557 @app.errorhandler(413)1558 def catcher(error):1559 return '42'15601561 rv = client.post('/accept', data={'myfile': 'foo' * 100})1562 assert rv.data == b'42'156315641565def test_url_processors(app, client):15661567 @app.url_defaults1568 def add_language_code(endpoint, values):1569 if flask.g.lang_code is not None and \1570 app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1571 values.setdefault('lang_code', flask.g.lang_code)15721573 @app.url_value_preprocessor1574 def pull_lang_code(endpoint, values):1575 flask.g.lang_code = values.pop('lang_code', None)15761577 @app.route('/<lang_code>/')1578 def index():1579 return flask.url_for('about')15801581 @app.route('/<lang_code>/about')1582 def about():1583 return flask.url_for('something_else')15841585 @app.route('/foo')1586 def something_else():1587 return flask.url_for('about', lang_code='en')15881589 assert client.get('/de/').data == b'/de/about'1590 assert client.get('/de/about').data == b'/foo'1591 assert client.get('/foo').data == b'/en/about'159215931594def test_inject_blueprint_url_defaults(app):1595 bp = flask.Blueprint('foo.bar.baz', __name__,1596 template_folder='template')15971598 @bp.url_defaults1599 def bp_defaults(endpoint, values):1600 values['page'] = 'login'16011602 @bp.route('/<page>')1603 def view(page):1604 pass16051606 app.register_blueprint(bp)16071608 values = dict()1609 app.inject_url_defaults('foo.bar.baz.view', values)1610 expected = dict(page='login')1611 assert values == expected16121613 with app.test_request_context('/somepage'):1614 url = flask.url_for('foo.bar.baz.view')1615 expected = '/login'1616 assert url == expected161716181619def test_nonascii_pathinfo(app, client):1620 @app.route(u'/киртест')1621 def index():1622 return 'Hello World!'16231624 rv = client.get(u'/киртест')1625 assert rv.data == b'Hello World!'162616271628def test_debug_mode_complains_after_first_request(app, client):1629 app.debug = True16301631 @app.route('/')1632 def index():1633 return 'Awesome'16341635 assert not app.got_first_request1636 assert client.get('/').data == b'Awesome'1637 with pytest.raises(AssertionError) as e:1638 @app.route('/foo')1639 def broken():1640 return 'Meh'1641 assert 'A setup function was called' in str(e)16421643 app.debug = False16441645 @app.route('/foo')1646 def working():1647 return 'Meh'16481649 assert client.get('/foo').data == b'Meh'1650 assert app.got_first_request165116521653def test_before_first_request_functions(app, client):1654 got = []16551656 @app.before_first_request1657 def foo():1658 got.append(42)16591660 client.get('/')1661 assert got == [42]1662 client.get('/')1663 assert got == [42]1664 assert app.got_first_request166516661667def test_before_first_request_functions_concurrent(app, client):1668 got = []16691670 @app.before_first_request1671 def foo():1672 time.sleep(0.2)1673 got.append(42)16741675 def get_and_assert():1676 client.get("/")1677 assert got == [42]16781679 t = Thread(target=get_and_assert)1680 t.start()1681 get_and_assert()1682 t.join()1683 assert app.got_first_request168416851686def test_routing_redirect_debugging(app, client):1687 app.debug = True16881689 @app.route('/foo/', methods=['GET', 'POST'])1690 def foo():1691 return 'success'16921693 with client:1694 with pytest.raises(AssertionError) as e:1695 client.post('/foo', data={})1696 assert 'http://localhost/foo/' in str(e)1697 assert ('Make sure to directly send '1698 'your POST-request to this URL') in str(e)16991700 rv = client.get('/foo', data={}, follow_redirects=True)1701 assert rv.data == b'success'17021703 app.debug = False1704 with client:1705 rv = client.post('/foo', data={}, follow_redirects=True)1706 assert rv.data == b'success'170717081709def test_route_decorator_custom_endpoint(app, client):1710 app.debug = True17111712 @app.route('/foo/')1713 def foo():1714 return flask.request.endpoint17151716 @app.route('/bar/', endpoint='bar')1717 def for_bar():1718 return flask.request.endpoint17191720 @app.route('/bar/123', endpoint='123')1721 def for_bar_foo():1722 return flask.request.endpoint17231724 with app.test_request_context():1725 assert flask.url_for('foo') == '/foo/'1726 assert flask.url_for('bar') == '/bar/'1727 assert flask.url_for('123') == '/bar/123'17281729 assert client.get('/foo/').data == b'foo'1730 assert client.get('/bar/').data == b'bar'1731 assert client.get('/bar/123').data == b'123'173217331734def test_preserve_only_once(app, client):1735 app.debug = True17361737 @app.route('/fail')1738 def fail_func():1739 1 // 017401741 for x in range(3):1742 with pytest.raises(ZeroDivisionError):1743 client.get('/fail')17441745 assert flask._request_ctx_stack.top is not None1746 assert flask._app_ctx_stack.top is not None1747 # implicit appctx disappears too1748 flask._request_ctx_stack.top.pop()1749 assert flask._request_ctx_stack.top is None1750 assert flask._app_ctx_stack.top is None175117521753def test_preserve_remembers_exception(app, client):1754 app.debug = True1755 errors = []17561757 @app.route('/fail')1758 def fail_func():1759 1 // 017601761 @app.route('/success')1762 def success_func():1763 return 'Okay'17641765 @app.teardown_request1766 def teardown_handler(exc):1767 errors.append(exc)17681769 # After this failure we did not yet call the teardown handler1770 with pytest.raises(ZeroDivisionError):1771 client.get('/fail')1772 assert errors == []17731774 # But this request triggers it, and it's an error1775 client.get('/success')1776 assert len(errors) == 21777 assert isinstance(errors[0], ZeroDivisionError)17781779 # At this point another request does nothing.1780 client.get('/success')1781 assert len(errors) == 31782 assert errors[1] is None178317841785def test_get_method_on_g(app_ctx):1786 assert flask.g.get('x') is None1787 assert flask.g.get('x', 11) == 111788 flask.g.x = 421789 assert flask.g.get('x') == 421790 assert flask.g.x == 42179117921793def test_g_iteration_protocol(app_ctx):1794 flask.g.foo = 231795 flask.g.bar = 421796 assert 'foo' in flask.g1797 assert 'foos' not in flask.g1798 assert sorted(flask.g) == ['bar', 'foo']179918001801def test_subdomain_basic_support():1802 app = flask.Flask(__name__, subdomain_matching=True)1803 app.config['SERVER_NAME'] = 'localhost.localdomain'1804 client = app.test_client()18051806 @app.route('/')1807 def normal_index():1808 return 'normal index'18091810 @app.route('/', subdomain='test')1811 def test_index():1812 return 'test index'18131814 rv = client.get('/', 'http://localhost.localdomain/')1815 assert rv.data == b'normal index'18161817 rv = client.get('/', 'http://test.localhost.localdomain/')1818 assert rv.data == b'test index'181918201821def test_subdomain_matching():1822 app = flask.Flask(__name__, subdomain_matching=True)1823 client = app.test_client()1824 app.config['SERVER_NAME'] = 'localhost.localdomain'18251826 @app.route('/', subdomain='<user>')1827 def index(user):1828 return 'index for %s' % user18291830 rv = client.get('/', 'http://mitsuhiko.localhost.localdomain/')1831 assert rv.data == b'index for mitsuhiko'183218331834def test_subdomain_matching_with_ports():1835 app = flask.Flask(__name__, subdomain_matching=True)1836 app.config['SERVER_NAME'] = 'localhost.localdomain:3000'1837 client = app.test_client()18381839 @app.route('/', subdomain='<user>')1840 def index(user):1841 return 'index for %s' % user18421843 rv = client.get('/', 'http://mitsuhiko.localhost.localdomain:3000/')1844 assert rv.data == b'index for mitsuhiko'184518461847@pytest.mark.parametrize('matching', (False, True))1848def test_subdomain_matching_other_name(matching):1849 app = flask.Flask(__name__, subdomain_matching=matching)1850 app.config['SERVER_NAME'] = 'localhost.localdomain:3000'1851 client = app.test_client()18521853 @app.route('/')1854 def index():1855 return '', 20418561857 # ip address can't match name1858 rv = client.get('/', 'http://127.0.0.1:3000/')1859 assert rv.status_code == 404 if matching else 20418601861 # allow all subdomains if matching is disabled1862 rv = client.get('/', 'http://www.localhost.localdomain:3000/')1863 assert rv.status_code == 404 if matching else 204186418651866def test_multi_route_rules(app, client):1867 @app.route('/')1868 @app.route('/<test>/')1869 def index(test='a'):1870 return test18711872 rv = client.open('/')1873 assert rv.data == b'a'1874 rv = client.open('/b/')1875 assert rv.data == b'b'187618771878def test_multi_route_class_views(app, client):1879 class View(object):1880 def __init__(self, app):1881 app.add_url_rule('/', 'index', self.index)1882 app.add_url_rule('/<test>/', 'index', self.index)18831884 def index(self, test='a'):1885 return test18861887 _ = View(app)1888 rv = client.open('/')1889 assert rv.data == b'a'1890 rv = client.open('/b/')1891 assert rv.data == b'b'189218931894def test_run_defaults(monkeypatch, app):1895 rv = {}18961897 # Mocks werkzeug.serving.run_simple method1898 def run_simple_mock(*args, **kwargs):1899 rv['result'] = 'running...'19001901 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1902 app.run()1903 assert rv['result'] == 'running...'190419051906def test_run_server_port(monkeypatch, app):1907 rv = {}19081909 # Mocks werkzeug.serving.run_simple method1910 def run_simple_mock(hostname, port, application, *args, **kwargs):1911 rv['result'] = 'running on %s:%s ...' % (hostname, port)19121913 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1914 hostname, port = 'localhost', 80001915 app.run(hostname, port, debug=True)1916 assert rv['result'] == 'running on %s:%s ...' % (hostname, port)191719181919@pytest.mark.parametrize('host,port,expect_host,expect_port', (1920 (None, None, 'pocoo.org', 8080),1921 ('localhost', None, 'localhost', 8080),1922 (None, 80, 'pocoo.org', 80),1923 ('localhost', 80, 'localhost', 80),1924))1925def test_run_from_config(monkeypatch, host, port, expect_host, expect_port, app):1926 def run_simple_mock(hostname, port, *args, **kwargs):1927 assert hostname == expect_host1928 assert port == expect_port19291930 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1931 app.config['SERVER_NAME'] = 'pocoo.org:8080'1932 app.run(host, port)193319341935def test_max_cookie_size(app, client, recwarn):1936 app.config['MAX_COOKIE_SIZE'] = 10019371938 # outside app context, default to Werkzeug static value,1939 # which is also the default config1940 response = flask.Response()1941 default = flask.Flask.default_config['MAX_COOKIE_SIZE']1942 assert response.max_cookie_size == default19431944 # inside app context, use app config1945 with app.app_context():1946 assert flask.Response().max_cookie_size == 10019471948 @app.route('/')1949 def index():1950 r = flask.Response('', status=204)1951 r.set_cookie('foo', 'bar' * 100)1952 return r19531954 client.get('/')1955 assert len(recwarn) == 11956 w = recwarn.pop()1957 assert 'cookie is too large' in str(w.message)19581959 app.config['MAX_COOKIE_SIZE'] = 019601961 client.get('/')1962 assert len(recwarn) == 0