Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

1,863 lines · 49.4 KiB · Python

Last changed by

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

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_PATH='/'323    )324325    @app.route('/')326    def index():327        flask.session['testing'] = 42328        return 'Hello World'329330    rv = client.get('/', 'http://www.example.com:8080/test/')331    cookie = rv.headers['set-cookie'].lower()332    assert 'domain=.example.com' in cookie333    assert 'path=/' in cookie334    assert 'secure' in cookie335    assert 'httponly' not in cookie336337338def test_session_localhost_warning(recwarn, app, client):339    app.config.update(340        SERVER_NAME='localhost:5000',341    )342343    @app.route('/')344    def index():345        flask.session['testing'] = 42346        return 'testing'347348    rv = client.get('/', 'http://localhost:5000/')349    assert 'domain' not in rv.headers['set-cookie'].lower()350    w = recwarn.pop(UserWarning)351    assert '"localhost" is not a valid cookie domain' in str(w.message)352353354def test_session_ip_warning(recwarn, app, client):355    app.config.update(356        SERVER_NAME='127.0.0.1:5000',357    )358359    @app.route('/')360    def index():361        flask.session['testing'] = 42362        return 'testing'363364    rv = client.get('/', 'http://127.0.0.1:5000/')365    assert 'domain=127.0.0.1' in rv.headers['set-cookie'].lower()366    w = recwarn.pop(UserWarning)367    assert 'cookie domain is an IP' in str(w.message)368369370def test_missing_session(app):371    app.secret_key = None372373    def expect_exception(f, *args, **kwargs):374        e = pytest.raises(RuntimeError, f, *args, **kwargs)375        assert e.value.args and 'session is unavailable' in e.value.args[0]376377    with app.test_request_context():378        assert flask.session.get('missing_key') is None379        expect_exception(flask.session.__setitem__, 'foo', 42)380        expect_exception(flask.session.pop, 'foo')381382383def test_session_expiration(app, client):384    permanent = True385386    @app.route('/')387    def index():388        flask.session['test'] = 42389        flask.session.permanent = permanent390        return ''391392    @app.route('/test')393    def test():394        return text_type(flask.session.permanent)395396    rv = client.get('/')397    assert 'set-cookie' in rv.headers398    match = re.search(r'(?i)\bexpires=([^;]+)', rv.headers['set-cookie'])399    expires = parse_date(match.group())400    expected = datetime.utcnow() + app.permanent_session_lifetime401    assert expires.year == expected.year402    assert expires.month == expected.month403    assert expires.day == expected.day404405    rv = client.get('/test')406    assert rv.data == b'True'407408    permanent = False409    rv = client.get('/')410    assert 'set-cookie' in rv.headers411    match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])412    assert match is None413414415def test_session_stored_last(app, client):416    @app.after_request417    def modify_session(response):418        flask.session['foo'] = 42419        return response420421    @app.route('/')422    def dump_session_contents():423        return repr(flask.session.get('foo'))424425    assert client.get('/').data == b'None'426    assert client.get('/').data == b'42'427428429def test_session_special_types(app, client):430    now = datetime.utcnow().replace(microsecond=0)431    the_uuid = uuid.uuid4()432433    @app.route('/')434    def dump_session_contents():435        flask.session['t'] = (1, 2, 3)436        flask.session['b'] = b'\xff'437        flask.session['m'] = flask.Markup('<html>')438        flask.session['u'] = the_uuid439        flask.session['d'] = now440        flask.session['t_tag'] = {' t': 'not-a-tuple'}441        flask.session['di_t_tag'] = {' t__': 'not-a-tuple'}442        flask.session['di_tag'] = {' di': 'not-a-dict'}443        return '', 204444445    with client:446        client.get('/')447        s = flask.session448        assert s['t'] == (1, 2, 3)449        assert type(s['b']) == bytes450        assert s['b'] == b'\xff'451        assert type(s['m']) == flask.Markup452        assert s['m'] == flask.Markup('<html>')453        assert s['u'] == the_uuid454        assert s['d'] == now455        assert s['t_tag'] == {' t': 'not-a-tuple'}456        assert s['di_t_tag'] == {' t__': 'not-a-tuple'}457        assert s['di_tag'] == {' di': 'not-a-dict'}458459460def test_session_cookie_setting(app):461    is_permanent = True462463    @app.route('/bump')464    def bump():465        rv = flask.session['foo'] = flask.session.get('foo', 0) + 1466        flask.session.permanent = is_permanent467        return str(rv)468469    @app.route('/read')470    def read():471        return str(flask.session.get('foo', 0))472473    def run_test(expect_header):474        with app.test_client() as c:475            assert c.get('/bump').data == b'1'476            assert c.get('/bump').data == b'2'477            assert c.get('/bump').data == b'3'478479            rv = c.get('/read')480            set_cookie = rv.headers.get('set-cookie')481            assert (set_cookie is not None) == expect_header482            assert rv.data == b'3'483484    is_permanent = True485    app.config['SESSION_REFRESH_EACH_REQUEST'] = True486    run_test(expect_header=True)487488    is_permanent = True489    app.config['SESSION_REFRESH_EACH_REQUEST'] = False490    run_test(expect_header=False)491492    is_permanent = False493    app.config['SESSION_REFRESH_EACH_REQUEST'] = True494    run_test(expect_header=False)495496    is_permanent = False497    app.config['SESSION_REFRESH_EACH_REQUEST'] = False498    run_test(expect_header=False)499500501def test_session_vary_cookie(app, client):502    @app.route('/set')503    def set_session():504        flask.session['test'] = 'test'505        return ''506507    @app.route('/get')508    def get():509        return flask.session.get('test')510511    @app.route('/getitem')512    def getitem():513        return flask.session['test']514515    @app.route('/setdefault')516    def setdefault():517        return flask.session.setdefault('test', 'default')518519    @app.route('/vary-cookie-header-set')520    def vary_cookie_header_set():521        response = flask.Response()522        response.vary.add('Cookie')523        flask.session['test'] = 'test'524        return response525526    @app.route('/vary-header-set')527    def vary_header_set():528        response = flask.Response()529        response.vary.update(('Accept-Encoding', 'Accept-Language'))530        flask.session['test'] = 'test'531        return response532533    @app.route('/no-vary-header')534    def no_vary_header():535        return ''536537    def expect(path, header_value='Cookie'):538        rv = client.get(path)539540        if header_value:541            # The 'Vary' key should exist in the headers only once.542            assert len(rv.headers.get_all('Vary')) == 1543            assert rv.headers['Vary'] == header_value544        else:545            assert 'Vary' not in rv.headers546547    expect('/set')548    expect('/get')549    expect('/getitem')550    expect('/setdefault')551    expect('/vary-cookie-header-set')552    expect('/vary-header-set', 'Accept-Encoding, Accept-Language, Cookie')553    expect('/no-vary-header', None)554555556def test_flashes(app, req_ctx):557    assert not flask.session.modified558    flask.flash('Zap')559    flask.session.modified = False560    flask.flash('Zip')561    assert flask.session.modified562    assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']563564565def test_extended_flashing(app):566    # Be sure app.testing=True below, else tests can fail silently.567    #568    # Specifically, if app.testing is not set to True, the AssertionErrors569    # in the view functions will cause a 500 response to the test client570    # instead of propagating exceptions.571572    @app.route('/')573    def index():574        flask.flash(u'Hello World')575        flask.flash(u'Hello World', 'error')576        flask.flash(flask.Markup(u'<em>Testing</em>'), 'warning')577        return ''578579    @app.route('/test/')580    def test():581        messages = flask.get_flashed_messages()582        assert list(messages) == [583            u'Hello World',584            u'Hello World',585            flask.Markup(u'<em>Testing</em>')586        ]587        return ''588589    @app.route('/test_with_categories/')590    def test_with_categories():591        messages = flask.get_flashed_messages(with_categories=True)592        assert len(messages) == 3593        assert list(messages) == [594            ('message', u'Hello World'),595            ('error', u'Hello World'),596            ('warning', flask.Markup(u'<em>Testing</em>'))597        ]598        return ''599600    @app.route('/test_filter/')601    def test_filter():602        messages = flask.get_flashed_messages(603            category_filter=['message'], with_categories=True)604        assert list(messages) == [('message', u'Hello World')]605        return ''606607    @app.route('/test_filters/')608    def test_filters():609        messages = flask.get_flashed_messages(610            category_filter=['message', 'warning'], with_categories=True)611        assert list(messages) == [612            ('message', u'Hello World'),613            ('warning', flask.Markup(u'<em>Testing</em>'))614        ]615        return ''616617    @app.route('/test_filters_without_returning_categories/')618    def test_filters2():619        messages = flask.get_flashed_messages(620            category_filter=['message', 'warning'])621        assert len(messages) == 2622        assert messages[0] == u'Hello World'623        assert messages[1] == flask.Markup(u'<em>Testing</em>')624        return ''625626    # Create new test client on each test to clean flashed messages.627628    client = app.test_client()629    client.get('/')630    client.get('/test_with_categories/')631632    client = app.test_client()633    client.get('/')634    client.get('/test_filter/')635636    client = app.test_client()637    client.get('/')638    client.get('/test_filters/')639640    client = app.test_client()641    client.get('/')642    client.get('/test_filters_without_returning_categories/')643644645def test_request_processing(app, client):646    evts = []647648    @app.before_request649    def before_request():650        evts.append('before')651652    @app.after_request653    def after_request(response):654        response.data += b'|after'655        evts.append('after')656        return response657658    @app.route('/')659    def index():660        assert 'before' in evts661        assert 'after' not in evts662        return 'request'663664    assert 'after' not in evts665    rv = client.get('/').data666    assert 'after' in evts667    assert rv == b'request|after'668669670def test_request_preprocessing_early_return(app, client):671    evts = []672673    @app.before_request674    def before_request1():675        evts.append(1)676677    @app.before_request678    def before_request2():679        evts.append(2)680        return "hello"681682    @app.before_request683    def before_request3():684        evts.append(3)685        return "bye"686687    @app.route('/')688    def index():689        evts.append('index')690        return "damnit"691692    rv = client.get('/').data.strip()693    assert rv == b'hello'694    assert evts == [1, 2]695696697def test_after_request_processing(app, client):698    @app.route('/')699    def index():700        @flask.after_this_request701        def foo(response):702            response.headers['X-Foo'] = 'a header'703            return response704705        return 'Test'706707    resp = client.get('/')708    assert resp.status_code == 200709    assert resp.headers['X-Foo'] == 'a header'710711712def test_teardown_request_handler(app, client):713    called = []714715    @app.teardown_request716    def teardown_request(exc):717        called.append(True)718        return "Ignored"719720    @app.route('/')721    def root():722        return "Response"723724    rv = client.get('/')725    assert rv.status_code == 200726    assert b'Response' in rv.data727    assert len(called) == 1728729730def test_teardown_request_handler_debug_mode(app, client):731    called = []732733    @app.teardown_request734    def teardown_request(exc):735        called.append(True)736        return "Ignored"737738    @app.route('/')739    def root():740        return "Response"741742    rv = client.get('/')743    assert rv.status_code == 200744    assert b'Response' in rv.data745    assert len(called) == 1746747748def test_teardown_request_handler_error(app, client):749    called = []750    app.testing = False751752    @app.teardown_request753    def teardown_request1(exc):754        assert type(exc) == ZeroDivisionError755        called.append(True)756        # This raises a new error and blows away sys.exc_info(), so we can757        # test that all teardown_requests get passed the same original758        # exception.759        try:760            raise TypeError()761        except:762            pass763764    @app.teardown_request765    def teardown_request2(exc):766        assert type(exc) == ZeroDivisionError767        called.append(True)768        # This raises a new error and blows away sys.exc_info(), so we can769        # test that all teardown_requests get passed the same original770        # exception.771        try:772            raise TypeError()773        except:774            pass775776    @app.route('/')777    def fails():778        1 // 0779780    rv = client.get('/')781    assert rv.status_code == 500782    assert b'Internal Server Error' in rv.data783    assert len(called) == 2784785786def test_before_after_request_order(app, client):787    called = []788789    @app.before_request790    def before1():791        called.append(1)792793    @app.before_request794    def before2():795        called.append(2)796797    @app.after_request798    def after1(response):799        called.append(4)800        return response801802    @app.after_request803    def after2(response):804        called.append(3)805        return response806807    @app.teardown_request808    def finish1(exc):809        called.append(6)810811    @app.teardown_request812    def finish2(exc):813        called.append(5)814815    @app.route('/')816    def index():817        return '42'818819    rv = client.get('/')820    assert rv.data == b'42'821    assert called == [1, 2, 3, 4, 5, 6]822823824def test_error_handling(app, client):825    app.testing = False826827    @app.errorhandler(404)828    def not_found(e):829        return 'not found', 404830831    @app.errorhandler(500)832    def internal_server_error(e):833        return 'internal server error', 500834835    @app.errorhandler(Forbidden)836    def forbidden(e):837        return 'forbidden', 403838839    @app.route('/')840    def index():841        flask.abort(404)842843    @app.route('/error')844    def error():845        1 // 0846847    @app.route('/forbidden')848    def error2():849        flask.abort(403)850851    rv = client.get('/')852    assert rv.status_code == 404853    assert rv.data == b'not found'854    rv = client.get('/error')855    assert rv.status_code == 500856    assert b'internal server error' == rv.data857    rv = client.get('/forbidden')858    assert rv.status_code == 403859    assert b'forbidden' == rv.data860861862def test_error_handler_unknown_code(app):863    with pytest.raises(KeyError) as exc_info:864        app.register_error_handler(999, lambda e: ('999', 999))865866    assert 'Use a subclass' in exc_info.value.args[0]867868869def test_error_handling_processing(app, client):870    app.testing = False871872    @app.errorhandler(500)873    def internal_server_error(e):874        return 'internal server error', 500875876    @app.route('/')877    def broken_func():878        1 // 0879880    @app.after_request881    def after_request(resp):882        resp.mimetype = 'text/x-special'883        return resp884885    resp = client.get('/')886    assert resp.mimetype == 'text/x-special'887    assert resp.data == b'internal server error'888889890def test_baseexception_error_handling(app, client):891    app.testing = False892893    @app.route('/')894    def broken_func():895        raise KeyboardInterrupt()896897    with pytest.raises(KeyboardInterrupt):898        client.get('/')899900        ctx = flask._request_ctx_stack.top901        assert ctx.preserved902        assert type(ctx._preserved_exc) is KeyboardInterrupt903904905def test_before_request_and_routing_errors(app, client):906    @app.before_request907    def attach_something():908        flask.g.something = 'value'909910    @app.errorhandler(404)911    def return_something(error):912        return flask.g.something, 404913914    rv = client.get('/')915    assert rv.status_code == 404916    assert rv.data == b'value'917918919def test_user_error_handling(app, client):920    class MyException(Exception):921        pass922923    @app.errorhandler(MyException)924    def handle_my_exception(e):925        assert isinstance(e, MyException)926        return '42'927928    @app.route('/')929    def index():930        raise MyException()931932    assert client.get('/').data == b'42'933934935def test_http_error_subclass_handling(app, client):936    class ForbiddenSubclass(Forbidden):937        pass938939    @app.errorhandler(ForbiddenSubclass)940    def handle_forbidden_subclass(e):941        assert isinstance(e, ForbiddenSubclass)942        return 'banana'943944    @app.errorhandler(403)945    def handle_forbidden_subclass(e):946        assert not isinstance(e, ForbiddenSubclass)947        assert isinstance(e, Forbidden)948        return 'apple'949950    @app.route('/1')951    def index1():952        raise ForbiddenSubclass()953954    @app.route('/2')955    def index2():956        flask.abort(403)957958    @app.route('/3')959    def index3():960        raise Forbidden()961962    assert client.get('/1').data == b'banana'963    assert client.get('/2').data == b'apple'964    assert client.get('/3').data == b'apple'965966967def test_errorhandler_precedence(app, client):968    class E1(Exception):969        pass970971    class E2(Exception):972        pass973974    class E3(E1, E2):975        pass976977    @app.errorhandler(E2)978    def handle_e2(e):979        return 'E2'980981    @app.errorhandler(Exception)982    def handle_exception(e):983        return 'Exception'984985    @app.route('/E1')986    def raise_e1():987        raise E1988989    @app.route('/E3')990    def raise_e3():991        raise E3992993    rv = client.get('/E1')994    assert rv.data == b'Exception'995996    rv = client.get('/E3')997    assert rv.data == b'E2'9989991000def test_trapping_of_bad_request_key_errors(app, client):1001    @app.route('/fail')1002    def fail():1003        flask.request.form['missing_key']10041005    rv = client.get('/fail')1006    assert rv.status_code == 4001007    assert b'missing_key' not in rv.data10081009    app.config['TRAP_BAD_REQUEST_ERRORS'] = True10101011    with pytest.raises(KeyError) as e:1012        client.get("/fail")10131014    assert e.errisinstance(BadRequest)1015    assert 'missing_key' in e.value.description101610171018def test_trapping_of_all_http_exceptions(app, client):1019    app.config['TRAP_HTTP_EXCEPTIONS'] = True10201021    @app.route('/fail')1022    def fail():1023        flask.abort(404)10241025    with pytest.raises(NotFound):1026        client.get('/fail')102710281029def test_error_handler_after_processor_error(app, client):1030    app.testing = False10311032    @app.before_request1033    def before_request():1034        if trigger == 'before':1035            1 // 010361037    @app.after_request1038    def after_request(response):1039        if trigger == 'after':1040            1 // 01041        return response10421043    @app.route('/')1044    def index():1045        return 'Foo'10461047    @app.errorhandler(500)1048    def internal_server_error(e):1049        return 'Hello Server Error', 50010501051    for trigger in 'before', 'after':1052        rv = client.get('/')1053        assert rv.status_code == 5001054        assert rv.data == b'Hello Server Error'105510561057def test_enctype_debug_helper(app, client):1058    from flask.debughelpers import DebugFilesKeyError1059    app.debug = True10601061    @app.route('/fail', methods=['POST'])1062    def index():1063        return flask.request.files['foo'].filename10641065    # with statement is important because we leave an exception on the1066    # stack otherwise and we want to ensure that this is not the case1067    # to not negatively affect other tests.1068    with client:1069        with pytest.raises(DebugFilesKeyError) as e:1070            client.post('/fail', data={'foo': 'index.txt'})1071        assert 'no file contents were transmitted' in str(e.value)1072        assert 'This was submitted: "index.txt"' in str(e.value)107310741075def test_response_types(app, client):1076    @app.route('/text')1077    def from_text():1078        return u'Hällo Wörld'10791080    @app.route('/bytes')1081    def from_bytes():1082        return u'Hällo Wörld'.encode('utf-8')10831084    @app.route('/full_tuple')1085    def from_full_tuple():1086        return 'Meh', 400, {1087            'X-Foo': 'Testing',1088            'Content-Type': 'text/plain; charset=utf-8'1089        }10901091    @app.route('/text_headers')1092    def from_text_headers():1093        return 'Hello', {1094            'X-Foo': 'Test',1095            'Content-Type': 'text/plain; charset=utf-8'1096        }10971098    @app.route('/text_status')1099    def from_text_status():1100        return 'Hi, status!', 40011011102    @app.route('/response_headers')1103    def from_response_headers():1104        return flask.Response('Hello world', 404, {'X-Foo': 'Baz'}), {1105            "X-Foo": "Bar",1106            "X-Bar": "Foo"1107        }11081109    @app.route('/response_status')1110    def from_response_status():1111        return app.response_class('Hello world', 400), 50011121113    @app.route('/wsgi')1114    def from_wsgi():1115        return NotFound()11161117    assert client.get('/text').data == u'Hällo Wörld'.encode('utf-8')1118    assert client.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')11191120    rv = client.get('/full_tuple')1121    assert rv.data == b'Meh'1122    assert rv.headers['X-Foo'] == 'Testing'1123    assert rv.status_code == 4001124    assert rv.mimetype == 'text/plain'11251126    rv = client.get('/text_headers')1127    assert rv.data == b'Hello'1128    assert rv.headers['X-Foo'] == 'Test'1129    assert rv.status_code == 2001130    assert rv.mimetype == 'text/plain'11311132    rv = client.get('/text_status')1133    assert rv.data == b'Hi, status!'1134    assert rv.status_code == 4001135    assert rv.mimetype == 'text/html'11361137    rv = client.get('/response_headers')1138    assert rv.data == b'Hello world'1139    assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar']1140    assert rv.headers['X-Bar'] == 'Foo'1141    assert rv.status_code == 40411421143    rv = client.get('/response_status')1144    assert rv.data == b'Hello world'1145    assert rv.status_code == 50011461147    rv = client.get('/wsgi')1148    assert b'Not Found' in rv.data1149    assert rv.status_code == 404115011511152def test_response_type_errors():1153    app = flask.Flask(__name__)1154    app.testing = True11551156    @app.route('/none')1157    def from_none():1158        pass11591160    @app.route('/small_tuple')1161    def from_small_tuple():1162        return 'Hello',11631164    @app.route('/large_tuple')1165    def from_large_tuple():1166        return 'Hello', 234, {'X-Foo': 'Bar'}, '???'11671168    @app.route('/bad_type')1169    def from_bad_type():1170        return True11711172    @app.route('/bad_wsgi')1173    def from_bad_wsgi():1174        return lambda: None11751176    c = app.test_client()11771178    with pytest.raises(TypeError) as e:1179        c.get('/none')1180        assert 'returned None' in str(e)11811182    with pytest.raises(TypeError) as e:1183        c.get('/small_tuple')1184        assert 'tuple must have the form' in str(e)11851186    pytest.raises(TypeError, c.get, '/large_tuple')11871188    with pytest.raises(TypeError) as e:1189        c.get('/bad_type')1190        assert 'it was a bool' in str(e)11911192    pytest.raises(TypeError, c.get, '/bad_wsgi')119311941195def test_make_response(app, req_ctx):1196    rv = flask.make_response()1197    assert rv.status_code == 2001198    assert rv.data == b''1199    assert rv.mimetype == 'text/html'12001201    rv = flask.make_response('Awesome')1202    assert rv.status_code == 2001203    assert rv.data == b'Awesome'1204    assert rv.mimetype == 'text/html'12051206    rv = flask.make_response('W00t', 404)1207    assert rv.status_code == 4041208    assert rv.data == b'W00t'1209    assert rv.mimetype == 'text/html'121012111212def test_make_response_with_response_instance(app, req_ctx):1213    rv = flask.make_response(1214        flask.jsonify({'msg': 'W00t'}), 400)1215    assert rv.status_code == 4001216    assert rv.data == b'{"msg":"W00t"}\n'1217    assert rv.mimetype == 'application/json'12181219    rv = flask.make_response(1220        flask.Response(''), 400)1221    assert rv.status_code == 4001222    assert rv.data == b''1223    assert rv.mimetype == 'text/html'12241225    rv = flask.make_response(1226        flask.Response('', headers={'Content-Type': 'text/html'}),1227        400, [('X-Foo', 'bar')])1228    assert rv.status_code == 4001229    assert rv.headers['Content-Type'] == 'text/html'1230    assert rv.headers['X-Foo'] == 'bar'123112321233def test_jsonify_no_prettyprint(app, req_ctx):1234    app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1235    compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1236    uncompressed_msg = {1237        "msg": {1238            "submsg": "W00t"1239        },1240        "msg2": "foobar"1241    }12421243    rv = flask.make_response(1244        flask.jsonify(uncompressed_msg), 200)1245    assert rv.data == compressed_msg124612471248def test_jsonify_prettyprint(app, req_ctx):1249    app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1250    compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1251    pretty_response = \1252        b'{\n  "msg": {\n    "submsg": "W00t"\n  }, \n  "msg2": "foobar"\n}\n'12531254    rv = flask.make_response(1255        flask.jsonify(compressed_msg), 200)1256    assert rv.data == pretty_response125712581259def test_jsonify_mimetype(app, req_ctx):1260    app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'})1261    msg = {1262        "msg": {"submsg": "W00t"},1263    }1264    rv = flask.make_response(1265        flask.jsonify(msg), 200)1266    assert rv.mimetype == 'application/vnd.api+json'126712681269def test_jsonify_args_and_kwargs_check(app, req_ctx):1270    with pytest.raises(TypeError) as e:1271        flask.jsonify('fake args', kwargs='fake')1272    assert 'behavior undefined' in str(e.value)127312741275def test_url_generation(app, req_ctx):1276    @app.route('/hello/<name>', methods=['POST'])1277    def hello():1278        pass12791280    assert flask.url_for('hello', name='test x') == '/hello/test%20x'1281    assert flask.url_for('hello', name='test x', _external=True) == \1282           'http://localhost/hello/test%20x'128312841285def test_build_error_handler(app):1286    # Test base case, a URL which results in a BuildError.1287    with app.test_request_context():1288        pytest.raises(BuildError, flask.url_for, 'spam')12891290    # Verify the error is re-raised if not the current exception.1291    try:1292        with app.test_request_context():1293            flask.url_for('spam')1294    except BuildError as err:1295        error = err1296    try:1297        raise RuntimeError('Test case where BuildError is not current.')1298    except RuntimeError:1299        pytest.raises(1300            BuildError, app.handle_url_build_error, error, 'spam', {})13011302    # Test a custom handler.1303    def handler(error, endpoint, values):1304        # Just a test.1305        return '/test_handler/'13061307    app.url_build_error_handlers.append(handler)1308    with app.test_request_context():1309        assert flask.url_for('spam') == '/test_handler/'131013111312def test_build_error_handler_reraise(app):1313    # Test a custom handler which reraises the BuildError1314    def handler_raises_build_error(error, endpoint, values):1315        raise error13161317    app.url_build_error_handlers.append(handler_raises_build_error)13181319    with app.test_request_context():1320        pytest.raises(BuildError, flask.url_for, 'not.existing')132113221323def test_url_for_passes_special_values_to_build_error_handler(app):1324    @app.url_build_error_handlers.append1325    def handler(error, endpoint, values):1326        assert values == {1327            '_external': False,1328            '_anchor': None,1329            '_method': None,1330            '_scheme': None,1331        }1332        return 'handled'13331334    with app.test_request_context():1335        flask.url_for('/')133613371338def test_custom_converters(app, client):1339    from werkzeug.routing import BaseConverter13401341    class ListConverter(BaseConverter):1342        def to_python(self, value):1343            return value.split(',')13441345        def to_url(self, value):1346            base_to_url = super(ListConverter, self).to_url1347            return ','.join(base_to_url(x) for x in value)13481349    app.url_map.converters['list'] = ListConverter13501351    @app.route('/<list:args>')1352    def index(args):1353        return '|'.join(args)13541355    assert client.get('/1,2,3').data == b'1|2|3'135613571358def test_static_files(app, client):1359    rv = client.get('/static/index.html')1360    assert rv.status_code == 2001361    assert rv.data.strip() == b'<h1>Hello World!</h1>'1362    with app.test_request_context():1363        assert flask.url_for('static', filename='index.html') == \1364               '/static/index.html'1365    rv.close()136613671368def test_static_url_path():1369    app = flask.Flask(__name__, static_url_path='/foo')1370    app.testing = True1371    rv = app.test_client().get('/foo/index.html')1372    assert rv.status_code == 2001373    rv.close()13741375    with app.test_request_context():1376        assert flask.url_for('static', filename='index.html') == '/foo/index.html'137713781379def test_static_route_with_host_matching():1380    app = flask.Flask(__name__, host_matching=True, static_host='example.com')1381    c = app.test_client()1382    rv = c.get('http://example.com/static/index.html')1383    assert rv.status_code == 2001384    rv.close()1385    with app.test_request_context():1386        rv = flask.url_for('static', filename='index.html', _external=True)1387        assert rv == 'http://example.com/static/index.html'1388    # Providing static_host without host_matching=True should error.1389    with pytest.raises(Exception):1390        flask.Flask(__name__, static_host='example.com')1391    # Providing host_matching=True with static_folder but without static_host should error.1392    with pytest.raises(Exception):1393        flask.Flask(__name__, host_matching=True)1394    # Providing host_matching=True without static_host but with static_folder=None should not error.1395    flask.Flask(__name__, host_matching=True, static_folder=None)139613971398def test_request_locals():1399    assert repr(flask.g) == '<LocalProxy unbound>'1400    assert not flask.g140114021403def test_test_app_proper_environ(app, client):1404    app.config.update(1405        SERVER_NAME='localhost.localdomain:5000'1406    )14071408    @app.route('/')1409    def index():1410        return 'Foo'14111412    @app.route('/', subdomain='foo')1413    def subdomain():1414        return 'Foo SubDomain'14151416    rv = client.get('/')1417    assert rv.data == b'Foo'14181419    rv = client.get('/', 'http://localhost.localdomain:5000')1420    assert rv.data == b'Foo'14211422    rv = client.get('/', 'https://localhost.localdomain:5000')1423    assert rv.data == b'Foo'14241425    app.config.update(SERVER_NAME='localhost.localdomain')1426    rv = client.get('/', 'https://localhost.localdomain')1427    assert rv.data == b'Foo'14281429    try:1430        app.config.update(SERVER_NAME='localhost.localdomain:443')1431        rv = client.get('/', 'https://localhost.localdomain')1432        # Werkzeug 0.81433        assert rv.status_code == 4041434    except ValueError as e:1435        # Werkzeug 0.71436        assert str(e) == (1437            "the server name provided "1438            "('localhost.localdomain:443') does not match the "1439            "server name from the WSGI environment ('localhost.localdomain')"1440        )14411442    try:1443        app.config.update(SERVER_NAME='localhost.localdomain')1444        rv = client.get('/', 'http://foo.localhost')1445        # Werkzeug 0.81446        assert rv.status_code == 4041447    except ValueError as e:1448        # Werkzeug 0.71449        assert str(e) == (1450            "the server name provided "1451            "('localhost.localdomain') does not match the "1452            "server name from the WSGI environment ('foo.localhost')"1453        )14541455    rv = client.get('/', 'http://foo.localhost.localdomain')1456    assert rv.data == b'Foo SubDomain'145714581459def test_exception_propagation(app, client):1460    def apprunner(config_key):14611462        @app.route('/')1463        def index():1464            1 // 014651466        if config_key is not None:1467            app.config[config_key] = True1468            with pytest.raises(Exception):1469                client.get('/')1470        else:1471            assert client.get('/').status_code == 50014721473    # we have to run this test in an isolated thread because if the1474    # debug flag is set to true and an exception happens the context is1475    # not torn down.  This causes other tests that run after this fail1476    # when they expect no exception on the stack.1477    for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None:1478        t = Thread(target=apprunner, args=(config_key,))1479        t.start()1480        t.join()148114821483@pytest.mark.parametrize('debug', [True, False])1484@pytest.mark.parametrize('use_debugger', [True, False])1485@pytest.mark.parametrize('use_reloader', [True, False])1486@pytest.mark.parametrize('propagate_exceptions', [None, True, False])1487def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1488                                     use_reloader, propagate_exceptions, app):1489    rv = {}14901491    # Mocks werkzeug.serving.run_simple method1492    def run_simple_mock(*args, **kwargs):1493        rv['passthrough_errors'] = kwargs.get('passthrough_errors')14941495    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1496    app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1497    app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)149814991500def test_max_content_length(app, client):1501    app.config['MAX_CONTENT_LENGTH'] = 6415021503    @app.before_request1504    def always_first():1505        flask.request.form['myfile']1506        assert False15071508    @app.route('/accept', methods=['POST'])1509    def accept_file():1510        flask.request.form['myfile']1511        assert False15121513    @app.errorhandler(413)1514    def catcher(error):1515        return '42'15161517    rv = client.post('/accept', data={'myfile': 'foo' * 100})1518    assert rv.data == b'42'151915201521def test_url_processors(app, client):15221523    @app.url_defaults1524    def add_language_code(endpoint, values):1525        if flask.g.lang_code is not None and \1526                app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1527            values.setdefault('lang_code', flask.g.lang_code)15281529    @app.url_value_preprocessor1530    def pull_lang_code(endpoint, values):1531        flask.g.lang_code = values.pop('lang_code', None)15321533    @app.route('/<lang_code>/')1534    def index():1535        return flask.url_for('about')15361537    @app.route('/<lang_code>/about')1538    def about():1539        return flask.url_for('something_else')15401541    @app.route('/foo')1542    def something_else():1543        return flask.url_for('about', lang_code='en')15441545    assert client.get('/de/').data == b'/de/about'1546    assert client.get('/de/about').data == b'/foo'1547    assert client.get('/foo').data == b'/en/about'154815491550def test_inject_blueprint_url_defaults(app):1551    bp = flask.Blueprint('foo.bar.baz', __name__,1552                         template_folder='template')15531554    @bp.url_defaults1555    def bp_defaults(endpoint, values):1556        values['page'] = 'login'15571558    @bp.route('/<page>')1559    def view(page):1560        pass15611562    app.register_blueprint(bp)15631564    values = dict()1565    app.inject_url_defaults('foo.bar.baz.view', values)1566    expected = dict(page='login')1567    assert values == expected15681569    with app.test_request_context('/somepage'):1570        url = flask.url_for('foo.bar.baz.view')1571    expected = '/login'1572    assert url == expected157315741575def test_nonascii_pathinfo(app, client):1576    @app.route(u'/киртест')1577    def index():1578        return 'Hello World!'15791580    rv = client.get(u'/киртест')1581    assert rv.data == b'Hello World!'158215831584def test_debug_mode_complains_after_first_request(app, client):1585    app.debug = True15861587    @app.route('/')1588    def index():1589        return 'Awesome'15901591    assert not app.got_first_request1592    assert client.get('/').data == b'Awesome'1593    with pytest.raises(AssertionError) as e:1594        @app.route('/foo')1595        def broken():1596            return 'Meh'1597    assert 'A setup function was called' in str(e)15981599    app.debug = False16001601    @app.route('/foo')1602    def working():1603        return 'Meh'16041605    assert client.get('/foo').data == b'Meh'1606    assert app.got_first_request160716081609def test_before_first_request_functions(app, client):1610    got = []16111612    @app.before_first_request1613    def foo():1614        got.append(42)16151616    client.get('/')1617    assert got == [42]1618    client.get('/')1619    assert got == [42]1620    assert app.got_first_request162116221623def test_before_first_request_functions_concurrent(app, client):1624    got = []16251626    @app.before_first_request1627    def foo():1628        time.sleep(0.2)1629        got.append(42)16301631    def get_and_assert():1632        client.get("/")1633        assert got == [42]16341635    t = Thread(target=get_and_assert)1636    t.start()1637    get_and_assert()1638    t.join()1639    assert app.got_first_request164016411642def test_routing_redirect_debugging(app, client):1643    app.debug = True16441645    @app.route('/foo/', methods=['GET', 'POST'])1646    def foo():1647        return 'success'16481649    with client:1650        with pytest.raises(AssertionError) as e:1651            client.post('/foo', data={})1652        assert 'http://localhost/foo/' in str(e)1653        assert ('Make sure to directly send '1654                'your POST-request to this URL') in str(e)16551656        rv = client.get('/foo', data={}, follow_redirects=True)1657        assert rv.data == b'success'16581659    app.debug = False1660    with client:1661        rv = client.post('/foo', data={}, follow_redirects=True)1662        assert rv.data == b'success'166316641665def test_route_decorator_custom_endpoint(app, client):1666    app.debug = True16671668    @app.route('/foo/')1669    def foo():1670        return flask.request.endpoint16711672    @app.route('/bar/', endpoint='bar')1673    def for_bar():1674        return flask.request.endpoint16751676    @app.route('/bar/123', endpoint='123')1677    def for_bar_foo():1678        return flask.request.endpoint16791680    with app.test_request_context():1681        assert flask.url_for('foo') == '/foo/'1682        assert flask.url_for('bar') == '/bar/'1683        assert flask.url_for('123') == '/bar/123'16841685    assert client.get('/foo/').data == b'foo'1686    assert client.get('/bar/').data == b'bar'1687    assert client.get('/bar/123').data == b'123'168816891690def test_preserve_only_once(app, client):1691    app.debug = True16921693    @app.route('/fail')1694    def fail_func():1695        1 // 016961697    for x in range(3):1698        with pytest.raises(ZeroDivisionError):1699            client.get('/fail')17001701    assert flask._request_ctx_stack.top is not None1702    assert flask._app_ctx_stack.top is not None1703    # implicit appctx disappears too1704    flask._request_ctx_stack.top.pop()1705    assert flask._request_ctx_stack.top is None1706    assert flask._app_ctx_stack.top is None170717081709def test_preserve_remembers_exception(app, client):1710    app.debug = True1711    errors = []17121713    @app.route('/fail')1714    def fail_func():1715        1 // 017161717    @app.route('/success')1718    def success_func():1719        return 'Okay'17201721    @app.teardown_request1722    def teardown_handler(exc):1723        errors.append(exc)17241725    # After this failure we did not yet call the teardown handler1726    with pytest.raises(ZeroDivisionError):1727        client.get('/fail')1728    assert errors == []17291730    # But this request triggers it, and it's an error1731    client.get('/success')1732    assert len(errors) == 21733    assert isinstance(errors[0], ZeroDivisionError)17341735    # At this point another request does nothing.1736    client.get('/success')1737    assert len(errors) == 31738    assert errors[1] is None173917401741def test_get_method_on_g(app_ctx):1742    assert flask.g.get('x') is None1743    assert flask.g.get('x', 11) == 111744    flask.g.x = 421745    assert flask.g.get('x') == 421746    assert flask.g.x == 42174717481749def test_g_iteration_protocol(app_ctx):1750    flask.g.foo = 231751    flask.g.bar = 421752    assert 'foo' in flask.g1753    assert 'foos' not in flask.g1754    assert sorted(flask.g) == ['bar', 'foo']175517561757def test_subdomain_basic_support(app, client):1758    app.config['SERVER_NAME'] = 'localhost.localdomain'17591760    @app.route('/')1761    def normal_index():1762        return 'normal index'17631764    @app.route('/', subdomain='test')1765    def test_index():1766        return 'test index'17671768    rv = client.get('/', 'http://localhost.localdomain/')1769    assert rv.data == b'normal index'17701771    rv = client.get('/', 'http://test.localhost.localdomain/')1772    assert rv.data == b'test index'177317741775def test_subdomain_matching(app, client):1776    app.config['SERVER_NAME'] = 'localhost.localdomain'17771778    @app.route('/', subdomain='<user>')1779    def index(user):1780        return 'index for %s' % user17811782    rv = client.get('/', 'http://mitsuhiko.localhost.localdomain/')1783    assert rv.data == b'index for mitsuhiko'178417851786def test_subdomain_matching_with_ports(app, client):1787    app.config['SERVER_NAME'] = 'localhost.localdomain:3000'17881789    @app.route('/', subdomain='<user>')1790    def index(user):1791        return 'index for %s' % user17921793    rv = client.get('/', 'http://mitsuhiko.localhost.localdomain:3000/')1794    assert rv.data == b'index for mitsuhiko'179517961797def test_multi_route_rules(app, client):1798    @app.route('/')1799    @app.route('/<test>/')1800    def index(test='a'):1801        return test18021803    rv = client.open('/')1804    assert rv.data == b'a'1805    rv = client.open('/b/')1806    assert rv.data == b'b'180718081809def test_multi_route_class_views(app, client):1810    class View(object):1811        def __init__(self, app):1812            app.add_url_rule('/', 'index', self.index)1813            app.add_url_rule('/<test>/', 'index', self.index)18141815        def index(self, test='a'):1816            return test18171818    _ = View(app)1819    rv = client.open('/')1820    assert rv.data == b'a'1821    rv = client.open('/b/')1822    assert rv.data == b'b'182318241825def test_run_defaults(monkeypatch, app):1826    rv = {}18271828    # Mocks werkzeug.serving.run_simple method1829    def run_simple_mock(*args, **kwargs):1830        rv['result'] = 'running...'18311832    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1833    app.run()1834    assert rv['result'] == 'running...'183518361837def test_run_server_port(monkeypatch, app):1838    rv = {}18391840    # Mocks werkzeug.serving.run_simple method1841    def run_simple_mock(hostname, port, application, *args, **kwargs):1842        rv['result'] = 'running on %s:%s ...' % (hostname, port)18431844    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1845    hostname, port = 'localhost', 80001846    app.run(hostname, port, debug=True)1847    assert rv['result'] == 'running on %s:%s ...' % (hostname, port)184818491850@pytest.mark.parametrize('host,port,expect_host,expect_port', (1851        (None, None, 'pocoo.org', 8080),1852        ('localhost', None, 'localhost', 8080),1853        (None, 80, 'pocoo.org', 80),1854        ('localhost', 80, 'localhost', 80),1855))1856def test_run_from_config(monkeypatch, host, port, expect_host, expect_port, app):1857    def run_simple_mock(hostname, port, *args, **kwargs):1858        assert hostname == expect_host1859        assert port == expect_port18601861    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1862    app.config['SERVER_NAME'] = 'pocoo.org:8080'1863    app.run(host, port)