Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

1,919 lines · 51.1 KiB · Python

Last changed by

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

History of this file

Take 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('/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():1433    app = flask.Flask(__name__, subdomain_matching=True)1434    app.config.update(1435        SERVER_NAME='localhost.localdomain:5000'1436    )1437    client = app.test_client()14381439    @app.route('/')1440    def index():1441        return 'Foo'14421443    @app.route('/', subdomain='foo')1444    def subdomain():1445        return 'Foo SubDomain'14461447    rv = client.get('/')1448    assert rv.data == b'Foo'14491450    rv = client.get('/', 'http://localhost.localdomain:5000')1451    assert rv.data == b'Foo'14521453    rv = client.get('/', 'https://localhost.localdomain:5000')1454    assert rv.data == b'Foo'14551456    app.config.update(SERVER_NAME='localhost.localdomain')1457    rv = client.get('/', 'https://localhost.localdomain')1458    assert rv.data == b'Foo'14591460    try:1461        app.config.update(SERVER_NAME='localhost.localdomain:443')1462        rv = client.get('/', 'https://localhost.localdomain')1463        # Werkzeug 0.81464        assert rv.status_code == 4041465    except ValueError as e:1466        # Werkzeug 0.71467        assert str(e) == (1468            "the server name provided "1469            "('localhost.localdomain:443') does not match the "1470            "server name from the WSGI environment ('localhost.localdomain')"1471        )14721473    try:1474        app.config.update(SERVER_NAME='localhost.localdomain')1475        rv = client.get('/', 'http://foo.localhost')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') does not match the "1483            "server name from the WSGI environment ('foo.localhost')"1484        )14851486    rv = client.get('/', 'http://foo.localhost.localdomain')1487    assert rv.data == b'Foo SubDomain'148814891490def test_exception_propagation(app, client):1491    def apprunner(config_key):14921493        @app.route('/')1494        def index():1495            1 // 014961497        if config_key is not None:1498            app.config[config_key] = True1499            with pytest.raises(Exception):1500                client.get('/')1501        else:1502            assert client.get('/').status_code == 50015031504    # we have to run this test in an isolated thread because if the1505    # debug flag is set to true and an exception happens the context is1506    # not torn down.  This causes other tests that run after this fail1507    # when they expect no exception on the stack.1508    for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None:1509        t = Thread(target=apprunner, args=(config_key,))1510        t.start()1511        t.join()151215131514@pytest.mark.parametrize('debug', [True, False])1515@pytest.mark.parametrize('use_debugger', [True, False])1516@pytest.mark.parametrize('use_reloader', [True, False])1517@pytest.mark.parametrize('propagate_exceptions', [None, True, False])1518def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1519                                     use_reloader, propagate_exceptions, app):1520    rv = {}15211522    # Mocks werkzeug.serving.run_simple method1523    def run_simple_mock(*args, **kwargs):1524        rv['passthrough_errors'] = kwargs.get('passthrough_errors')15251526    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1527    app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1528    app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)152915301531def test_max_content_length(app, client):1532    app.config['MAX_CONTENT_LENGTH'] = 6415331534    @app.before_request1535    def always_first():1536        flask.request.form['myfile']1537        assert False15381539    @app.route('/accept', methods=['POST'])1540    def accept_file():1541        flask.request.form['myfile']1542        assert False15431544    @app.errorhandler(413)1545    def catcher(error):1546        return '42'15471548    rv = client.post('/accept', data={'myfile': 'foo' * 100})1549    assert rv.data == b'42'155015511552def test_url_processors(app, client):15531554    @app.url_defaults1555    def add_language_code(endpoint, values):1556        if flask.g.lang_code is not None and \1557                app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1558            values.setdefault('lang_code', flask.g.lang_code)15591560    @app.url_value_preprocessor1561    def pull_lang_code(endpoint, values):1562        flask.g.lang_code = values.pop('lang_code', None)15631564    @app.route('/<lang_code>/')1565    def index():1566        return flask.url_for('about')15671568    @app.route('/<lang_code>/about')1569    def about():1570        return flask.url_for('something_else')15711572    @app.route('/foo')1573    def something_else():1574        return flask.url_for('about', lang_code='en')15751576    assert client.get('/de/').data == b'/de/about'1577    assert client.get('/de/about').data == b'/foo'1578    assert client.get('/foo').data == b'/en/about'157915801581def test_inject_blueprint_url_defaults(app):1582    bp = flask.Blueprint('foo.bar.baz', __name__,1583                         template_folder='template')15841585    @bp.url_defaults1586    def bp_defaults(endpoint, values):1587        values['page'] = 'login'15881589    @bp.route('/<page>')1590    def view(page):1591        pass15921593    app.register_blueprint(bp)15941595    values = dict()1596    app.inject_url_defaults('foo.bar.baz.view', values)1597    expected = dict(page='login')1598    assert values == expected15991600    with app.test_request_context('/somepage'):1601        url = flask.url_for('foo.bar.baz.view')1602    expected = '/login'1603    assert url == expected160416051606def test_nonascii_pathinfo(app, client):1607    @app.route(u'/киртест')1608    def index():1609        return 'Hello World!'16101611    rv = client.get(u'/киртест')1612    assert rv.data == b'Hello World!'161316141615def test_debug_mode_complains_after_first_request(app, client):1616    app.debug = True16171618    @app.route('/')1619    def index():1620        return 'Awesome'16211622    assert not app.got_first_request1623    assert client.get('/').data == b'Awesome'1624    with pytest.raises(AssertionError) as e:1625        @app.route('/foo')1626        def broken():1627            return 'Meh'1628    assert 'A setup function was called' in str(e)16291630    app.debug = False16311632    @app.route('/foo')1633    def working():1634        return 'Meh'16351636    assert client.get('/foo').data == b'Meh'1637    assert app.got_first_request163816391640def test_before_first_request_functions(app, client):1641    got = []16421643    @app.before_first_request1644    def foo():1645        got.append(42)16461647    client.get('/')1648    assert got == [42]1649    client.get('/')1650    assert got == [42]1651    assert app.got_first_request165216531654def test_before_first_request_functions_concurrent(app, client):1655    got = []16561657    @app.before_first_request1658    def foo():1659        time.sleep(0.2)1660        got.append(42)16611662    def get_and_assert():1663        client.get("/")1664        assert got == [42]16651666    t = Thread(target=get_and_assert)1667    t.start()1668    get_and_assert()1669    t.join()1670    assert app.got_first_request167116721673def test_routing_redirect_debugging(app, client):1674    app.debug = True16751676    @app.route('/foo/', methods=['GET', 'POST'])1677    def foo():1678        return 'success'16791680    with client:1681        with pytest.raises(AssertionError) as e:1682            client.post('/foo', data={})1683        assert 'http://localhost/foo/' in str(e)1684        assert ('Make sure to directly send '1685                'your POST-request to this URL') in str(e)16861687        rv = client.get('/foo', data={}, follow_redirects=True)1688        assert rv.data == b'success'16891690    app.debug = False1691    with client:1692        rv = client.post('/foo', data={}, follow_redirects=True)1693        assert rv.data == b'success'169416951696def test_route_decorator_custom_endpoint(app, client):1697    app.debug = True16981699    @app.route('/foo/')1700    def foo():1701        return flask.request.endpoint17021703    @app.route('/bar/', endpoint='bar')1704    def for_bar():1705        return flask.request.endpoint17061707    @app.route('/bar/123', endpoint='123')1708    def for_bar_foo():1709        return flask.request.endpoint17101711    with app.test_request_context():1712        assert flask.url_for('foo') == '/foo/'1713        assert flask.url_for('bar') == '/bar/'1714        assert flask.url_for('123') == '/bar/123'17151716    assert client.get('/foo/').data == b'foo'1717    assert client.get('/bar/').data == b'bar'1718    assert client.get('/bar/123').data == b'123'171917201721def test_preserve_only_once(app, client):1722    app.debug = True17231724    @app.route('/fail')1725    def fail_func():1726        1 // 017271728    for x in range(3):1729        with pytest.raises(ZeroDivisionError):1730            client.get('/fail')17311732    assert flask._request_ctx_stack.top is not None1733    assert flask._app_ctx_stack.top is not None1734    # implicit appctx disappears too1735    flask._request_ctx_stack.top.pop()1736    assert flask._request_ctx_stack.top is None1737    assert flask._app_ctx_stack.top is None173817391740def test_preserve_remembers_exception(app, client):1741    app.debug = True1742    errors = []17431744    @app.route('/fail')1745    def fail_func():1746        1 // 017471748    @app.route('/success')1749    def success_func():1750        return 'Okay'17511752    @app.teardown_request1753    def teardown_handler(exc):1754        errors.append(exc)17551756    # After this failure we did not yet call the teardown handler1757    with pytest.raises(ZeroDivisionError):1758        client.get('/fail')1759    assert errors == []17601761    # But this request triggers it, and it's an error1762    client.get('/success')1763    assert len(errors) == 21764    assert isinstance(errors[0], ZeroDivisionError)17651766    # At this point another request does nothing.1767    client.get('/success')1768    assert len(errors) == 31769    assert errors[1] is None177017711772def test_get_method_on_g(app_ctx):1773    assert flask.g.get('x') is None1774    assert flask.g.get('x', 11) == 111775    flask.g.x = 421776    assert flask.g.get('x') == 421777    assert flask.g.x == 42177817791780def test_g_iteration_protocol(app_ctx):1781    flask.g.foo = 231782    flask.g.bar = 421783    assert 'foo' in flask.g1784    assert 'foos' not in flask.g1785    assert sorted(flask.g) == ['bar', 'foo']178617871788def test_subdomain_basic_support():1789    app = flask.Flask(__name__, subdomain_matching=True)1790    app.config['SERVER_NAME'] = 'localhost.localdomain'1791    client = app.test_client()17921793    @app.route('/')1794    def normal_index():1795        return 'normal index'17961797    @app.route('/', subdomain='test')1798    def test_index():1799        return 'test index'18001801    rv = client.get('/', 'http://localhost.localdomain/')1802    assert rv.data == b'normal index'18031804    rv = client.get('/', 'http://test.localhost.localdomain/')1805    assert rv.data == b'test index'180618071808def test_subdomain_matching():1809    app = flask.Flask(__name__, subdomain_matching=True)1810    client = app.test_client()1811    app.config['SERVER_NAME'] = 'localhost.localdomain'18121813    @app.route('/', subdomain='<user>')1814    def index(user):1815        return 'index for %s' % user18161817    rv = client.get('/', 'http://mitsuhiko.localhost.localdomain/')1818    assert rv.data == b'index for mitsuhiko'181918201821def test_subdomain_matching_with_ports():1822    app = flask.Flask(__name__, subdomain_matching=True)1823    app.config['SERVER_NAME'] = 'localhost.localdomain:3000'1824    client = app.test_client()18251826    @app.route('/', subdomain='<user>')1827    def index(user):1828        return 'index for %s' % user18291830    rv = client.get('/', 'http://mitsuhiko.localhost.localdomain:3000/')1831    assert rv.data == b'index for mitsuhiko'183218331834@pytest.mark.parametrize('matching', (False, True))1835def test_subdomain_matching_other_name(matching):1836    app = flask.Flask(__name__, subdomain_matching=matching)1837    app.config['SERVER_NAME'] = 'localhost.localdomain:3000'1838    client = app.test_client()18391840    @app.route('/')1841    def index():1842        return '', 20418431844    # ip address can't match name1845    rv = client.get('/', 'http://127.0.0.1:3000/')1846    assert rv.status_code == 404 if matching else 20418471848    # allow all subdomains if matching is disabled1849    rv = client.get('/', 'http://www.localhost.localdomain:3000/')1850    assert rv.status_code == 404 if matching else 204185118521853def test_multi_route_rules(app, client):1854    @app.route('/')1855    @app.route('/<test>/')1856    def index(test='a'):1857        return test18581859    rv = client.open('/')1860    assert rv.data == b'a'1861    rv = client.open('/b/')1862    assert rv.data == b'b'186318641865def test_multi_route_class_views(app, client):1866    class View(object):1867        def __init__(self, app):1868            app.add_url_rule('/', 'index', self.index)1869            app.add_url_rule('/<test>/', 'index', self.index)18701871        def index(self, test='a'):1872            return test18731874    _ = View(app)1875    rv = client.open('/')1876    assert rv.data == b'a'1877    rv = client.open('/b/')1878    assert rv.data == b'b'187918801881def test_run_defaults(monkeypatch, app):1882    rv = {}18831884    # Mocks werkzeug.serving.run_simple method1885    def run_simple_mock(*args, **kwargs):1886        rv['result'] = 'running...'18871888    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1889    app.run()1890    assert rv['result'] == 'running...'189118921893def test_run_server_port(monkeypatch, app):1894    rv = {}18951896    # Mocks werkzeug.serving.run_simple method1897    def run_simple_mock(hostname, port, application, *args, **kwargs):1898        rv['result'] = 'running on %s:%s ...' % (hostname, port)18991900    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1901    hostname, port = 'localhost', 80001902    app.run(hostname, port, debug=True)1903    assert rv['result'] == 'running on %s:%s ...' % (hostname, port)190419051906@pytest.mark.parametrize('host,port,expect_host,expect_port', (1907        (None, None, 'pocoo.org', 8080),1908        ('localhost', None, 'localhost', 8080),1909        (None, 80, 'pocoo.org', 80),1910        ('localhost', 80, 'localhost', 80),1911))1912def test_run_from_config(monkeypatch, host, port, expect_host, expect_port, app):1913    def run_simple_mock(hostname, port, *args, **kwargs):1914        assert hostname == expect_host1915        assert port == expect_port19161917    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1918    app.config['SERVER_NAME'] = 'pocoo.org:8080'1919    app.run(host, port)