Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

1,892 lines · 50.2 KiB · Python

Last changed by

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

History of this file

Take it

1# -*- coding: utf-8 -*-2"""3    tests.basic4    ~~~~~~~~~~~~~~~~~~~~~56    The basic functionality.78    :copyright: (c) 2015 by Armin Ronacher.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('/fail')1031    def fail():1032        flask.request.form['missing_key']10331034    rv = client.get('/fail')1035    assert rv.status_code == 4001036    assert b'missing_key' not in rv.data10371038    app.config['TRAP_BAD_REQUEST_ERRORS'] = True10391040    with pytest.raises(KeyError) as e:1041        client.get("/fail")10421043    assert e.errisinstance(BadRequest)1044    assert 'missing_key' in e.value.description104510461047def test_trapping_of_all_http_exceptions(app, client):1048    app.config['TRAP_HTTP_EXCEPTIONS'] = True10491050    @app.route('/fail')1051    def fail():1052        flask.abort(404)10531054    with pytest.raises(NotFound):1055        client.get('/fail')105610571058def test_error_handler_after_processor_error(app, client):1059    app.testing = False10601061    @app.before_request1062    def before_request():1063        if trigger == 'before':1064            1 // 010651066    @app.after_request1067    def after_request(response):1068        if trigger == 'after':1069            1 // 01070        return response10711072    @app.route('/')1073    def index():1074        return 'Foo'10751076    @app.errorhandler(500)1077    def internal_server_error(e):1078        return 'Hello Server Error', 50010791080    for trigger in 'before', 'after':1081        rv = client.get('/')1082        assert rv.status_code == 5001083        assert rv.data == b'Hello Server Error'108410851086def test_enctype_debug_helper(app, client):1087    from flask.debughelpers import DebugFilesKeyError1088    app.debug = True10891090    @app.route('/fail', methods=['POST'])1091    def index():1092        return flask.request.files['foo'].filename10931094    # with statement is important because we leave an exception on the1095    # stack otherwise and we want to ensure that this is not the case1096    # to not negatively affect other tests.1097    with client:1098        with pytest.raises(DebugFilesKeyError) as e:1099            client.post('/fail', data={'foo': 'index.txt'})1100        assert 'no file contents were transmitted' in str(e.value)1101        assert 'This was submitted: "index.txt"' in str(e.value)110211031104def test_response_types(app, client):1105    @app.route('/text')1106    def from_text():1107        return u'Hällo Wörld'11081109    @app.route('/bytes')1110    def from_bytes():1111        return u'Hällo Wörld'.encode('utf-8')11121113    @app.route('/full_tuple')1114    def from_full_tuple():1115        return 'Meh', 400, {1116            'X-Foo': 'Testing',1117            'Content-Type': 'text/plain; charset=utf-8'1118        }11191120    @app.route('/text_headers')1121    def from_text_headers():1122        return 'Hello', {1123            'X-Foo': 'Test',1124            'Content-Type': 'text/plain; charset=utf-8'1125        }11261127    @app.route('/text_status')1128    def from_text_status():1129        return 'Hi, status!', 40011301131    @app.route('/response_headers')1132    def from_response_headers():1133        return flask.Response('Hello world', 404, {'X-Foo': 'Baz'}), {1134            "X-Foo": "Bar",1135            "X-Bar": "Foo"1136        }11371138    @app.route('/response_status')1139    def from_response_status():1140        return app.response_class('Hello world', 400), 50011411142    @app.route('/wsgi')1143    def from_wsgi():1144        return NotFound()11451146    assert client.get('/text').data == u'Hällo Wörld'.encode('utf-8')1147    assert client.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')11481149    rv = client.get('/full_tuple')1150    assert rv.data == b'Meh'1151    assert rv.headers['X-Foo'] == 'Testing'1152    assert rv.status_code == 4001153    assert rv.mimetype == 'text/plain'11541155    rv = client.get('/text_headers')1156    assert rv.data == b'Hello'1157    assert rv.headers['X-Foo'] == 'Test'1158    assert rv.status_code == 2001159    assert rv.mimetype == 'text/plain'11601161    rv = client.get('/text_status')1162    assert rv.data == b'Hi, status!'1163    assert rv.status_code == 4001164    assert rv.mimetype == 'text/html'11651166    rv = client.get('/response_headers')1167    assert rv.data == b'Hello world'1168    assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar']1169    assert rv.headers['X-Bar'] == 'Foo'1170    assert rv.status_code == 40411711172    rv = client.get('/response_status')1173    assert rv.data == b'Hello world'1174    assert rv.status_code == 50011751176    rv = client.get('/wsgi')1177    assert b'Not Found' in rv.data1178    assert rv.status_code == 404117911801181def test_response_type_errors():1182    app = flask.Flask(__name__)1183    app.testing = True11841185    @app.route('/none')1186    def from_none():1187        pass11881189    @app.route('/small_tuple')1190    def from_small_tuple():1191        return 'Hello',11921193    @app.route('/large_tuple')1194    def from_large_tuple():1195        return 'Hello', 234, {'X-Foo': 'Bar'}, '???'11961197    @app.route('/bad_type')1198    def from_bad_type():1199        return True12001201    @app.route('/bad_wsgi')1202    def from_bad_wsgi():1203        return lambda: None12041205    c = app.test_client()12061207    with pytest.raises(TypeError) as e:1208        c.get('/none')1209        assert 'returned None' in str(e)12101211    with pytest.raises(TypeError) as e:1212        c.get('/small_tuple')1213        assert 'tuple must have the form' in str(e)12141215    pytest.raises(TypeError, c.get, '/large_tuple')12161217    with pytest.raises(TypeError) as e:1218        c.get('/bad_type')1219        assert 'it was a bool' in str(e)12201221    pytest.raises(TypeError, c.get, '/bad_wsgi')122212231224def test_make_response(app, req_ctx):1225    rv = flask.make_response()1226    assert rv.status_code == 2001227    assert rv.data == b''1228    assert rv.mimetype == 'text/html'12291230    rv = flask.make_response('Awesome')1231    assert rv.status_code == 2001232    assert rv.data == b'Awesome'1233    assert rv.mimetype == 'text/html'12341235    rv = flask.make_response('W00t', 404)1236    assert rv.status_code == 4041237    assert rv.data == b'W00t'1238    assert rv.mimetype == 'text/html'123912401241def test_make_response_with_response_instance(app, req_ctx):1242    rv = flask.make_response(1243        flask.jsonify({'msg': 'W00t'}), 400)1244    assert rv.status_code == 4001245    assert rv.data == b'{"msg":"W00t"}\n'1246    assert rv.mimetype == 'application/json'12471248    rv = flask.make_response(1249        flask.Response(''), 400)1250    assert rv.status_code == 4001251    assert rv.data == b''1252    assert rv.mimetype == 'text/html'12531254    rv = flask.make_response(1255        flask.Response('', headers={'Content-Type': 'text/html'}),1256        400, [('X-Foo', 'bar')])1257    assert rv.status_code == 4001258    assert rv.headers['Content-Type'] == 'text/html'1259    assert rv.headers['X-Foo'] == 'bar'126012611262def test_jsonify_no_prettyprint(app, req_ctx):1263    app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1264    compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1265    uncompressed_msg = {1266        "msg": {1267            "submsg": "W00t"1268        },1269        "msg2": "foobar"1270    }12711272    rv = flask.make_response(1273        flask.jsonify(uncompressed_msg), 200)1274    assert rv.data == compressed_msg127512761277def test_jsonify_prettyprint(app, req_ctx):1278    app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1279    compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1280    pretty_response = \1281        b'{\n  "msg": {\n    "submsg": "W00t"\n  }, \n  "msg2": "foobar"\n}\n'12821283    rv = flask.make_response(1284        flask.jsonify(compressed_msg), 200)1285    assert rv.data == pretty_response128612871288def test_jsonify_mimetype(app, req_ctx):1289    app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'})1290    msg = {1291        "msg": {"submsg": "W00t"},1292    }1293    rv = flask.make_response(1294        flask.jsonify(msg), 200)1295    assert rv.mimetype == 'application/vnd.api+json'129612971298def test_jsonify_args_and_kwargs_check(app, req_ctx):1299    with pytest.raises(TypeError) as e:1300        flask.jsonify('fake args', kwargs='fake')1301    assert 'behavior undefined' in str(e.value)130213031304def test_url_generation(app, req_ctx):1305    @app.route('/hello/<name>', methods=['POST'])1306    def hello():1307        pass13081309    assert flask.url_for('hello', name='test x') == '/hello/test%20x'1310    assert flask.url_for('hello', name='test x', _external=True) == \1311           'http://localhost/hello/test%20x'131213131314def test_build_error_handler(app):1315    # Test base case, a URL which results in a BuildError.1316    with app.test_request_context():1317        pytest.raises(BuildError, flask.url_for, 'spam')13181319    # Verify the error is re-raised if not the current exception.1320    try:1321        with app.test_request_context():1322            flask.url_for('spam')1323    except BuildError as err:1324        error = err1325    try:1326        raise RuntimeError('Test case where BuildError is not current.')1327    except RuntimeError:1328        pytest.raises(1329            BuildError, app.handle_url_build_error, error, 'spam', {})13301331    # Test a custom handler.1332    def handler(error, endpoint, values):1333        # Just a test.1334        return '/test_handler/'13351336    app.url_build_error_handlers.append(handler)1337    with app.test_request_context():1338        assert flask.url_for('spam') == '/test_handler/'133913401341def test_build_error_handler_reraise(app):1342    # Test a custom handler which reraises the BuildError1343    def handler_raises_build_error(error, endpoint, values):1344        raise error13451346    app.url_build_error_handlers.append(handler_raises_build_error)13471348    with app.test_request_context():1349        pytest.raises(BuildError, flask.url_for, 'not.existing')135013511352def test_url_for_passes_special_values_to_build_error_handler(app):1353    @app.url_build_error_handlers.append1354    def handler(error, endpoint, values):1355        assert values == {1356            '_external': False,1357            '_anchor': None,1358            '_method': None,1359            '_scheme': None,1360        }1361        return 'handled'13621363    with app.test_request_context():1364        flask.url_for('/')136513661367def test_custom_converters(app, client):1368    from werkzeug.routing import BaseConverter13691370    class ListConverter(BaseConverter):1371        def to_python(self, value):1372            return value.split(',')13731374        def to_url(self, value):1375            base_to_url = super(ListConverter, self).to_url1376            return ','.join(base_to_url(x) for x in value)13771378    app.url_map.converters['list'] = ListConverter13791380    @app.route('/<list:args>')1381    def index(args):1382        return '|'.join(args)13831384    assert client.get('/1,2,3').data == b'1|2|3'138513861387def test_static_files(app, client):1388    rv = client.get('/static/index.html')1389    assert rv.status_code == 2001390    assert rv.data.strip() == b'<h1>Hello World!</h1>'1391    with app.test_request_context():1392        assert flask.url_for('static', filename='index.html') == \1393               '/static/index.html'1394    rv.close()139513961397def test_static_url_path():1398    app = flask.Flask(__name__, static_url_path='/foo')1399    app.testing = True1400    rv = app.test_client().get('/foo/index.html')1401    assert rv.status_code == 2001402    rv.close()14031404    with app.test_request_context():1405        assert flask.url_for('static', filename='index.html') == '/foo/index.html'140614071408def test_static_route_with_host_matching():1409    app = flask.Flask(__name__, host_matching=True, static_host='example.com')1410    c = app.test_client()1411    rv = c.get('http://example.com/static/index.html')1412    assert rv.status_code == 2001413    rv.close()1414    with app.test_request_context():1415        rv = flask.url_for('static', filename='index.html', _external=True)1416        assert rv == 'http://example.com/static/index.html'1417    # Providing static_host without host_matching=True should error.1418    with pytest.raises(Exception):1419        flask.Flask(__name__, static_host='example.com')1420    # Providing host_matching=True with static_folder but without static_host should error.1421    with pytest.raises(Exception):1422        flask.Flask(__name__, host_matching=True)1423    # Providing host_matching=True without static_host but with static_folder=None should not error.1424    flask.Flask(__name__, host_matching=True, static_folder=None)142514261427def test_request_locals():1428    assert repr(flask.g) == '<LocalProxy unbound>'1429    assert not flask.g143014311432def test_test_app_proper_environ(app, client):1433    app.config.update(1434        SERVER_NAME='localhost.localdomain:5000'1435    )14361437    @app.route('/')1438    def index():1439        return 'Foo'14401441    @app.route('/', subdomain='foo')1442    def subdomain():1443        return 'Foo SubDomain'14441445    rv = client.get('/')1446    assert rv.data == b'Foo'14471448    rv = client.get('/', 'http://localhost.localdomain:5000')1449    assert rv.data == b'Foo'14501451    rv = client.get('/', 'https://localhost.localdomain:5000')1452    assert rv.data == b'Foo'14531454    app.config.update(SERVER_NAME='localhost.localdomain')1455    rv = client.get('/', 'https://localhost.localdomain')1456    assert rv.data == b'Foo'14571458    try:1459        app.config.update(SERVER_NAME='localhost.localdomain:443')1460        rv = client.get('/', 'https://localhost.localdomain')1461        # Werkzeug 0.81462        assert rv.status_code == 4041463    except ValueError as e:1464        # Werkzeug 0.71465        assert str(e) == (1466            "the server name provided "1467            "('localhost.localdomain:443') does not match the "1468            "server name from the WSGI environment ('localhost.localdomain')"1469        )14701471    try:1472        app.config.update(SERVER_NAME='localhost.localdomain')1473        rv = client.get('/', 'http://foo.localhost')1474        # Werkzeug 0.81475        assert rv.status_code == 4041476    except ValueError as e:1477        # Werkzeug 0.71478        assert str(e) == (1479            "the server name provided "1480            "('localhost.localdomain') does not match the "1481            "server name from the WSGI environment ('foo.localhost')"1482        )14831484    rv = client.get('/', 'http://foo.localhost.localdomain')1485    assert rv.data == b'Foo SubDomain'148614871488def test_exception_propagation(app, client):1489    def apprunner(config_key):14901491        @app.route('/')1492        def index():1493            1 // 014941495        if config_key is not None:1496            app.config[config_key] = True1497            with pytest.raises(Exception):1498                client.get('/')1499        else:1500            assert client.get('/').status_code == 50015011502    # we have to run this test in an isolated thread because if the1503    # debug flag is set to true and an exception happens the context is1504    # not torn down.  This causes other tests that run after this fail1505    # when they expect no exception on the stack.1506    for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None:1507        t = Thread(target=apprunner, args=(config_key,))1508        t.start()1509        t.join()151015111512@pytest.mark.parametrize('debug', [True, False])1513@pytest.mark.parametrize('use_debugger', [True, False])1514@pytest.mark.parametrize('use_reloader', [True, False])1515@pytest.mark.parametrize('propagate_exceptions', [None, True, False])1516def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1517                                     use_reloader, propagate_exceptions, app):1518    rv = {}15191520    # Mocks werkzeug.serving.run_simple method1521    def run_simple_mock(*args, **kwargs):1522        rv['passthrough_errors'] = kwargs.get('passthrough_errors')15231524    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1525    app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1526    app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)152715281529def test_max_content_length(app, client):1530    app.config['MAX_CONTENT_LENGTH'] = 6415311532    @app.before_request1533    def always_first():1534        flask.request.form['myfile']1535        assert False15361537    @app.route('/accept', methods=['POST'])1538    def accept_file():1539        flask.request.form['myfile']1540        assert False15411542    @app.errorhandler(413)1543    def catcher(error):1544        return '42'15451546    rv = client.post('/accept', data={'myfile': 'foo' * 100})1547    assert rv.data == b'42'154815491550def test_url_processors(app, client):15511552    @app.url_defaults1553    def add_language_code(endpoint, values):1554        if flask.g.lang_code is not None and \1555                app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1556            values.setdefault('lang_code', flask.g.lang_code)15571558    @app.url_value_preprocessor1559    def pull_lang_code(endpoint, values):1560        flask.g.lang_code = values.pop('lang_code', None)15611562    @app.route('/<lang_code>/')1563    def index():1564        return flask.url_for('about')15651566    @app.route('/<lang_code>/about')1567    def about():1568        return flask.url_for('something_else')15691570    @app.route('/foo')1571    def something_else():1572        return flask.url_for('about', lang_code='en')15731574    assert client.get('/de/').data == b'/de/about'1575    assert client.get('/de/about').data == b'/foo'1576    assert client.get('/foo').data == b'/en/about'157715781579def test_inject_blueprint_url_defaults(app):1580    bp = flask.Blueprint('foo.bar.baz', __name__,1581                         template_folder='template')15821583    @bp.url_defaults1584    def bp_defaults(endpoint, values):1585        values['page'] = 'login'15861587    @bp.route('/<page>')1588    def view(page):1589        pass15901591    app.register_blueprint(bp)15921593    values = dict()1594    app.inject_url_defaults('foo.bar.baz.view', values)1595    expected = dict(page='login')1596    assert values == expected15971598    with app.test_request_context('/somepage'):1599        url = flask.url_for('foo.bar.baz.view')1600    expected = '/login'1601    assert url == expected160216031604def test_nonascii_pathinfo(app, client):1605    @app.route(u'/киртест')1606    def index():1607        return 'Hello World!'16081609    rv = client.get(u'/киртест')1610    assert rv.data == b'Hello World!'161116121613def test_debug_mode_complains_after_first_request(app, client):1614    app.debug = True16151616    @app.route('/')1617    def index():1618        return 'Awesome'16191620    assert not app.got_first_request1621    assert client.get('/').data == b'Awesome'1622    with pytest.raises(AssertionError) as e:1623        @app.route('/foo')1624        def broken():1625            return 'Meh'1626    assert 'A setup function was called' in str(e)16271628    app.debug = False16291630    @app.route('/foo')1631    def working():1632        return 'Meh'16331634    assert client.get('/foo').data == b'Meh'1635    assert app.got_first_request163616371638def test_before_first_request_functions(app, client):1639    got = []16401641    @app.before_first_request1642    def foo():1643        got.append(42)16441645    client.get('/')1646    assert got == [42]1647    client.get('/')1648    assert got == [42]1649    assert app.got_first_request165016511652def test_before_first_request_functions_concurrent(app, client):1653    got = []16541655    @app.before_first_request1656    def foo():1657        time.sleep(0.2)1658        got.append(42)16591660    def get_and_assert():1661        client.get("/")1662        assert got == [42]16631664    t = Thread(target=get_and_assert)1665    t.start()1666    get_and_assert()1667    t.join()1668    assert app.got_first_request166916701671def test_routing_redirect_debugging(app, client):1672    app.debug = True16731674    @app.route('/foo/', methods=['GET', 'POST'])1675    def foo():1676        return 'success'16771678    with client:1679        with pytest.raises(AssertionError) as e:1680            client.post('/foo', data={})1681        assert 'http://localhost/foo/' in str(e)1682        assert ('Make sure to directly send '1683                'your POST-request to this URL') in str(e)16841685        rv = client.get('/foo', data={}, follow_redirects=True)1686        assert rv.data == b'success'16871688    app.debug = False1689    with client:1690        rv = client.post('/foo', data={}, follow_redirects=True)1691        assert rv.data == b'success'169216931694def test_route_decorator_custom_endpoint(app, client):1695    app.debug = True16961697    @app.route('/foo/')1698    def foo():1699        return flask.request.endpoint17001701    @app.route('/bar/', endpoint='bar')1702    def for_bar():1703        return flask.request.endpoint17041705    @app.route('/bar/123', endpoint='123')1706    def for_bar_foo():1707        return flask.request.endpoint17081709    with app.test_request_context():1710        assert flask.url_for('foo') == '/foo/'1711        assert flask.url_for('bar') == '/bar/'1712        assert flask.url_for('123') == '/bar/123'17131714    assert client.get('/foo/').data == b'foo'1715    assert client.get('/bar/').data == b'bar'1716    assert client.get('/bar/123').data == b'123'171717181719def test_preserve_only_once(app, client):1720    app.debug = True17211722    @app.route('/fail')1723    def fail_func():1724        1 // 017251726    for x in range(3):1727        with pytest.raises(ZeroDivisionError):1728            client.get('/fail')17291730    assert flask._request_ctx_stack.top is not None1731    assert flask._app_ctx_stack.top is not None1732    # implicit appctx disappears too1733    flask._request_ctx_stack.top.pop()1734    assert flask._request_ctx_stack.top is None1735    assert flask._app_ctx_stack.top is None173617371738def test_preserve_remembers_exception(app, client):1739    app.debug = True1740    errors = []17411742    @app.route('/fail')1743    def fail_func():1744        1 // 017451746    @app.route('/success')1747    def success_func():1748        return 'Okay'17491750    @app.teardown_request1751    def teardown_handler(exc):1752        errors.append(exc)17531754    # After this failure we did not yet call the teardown handler1755    with pytest.raises(ZeroDivisionError):1756        client.get('/fail')1757    assert errors == []17581759    # But this request triggers it, and it's an error1760    client.get('/success')1761    assert len(errors) == 21762    assert isinstance(errors[0], ZeroDivisionError)17631764    # At this point another request does nothing.1765    client.get('/success')1766    assert len(errors) == 31767    assert errors[1] is None176817691770def test_get_method_on_g(app_ctx):1771    assert flask.g.get('x') is None1772    assert flask.g.get('x', 11) == 111773    flask.g.x = 421774    assert flask.g.get('x') == 421775    assert flask.g.x == 42177617771778def test_g_iteration_protocol(app_ctx):1779    flask.g.foo = 231780    flask.g.bar = 421781    assert 'foo' in flask.g1782    assert 'foos' not in flask.g1783    assert sorted(flask.g) == ['bar', 'foo']178417851786def test_subdomain_basic_support(app, client):1787    app.config['SERVER_NAME'] = 'localhost.localdomain'17881789    @app.route('/')1790    def normal_index():1791        return 'normal index'17921793    @app.route('/', subdomain='test')1794    def test_index():1795        return 'test index'17961797    rv = client.get('/', 'http://localhost.localdomain/')1798    assert rv.data == b'normal index'17991800    rv = client.get('/', 'http://test.localhost.localdomain/')1801    assert rv.data == b'test index'180218031804def test_subdomain_matching(app, client):1805    app.config['SERVER_NAME'] = 'localhost.localdomain'18061807    @app.route('/', subdomain='<user>')1808    def index(user):1809        return 'index for %s' % user18101811    rv = client.get('/', 'http://mitsuhiko.localhost.localdomain/')1812    assert rv.data == b'index for mitsuhiko'181318141815def test_subdomain_matching_with_ports(app, client):1816    app.config['SERVER_NAME'] = 'localhost.localdomain:3000'18171818    @app.route('/', subdomain='<user>')1819    def index(user):1820        return 'index for %s' % user18211822    rv = client.get('/', 'http://mitsuhiko.localhost.localdomain:3000/')1823    assert rv.data == b'index for mitsuhiko'182418251826def test_multi_route_rules(app, client):1827    @app.route('/')1828    @app.route('/<test>/')1829    def index(test='a'):1830        return test18311832    rv = client.open('/')1833    assert rv.data == b'a'1834    rv = client.open('/b/')1835    assert rv.data == b'b'183618371838def test_multi_route_class_views(app, client):1839    class View(object):1840        def __init__(self, app):1841            app.add_url_rule('/', 'index', self.index)1842            app.add_url_rule('/<test>/', 'index', self.index)18431844        def index(self, test='a'):1845            return test18461847    _ = View(app)1848    rv = client.open('/')1849    assert rv.data == b'a'1850    rv = client.open('/b/')1851    assert rv.data == b'b'185218531854def test_run_defaults(monkeypatch, app):1855    rv = {}18561857    # Mocks werkzeug.serving.run_simple method1858    def run_simple_mock(*args, **kwargs):1859        rv['result'] = 'running...'18601861    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1862    app.run()1863    assert rv['result'] == 'running...'186418651866def test_run_server_port(monkeypatch, app):1867    rv = {}18681869    # Mocks werkzeug.serving.run_simple method1870    def run_simple_mock(hostname, port, application, *args, **kwargs):1871        rv['result'] = 'running on %s:%s ...' % (hostname, port)18721873    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1874    hostname, port = 'localhost', 80001875    app.run(hostname, port, debug=True)1876    assert rv['result'] == 'running on %s:%s ...' % (hostname, port)187718781879@pytest.mark.parametrize('host,port,expect_host,expect_port', (1880        (None, None, 'pocoo.org', 8080),1881        ('localhost', None, 'localhost', 8080),1882        (None, 80, 'pocoo.org', 80),1883        ('localhost', 80, 'localhost', 80),1884))1885def test_run_from_config(monkeypatch, host, port, expect_host, expect_port, app):1886    def run_simple_mock(hostname, port, *args, **kwargs):1887        assert hostname == expect_host1888        assert port == expect_port18891890    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1891    app.config['SERVER_NAME'] = 'pocoo.org:8080'1892    app.run(host, port)