Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

1,865 lines · 49.5 KiB · Python

Last changed by

Merge pull request #2362 from davidism/remove-error-handler-cacheDavid Lordbefore adoptionb80cf05

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 pickle13import re14import time15import uuid16from datetime import datetime17from threading import Thread1819import pytest20import werkzeug.serving21from werkzeug.exceptions import BadRequest, Forbidden, NotFound22from werkzeug.http import parse_date23from werkzeug.routing import BuildError2425import flask26from flask._compat import text_type272829def test_options_work(app, client):30    @app.route('/', methods=['GET', 'POST'])31    def index():32        return 'Hello World'3334    rv = client.open('/', method='OPTIONS')35    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']36    assert rv.data == b''373839def test_options_on_multiple_rules(app, client):40    @app.route('/', methods=['GET', 'POST'])41    def index():42        return 'Hello World'4344    @app.route('/', methods=['PUT'])45    def index_put():46        return 'Aha!'4748    rv = client.open('/', method='OPTIONS')49    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']505152def test_provide_automatic_options_attr():53    app = flask.Flask(__name__)5455    def index():56        return 'Hello World!'5758    index.provide_automatic_options = False59    app.route('/')(index)60    rv = app.test_client().open('/', method='OPTIONS')61    assert rv.status_code == 4056263    app = flask.Flask(__name__)6465    def index2():66        return 'Hello World!'6768    index2.provide_automatic_options = True69    app.route('/', methods=['OPTIONS'])(index2)70    rv = app.test_client().open('/', method='OPTIONS')71    assert sorted(rv.allow) == ['OPTIONS']727374def test_provide_automatic_options_kwarg(app, client):75    def index():76        return flask.request.method7778    def more():79        return flask.request.method8081    app.add_url_rule('/', view_func=index, provide_automatic_options=False)82    app.add_url_rule(83        '/more', view_func=more, methods=['GET', 'POST'],84        provide_automatic_options=False85    )86    assert client.get('/').data == b'GET'8788    rv = client.post('/')89    assert rv.status_code == 40590    assert sorted(rv.allow) == ['GET', 'HEAD']9192    # Older versions of Werkzeug.test.Client don't have an options method93    if hasattr(client, 'options'):94        rv = client.options('/')95    else:96        rv = client.open('/', method='OPTIONS')9798    assert rv.status_code == 40599100    rv = client.head('/')101    assert rv.status_code == 200102    assert not rv.data  # head truncates103    assert client.post('/more').data == b'POST'104    assert client.get('/more').data == b'GET'105106    rv = client.delete('/more')107    assert rv.status_code == 405108    assert sorted(rv.allow) == ['GET', 'HEAD', 'POST']109110    if hasattr(client, 'options'):111        rv = client.options('/more')112    else:113        rv = client.open('/more', method='OPTIONS')114115    assert rv.status_code == 405116117118def test_request_dispatching(app, client):119    @app.route('/')120    def index():121        return flask.request.method122123    @app.route('/more', methods=['GET', 'POST'])124    def more():125        return flask.request.method126127    assert client.get('/').data == b'GET'128    rv = client.post('/')129    assert rv.status_code == 405130    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']131    rv = client.head('/')132    assert rv.status_code == 200133    assert not rv.data  # head truncates134    assert client.post('/more').data == b'POST'135    assert client.get('/more').data == b'GET'136    rv = client.delete('/more')137    assert rv.status_code == 405138    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']139140141def test_disallow_string_for_allowed_methods(app):142    with pytest.raises(TypeError):143        @app.route('/', methods='GET POST')144        def index():145            return "Hey"146147148def test_url_mapping(app, client):149    random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"150151    def index():152        return flask.request.method153154    def more():155        return flask.request.method156157    def options():158        return random_uuid4159160    app.add_url_rule('/', 'index', index)161    app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])162163    # Issue 1288: Test that automatic options are not added when non-uppercase 'options' in methods164    app.add_url_rule('/options', 'options', options, methods=['options'])165166    assert client.get('/').data == b'GET'167    rv = client.post('/')168    assert rv.status_code == 405169    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']170    rv = client.head('/')171    assert rv.status_code == 200172    assert not rv.data  # head truncates173    assert client.post('/more').data == b'POST'174    assert client.get('/more').data == b'GET'175    rv = client.delete('/more')176    assert rv.status_code == 405177    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']178    rv = client.open('/options', method='OPTIONS')179    assert rv.status_code == 200180    assert random_uuid4 in rv.data.decode("utf-8")181182183def test_werkzeug_routing(app, client):184    from werkzeug.routing import Submount, Rule185    app.url_map.add(Submount('/foo', [186        Rule('/bar', endpoint='bar'),187        Rule('/', endpoint='index')188    ]))189190    def bar():191        return 'bar'192193    def index():194        return 'index'195196    app.view_functions['bar'] = bar197    app.view_functions['index'] = index198199    assert client.get('/foo/').data == b'index'200    assert client.get('/foo/bar').data == b'bar'201202203def test_endpoint_decorator(app, client):204    from werkzeug.routing import Submount, Rule205    app.url_map.add(Submount('/foo', [206        Rule('/bar', endpoint='bar'),207        Rule('/', endpoint='index')208    ]))209210    @app.endpoint('bar')211    def bar():212        return 'bar'213214    @app.endpoint('index')215    def index():216        return 'index'217218    assert client.get('/foo/').data == b'index'219    assert client.get('/foo/bar').data == b'bar'220221222def test_session(app, client):223    app.secret_key = 'testkey'224225    @app.route('/set', methods=['POST'])226    def set():227        flask.session['value'] = flask.request.form['value']228        return 'value set'229230    @app.route('/get')231    def get():232        return flask.session['value']233234    assert client.post('/set', data={'value': '42'}).data == b'value set'235    assert client.get('/get').data == b'42'236237238def test_session_using_server_name(app, client):239    app.config.update(240        SECRET_KEY='foo',241        SERVER_NAME='example.com'242    )243244    @app.route('/')245    def index():246        flask.session['testing'] = 42247        return 'Hello World'248249    rv = client.get('/', 'http://example.com/')250    assert 'domain=.example.com' in rv.headers['set-cookie'].lower()251    assert 'httponly' in rv.headers['set-cookie'].lower()252253254def test_session_using_server_name_and_port(app, client):255    app.config.update(256        SECRET_KEY='foo',257        SERVER_NAME='example.com:8080'258    )259260    @app.route('/')261    def index():262        flask.session['testing'] = 42263        return 'Hello World'264265    rv = client.get('/', 'http://example.com:8080/')266    assert 'domain=.example.com' in rv.headers['set-cookie'].lower()267    assert 'httponly' in rv.headers['set-cookie'].lower()268269270def test_session_using_server_name_port_and_path(app, client):271    app.config.update(272        SECRET_KEY='foo',273        SERVER_NAME='example.com:8080',274        APPLICATION_ROOT='/foo'275    )276277    @app.route('/')278    def index():279        flask.session['testing'] = 42280        return 'Hello World'281282    rv = client.get('/', 'http://example.com:8080/foo')283    assert 'domain=example.com' in rv.headers['set-cookie'].lower()284    assert 'path=/foo' in rv.headers['set-cookie'].lower()285    assert 'httponly' in rv.headers['set-cookie'].lower()286287288def test_session_using_application_root(app, client):289    class PrefixPathMiddleware(object):290        def __init__(self, app, prefix):291            self.app = app292            self.prefix = prefix293294        def __call__(self, environ, start_response):295            environ['SCRIPT_NAME'] = self.prefix296            return self.app(environ, start_response)297298    app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar')299    app.config.update(300        SECRET_KEY='foo',301        APPLICATION_ROOT='/bar'302    )303304    @app.route('/')305    def index():306        flask.session['testing'] = 42307        return 'Hello World'308309    rv = client.get('/', 'http://example.com:8080/')310    assert 'path=/bar' in rv.headers['set-cookie'].lower()311312313def test_session_using_session_settings(app, client):314    app.config.update(315        SECRET_KEY='foo',316        SERVER_NAME='www.example.com:8080',317        APPLICATION_ROOT='/test',318        SESSION_COOKIE_DOMAIN='.example.com',319        SESSION_COOKIE_HTTPONLY=False,320        SESSION_COOKIE_SECURE=True,321        SESSION_COOKIE_PATH='/'322    )323324    @app.route('/')325    def index():326        flask.session['testing'] = 42327        return 'Hello World'328329    rv = client.get('/', 'http://www.example.com:8080/test/')330    cookie = rv.headers['set-cookie'].lower()331    assert 'domain=.example.com' in cookie332    assert 'path=/' in cookie333    assert 'secure' in cookie334    assert 'httponly' not in cookie335336337def test_session_localhost_warning(recwarn, app, client):338    app.config.update(339        SECRET_KEY='testing',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        SECRET_KEY='testing',357        SERVER_NAME='127.0.0.1:5000',358    )359360    @app.route('/')361    def index():362        flask.session['testing'] = 42363        return 'testing'364365    rv = client.get('/', 'http://127.0.0.1:5000/')366    assert 'domain=127.0.0.1' in rv.headers['set-cookie'].lower()367    w = recwarn.pop(UserWarning)368    assert 'cookie domain is an IP' in str(w.message)369370371def test_missing_session():372    app = flask.Flask(__name__)373374    def expect_exception(f, *args, **kwargs):375        e = pytest.raises(RuntimeError, f, *args, **kwargs)376        assert e.value.args and 'session is unavailable' in e.value.args[0]377378    with app.test_request_context():379        assert flask.session.get('missing_key') is None380        expect_exception(flask.session.__setitem__, 'foo', 42)381        expect_exception(flask.session.pop, 'foo')382383384def test_session_expiration(app, client):385    permanent = True386    app.secret_key = 'testkey'387388    @app.route('/')389    def index():390        flask.session['test'] = 42391        flask.session.permanent = permanent392        return ''393394    @app.route('/test')395    def test():396        return text_type(flask.session.permanent)397398    rv = client.get('/')399    assert 'set-cookie' in rv.headers400    match = re.search(r'(?i)\bexpires=([^;]+)', rv.headers['set-cookie'])401    expires = parse_date(match.group())402    expected = datetime.utcnow() + app.permanent_session_lifetime403    assert expires.year == expected.year404    assert expires.month == expected.month405    assert expires.day == expected.day406407    rv = client.get('/test')408    assert rv.data == b'True'409410    permanent = False411    rv = client.get('/')412    assert 'set-cookie' in rv.headers413    match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])414    assert match is None415416417def test_session_stored_last(app, client):418    app.secret_key = 'development-key'419420    @app.after_request421    def modify_session(response):422        flask.session['foo'] = 42423        return response424425    @app.route('/')426    def dump_session_contents():427        return repr(flask.session.get('foo'))428429    assert client.get('/').data == b'None'430    assert client.get('/').data == b'42'431432433def test_session_special_types(app, client):434    app.secret_key = 'development-key'435    now = datetime.utcnow().replace(microsecond=0)436    the_uuid = uuid.uuid4()437438    @app.route('/')439    def dump_session_contents():440        flask.session['t'] = (1, 2, 3)441        flask.session['b'] = b'\xff'442        flask.session['m'] = flask.Markup('<html>')443        flask.session['u'] = the_uuid444        flask.session['d'] = now445        flask.session['t_tag'] = {' t': 'not-a-tuple'}446        flask.session['di_t_tag'] = {' t__': 'not-a-tuple'}447        flask.session['di_tag'] = {' di': 'not-a-dict'}448        return '', 204449450    with client:451        client.get('/')452        s = flask.session453        assert s['t'] == (1, 2, 3)454        assert type(s['b']) == bytes455        assert s['b'] == b'\xff'456        assert type(s['m']) == flask.Markup457        assert s['m'] == flask.Markup('<html>')458        assert s['u'] == the_uuid459        assert s['d'] == now460        assert s['t_tag'] == {' t': 'not-a-tuple'}461        assert s['di_t_tag'] == {' t__': 'not-a-tuple'}462        assert s['di_tag'] == {' di': 'not-a-dict'}463464465def test_session_cookie_setting(app):466    app.secret_key = 'dev key'467    is_permanent = True468469    @app.route('/bump')470    def bump():471        rv = flask.session['foo'] = flask.session.get('foo', 0) + 1472        flask.session.permanent = is_permanent473        return str(rv)474475    @app.route('/read')476    def read():477        return str(flask.session.get('foo', 0))478479    def run_test(expect_header):480        with app.test_client() as c:481            assert c.get('/bump').data == b'1'482            assert c.get('/bump').data == b'2'483            assert c.get('/bump').data == b'3'484485            rv = c.get('/read')486            set_cookie = rv.headers.get('set-cookie')487            assert (set_cookie is not None) == expect_header488            assert rv.data == b'3'489490    is_permanent = True491    app.config['SESSION_REFRESH_EACH_REQUEST'] = True492    run_test(expect_header=True)493494    is_permanent = True495    app.config['SESSION_REFRESH_EACH_REQUEST'] = False496    run_test(expect_header=False)497498    is_permanent = False499    app.config['SESSION_REFRESH_EACH_REQUEST'] = True500    run_test(expect_header=False)501502    is_permanent = False503    app.config['SESSION_REFRESH_EACH_REQUEST'] = False504    run_test(expect_header=False)505506507def test_session_vary_cookie(app, client):508    app.secret_key = 'testkey'509510    @app.route('/set')511    def set_session():512        flask.session['test'] = 'test'513        return ''514515    @app.route('/get')516    def get():517        return flask.session.get('test')518519    @app.route('/getitem')520    def getitem():521        return flask.session['test']522523    @app.route('/setdefault')524    def setdefault():525        return flask.session.setdefault('test', 'default')526527    @app.route('/vary-cookie-header-set')528    def vary_cookie_header_set():529        response = flask.Response()530        response.vary.add('Cookie')531        flask.session['test'] = 'test'532        return response533534    @app.route('/vary-header-set')535    def vary_header_set():536        response = flask.Response()537        response.vary.update(('Accept-Encoding', 'Accept-Language'))538        flask.session['test'] = 'test'539        return response540541    @app.route('/no-vary-header')542    def no_vary_header():543        return ''544545    def expect(path, header_value='Cookie'):546        rv = client.get(path)547548        if header_value:549            # The 'Vary' key should exist in the headers only once.550            assert len(rv.headers.get_all('Vary')) == 1551            assert rv.headers['Vary'] == header_value552        else:553            assert 'Vary' not in rv.headers554555    expect('/set')556    expect('/get')557    expect('/getitem')558    expect('/setdefault')559    expect('/vary-cookie-header-set')560    expect('/vary-header-set', 'Accept-Encoding, Accept-Language, Cookie')561    expect('/no-vary-header', None)562563564def test_flashes(app, req_ctx):565    app.secret_key = 'testkey'566567    assert not flask.session.modified568    flask.flash('Zap')569    flask.session.modified = False570    flask.flash('Zip')571    assert flask.session.modified572    assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']573574575def test_extended_flashing(app):576    # Be sure app.testing=True below, else tests can fail silently.577    #578    # Specifically, if app.testing is not set to True, the AssertionErrors579    # in the view functions will cause a 500 response to the test client580    # instead of propagating exceptions.581582    app.secret_key = 'testkey'583584    @app.route('/')585    def index():586        flask.flash(u'Hello World')587        flask.flash(u'Hello World', 'error')588        flask.flash(flask.Markup(u'<em>Testing</em>'), 'warning')589        return ''590591    @app.route('/test/')592    def test():593        messages = flask.get_flashed_messages()594        assert list(messages) == [595            u'Hello World',596            u'Hello World',597            flask.Markup(u'<em>Testing</em>')598        ]599        return ''600601    @app.route('/test_with_categories/')602    def test_with_categories():603        messages = flask.get_flashed_messages(with_categories=True)604        assert len(messages) == 3605        assert list(messages) == [606            ('message', u'Hello World'),607            ('error', u'Hello World'),608            ('warning', flask.Markup(u'<em>Testing</em>'))609        ]610        return ''611612    @app.route('/test_filter/')613    def test_filter():614        messages = flask.get_flashed_messages(615            category_filter=['message'], with_categories=True)616        assert list(messages) == [('message', u'Hello World')]617        return ''618619    @app.route('/test_filters/')620    def test_filters():621        messages = flask.get_flashed_messages(622            category_filter=['message', 'warning'], with_categories=True)623        assert list(messages) == [624            ('message', u'Hello World'),625            ('warning', flask.Markup(u'<em>Testing</em>'))626        ]627        return ''628629    @app.route('/test_filters_without_returning_categories/')630    def test_filters2():631        messages = flask.get_flashed_messages(632            category_filter=['message', 'warning'])633        assert len(messages) == 2634        assert messages[0] == u'Hello World'635        assert messages[1] == flask.Markup(u'<em>Testing</em>')636        return ''637638    # Create new test client on each test to clean flashed messages.639640    client = app.test_client()641    client.get('/')642    client.get('/test_with_categories/')643644    client = app.test_client()645    client.get('/')646    client.get('/test_filter/')647648    client = app.test_client()649    client.get('/')650    client.get('/test_filters/')651652    client = app.test_client()653    client.get('/')654    client.get('/test_filters_without_returning_categories/')655656657def test_request_processing(app, client):658    evts = []659660    @app.before_request661    def before_request():662        evts.append('before')663664    @app.after_request665    def after_request(response):666        response.data += b'|after'667        evts.append('after')668        return response669670    @app.route('/')671    def index():672        assert 'before' in evts673        assert 'after' not in evts674        return 'request'675676    assert 'after' not in evts677    rv = client.get('/').data678    assert 'after' in evts679    assert rv == b'request|after'680681682def test_request_preprocessing_early_return(app, client):683    evts = []684685    @app.before_request686    def before_request1():687        evts.append(1)688689    @app.before_request690    def before_request2():691        evts.append(2)692        return "hello"693694    @app.before_request695    def before_request3():696        evts.append(3)697        return "bye"698699    @app.route('/')700    def index():701        evts.append('index')702        return "damnit"703704    rv = client.get('/').data.strip()705    assert rv == b'hello'706    assert evts == [1, 2]707708709def test_after_request_processing(app, client):710    @app.route('/')711    def index():712        @flask.after_this_request713        def foo(response):714            response.headers['X-Foo'] = 'a header'715            return response716717        return 'Test'718719    resp = client.get('/')720    assert resp.status_code == 200721    assert resp.headers['X-Foo'] == 'a header'722723724def test_teardown_request_handler(app, client):725    called = []726727    @app.teardown_request728    def teardown_request(exc):729        called.append(True)730        return "Ignored"731732    @app.route('/')733    def root():734        return "Response"735736    rv = client.get('/')737    assert rv.status_code == 200738    assert b'Response' in rv.data739    assert len(called) == 1740741742def test_teardown_request_handler_debug_mode(app, client):743    called = []744745    @app.teardown_request746    def teardown_request(exc):747        called.append(True)748        return "Ignored"749750    @app.route('/')751    def root():752        return "Response"753754    rv = client.get('/')755    assert rv.status_code == 200756    assert b'Response' in rv.data757    assert len(called) == 1758759760def test_teardown_request_handler_error(app, client):761    called = []762    app.config['LOGGER_HANDLER_POLICY'] = 'never'763    app.testing = False764765    @app.teardown_request766    def teardown_request1(exc):767        assert type(exc) == ZeroDivisionError768        called.append(True)769        # This raises a new error and blows away sys.exc_info(), so we can770        # test that all teardown_requests get passed the same original771        # exception.772        try:773            raise TypeError()774        except:775            pass776777    @app.teardown_request778    def teardown_request2(exc):779        assert type(exc) == ZeroDivisionError780        called.append(True)781        # This raises a new error and blows away sys.exc_info(), so we can782        # test that all teardown_requests get passed the same original783        # exception.784        try:785            raise TypeError()786        except:787            pass788789    @app.route('/')790    def fails():791        1 // 0792793    rv = client.get('/')794    assert rv.status_code == 500795    assert b'Internal Server Error' in rv.data796    assert len(called) == 2797798799def test_before_after_request_order(app, client):800    called = []801802    @app.before_request803    def before1():804        called.append(1)805806    @app.before_request807    def before2():808        called.append(2)809810    @app.after_request811    def after1(response):812        called.append(4)813        return response814815    @app.after_request816    def after2(response):817        called.append(3)818        return response819820    @app.teardown_request821    def finish1(exc):822        called.append(6)823824    @app.teardown_request825    def finish2(exc):826        called.append(5)827828    @app.route('/')829    def index():830        return '42'831832    rv = client.get('/')833    assert rv.data == b'42'834    assert called == [1, 2, 3, 4, 5, 6]835836837def test_error_handling(app, client):838    app.config['LOGGER_HANDLER_POLICY'] = 'never'839    app.testing = False840841    @app.errorhandler(404)842    def not_found(e):843        return 'not found', 404844845    @app.errorhandler(500)846    def internal_server_error(e):847        return 'internal server error', 500848849    @app.errorhandler(Forbidden)850    def forbidden(e):851        return 'forbidden', 403852853    @app.route('/')854    def index():855        flask.abort(404)856857    @app.route('/error')858    def error():859        1 // 0860861    @app.route('/forbidden')862    def error2():863        flask.abort(403)864865    rv = client.get('/')866    assert rv.status_code == 404867    assert rv.data == b'not found'868    rv = client.get('/error')869    assert rv.status_code == 500870    assert b'internal server error' == rv.data871    rv = client.get('/forbidden')872    assert rv.status_code == 403873    assert b'forbidden' == rv.data874875876def test_error_handler_unknown_code(app):877    with pytest.raises(KeyError) as exc_info:878        app.register_error_handler(999, lambda e: ('999', 999))879880    assert 'Use a subclass' in exc_info.value.args[0]881882883def test_error_handling_processing(app, client):884    app.config['LOGGER_HANDLER_POLICY'] = 'never'885    app.testing = False886887    @app.errorhandler(500)888    def internal_server_error(e):889        return 'internal server error', 500890891    @app.route('/')892    def broken_func():893        1 // 0894895    @app.after_request896    def after_request(resp):897        resp.mimetype = 'text/x-special'898        return resp899900    resp = client.get('/')901    assert resp.mimetype == 'text/x-special'902    assert resp.data == b'internal server error'903904905def test_baseexception_error_handling(app, client):906    app.config['LOGGER_HANDLER_POLICY'] = 'never'907    app.testing = False908909    @app.route('/')910    def broken_func():911        raise KeyboardInterrupt()912913    with pytest.raises(KeyboardInterrupt):914        client.get('/')915916        ctx = flask._request_ctx_stack.top917        assert ctx.preserved918        assert type(ctx._preserved_exc) is KeyboardInterrupt919920921def test_before_request_and_routing_errors(app, client):922    @app.before_request923    def attach_something():924        flask.g.something = 'value'925926    @app.errorhandler(404)927    def return_something(error):928        return flask.g.something, 404929930    rv = client.get('/')931    assert rv.status_code == 404932    assert rv.data == b'value'933934935def test_user_error_handling(app, client):936    class MyException(Exception):937        pass938939    @app.errorhandler(MyException)940    def handle_my_exception(e):941        assert isinstance(e, MyException)942        return '42'943944    @app.route('/')945    def index():946        raise MyException()947948    assert client.get('/').data == b'42'949950951def test_http_error_subclass_handling(app, client):952    class ForbiddenSubclass(Forbidden):953        pass954955    @app.errorhandler(ForbiddenSubclass)956    def handle_forbidden_subclass(e):957        assert isinstance(e, ForbiddenSubclass)958        return 'banana'959960    @app.errorhandler(403)961    def handle_forbidden_subclass(e):962        assert not isinstance(e, ForbiddenSubclass)963        assert isinstance(e, Forbidden)964        return 'apple'965966    @app.route('/1')967    def index1():968        raise ForbiddenSubclass()969970    @app.route('/2')971    def index2():972        flask.abort(403)973974    @app.route('/3')975    def index3():976        raise Forbidden()977978    assert client.get('/1').data == b'banana'979    assert client.get('/2').data == b'apple'980    assert client.get('/3').data == b'apple'981982983def test_errorhandler_precedence(app, client):984    class E1(Exception):985        pass986987    class E2(Exception):988        pass989990    class E3(E1, E2):991        pass992993    @app.errorhandler(E2)994    def handle_e2(e):995        return 'E2'996997    @app.errorhandler(Exception)998    def handle_exception(e):999        return 'Exception'10001001    @app.route('/E1')1002    def raise_e1():1003        raise E110041005    @app.route('/E3')1006    def raise_e3():1007        raise E310081009    rv = client.get('/E1')1010    assert rv.data == b'Exception'10111012    rv = client.get('/E3')1013    assert rv.data == b'E2'101410151016def test_trapping_of_bad_request_key_errors(app, client):1017    @app.route('/fail')1018    def fail():1019        flask.request.form['missing_key']10201021    rv = client.get('/fail')1022    assert rv.status_code == 4001023    assert b'missing_key' not in rv.data10241025    app.config['TRAP_BAD_REQUEST_ERRORS'] = True10261027    with pytest.raises(KeyError) as e:1028        client.get("/fail")10291030    assert e.errisinstance(BadRequest)1031    assert 'missing_key' in e.value.description103210331034def test_trapping_of_all_http_exceptions(app, client):1035    app.config['TRAP_HTTP_EXCEPTIONS'] = True10361037    @app.route('/fail')1038    def fail():1039        flask.abort(404)10401041    with pytest.raises(NotFound):1042        client.get('/fail')104310441045def test_enctype_debug_helper(app, client):1046    from flask.debughelpers import DebugFilesKeyError1047    app.debug = True10481049    @app.route('/fail', methods=['POST'])1050    def index():1051        return flask.request.files['foo'].filename10521053    # with statement is important because we leave an exception on the1054    # stack otherwise and we want to ensure that this is not the case1055    # to not negatively affect other tests.1056    with client:1057        with pytest.raises(DebugFilesKeyError) as e:1058            client.post('/fail', data={'foo': 'index.txt'})1059        assert 'no file contents were transmitted' in str(e.value)1060        assert 'This was submitted: "index.txt"' in str(e.value)106110621063def test_response_types(app, client):1064    @app.route('/text')1065    def from_text():1066        return u'Hällo Wörld'10671068    @app.route('/bytes')1069    def from_bytes():1070        return u'Hällo Wörld'.encode('utf-8')10711072    @app.route('/full_tuple')1073    def from_full_tuple():1074        return 'Meh', 400, {1075            'X-Foo': 'Testing',1076            'Content-Type': 'text/plain; charset=utf-8'1077        }10781079    @app.route('/text_headers')1080    def from_text_headers():1081        return 'Hello', {1082            'X-Foo': 'Test',1083            'Content-Type': 'text/plain; charset=utf-8'1084        }10851086    @app.route('/text_status')1087    def from_text_status():1088        return 'Hi, status!', 40010891090    @app.route('/response_headers')1091    def from_response_headers():1092        return flask.Response('Hello world', 404, {'X-Foo': 'Baz'}), {1093            "X-Foo": "Bar",1094            "X-Bar": "Foo"1095        }10961097    @app.route('/response_status')1098    def from_response_status():1099        return app.response_class('Hello world', 400), 50011001101    @app.route('/wsgi')1102    def from_wsgi():1103        return NotFound()11041105    assert client.get('/text').data == u'Hällo Wörld'.encode('utf-8')1106    assert client.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')11071108    rv = client.get('/full_tuple')1109    assert rv.data == b'Meh'1110    assert rv.headers['X-Foo'] == 'Testing'1111    assert rv.status_code == 4001112    assert rv.mimetype == 'text/plain'11131114    rv = client.get('/text_headers')1115    assert rv.data == b'Hello'1116    assert rv.headers['X-Foo'] == 'Test'1117    assert rv.status_code == 2001118    assert rv.mimetype == 'text/plain'11191120    rv = client.get('/text_status')1121    assert rv.data == b'Hi, status!'1122    assert rv.status_code == 4001123    assert rv.mimetype == 'text/html'11241125    rv = client.get('/response_headers')1126    assert rv.data == b'Hello world'1127    assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar']1128    assert rv.headers['X-Bar'] == 'Foo'1129    assert rv.status_code == 40411301131    rv = client.get('/response_status')1132    assert rv.data == b'Hello world'1133    assert rv.status_code == 50011341135    rv = client.get('/wsgi')1136    assert b'Not Found' in rv.data1137    assert rv.status_code == 404113811391140def test_response_type_errors():1141    app = flask.Flask(__name__)1142    app.testing = True11431144    @app.route('/none')1145    def from_none():1146        pass11471148    @app.route('/small_tuple')1149    def from_small_tuple():1150        return 'Hello',11511152    @app.route('/large_tuple')1153    def from_large_tuple():1154        return 'Hello', 234, {'X-Foo': 'Bar'}, '???'11551156    @app.route('/bad_type')1157    def from_bad_type():1158        return True11591160    @app.route('/bad_wsgi')1161    def from_bad_wsgi():1162        return lambda: None11631164    c = app.test_client()11651166    with pytest.raises(TypeError) as e:1167        c.get('/none')1168        assert 'returned None' in str(e)11691170    with pytest.raises(TypeError) as e:1171        c.get('/small_tuple')1172        assert 'tuple must have the form' in str(e)11731174    pytest.raises(TypeError, c.get, '/large_tuple')11751176    with pytest.raises(TypeError) as e:1177        c.get('/bad_type')1178        assert 'it was a bool' in str(e)11791180    pytest.raises(TypeError, c.get, '/bad_wsgi')118111821183def test_make_response(app, req_ctx):1184    rv = flask.make_response()1185    assert rv.status_code == 2001186    assert rv.data == b''1187    assert rv.mimetype == 'text/html'11881189    rv = flask.make_response('Awesome')1190    assert rv.status_code == 2001191    assert rv.data == b'Awesome'1192    assert rv.mimetype == 'text/html'11931194    rv = flask.make_response('W00t', 404)1195    assert rv.status_code == 4041196    assert rv.data == b'W00t'1197    assert rv.mimetype == 'text/html'119811991200def test_make_response_with_response_instance(app, req_ctx):1201    rv = flask.make_response(1202        flask.jsonify({'msg': 'W00t'}), 400)1203    assert rv.status_code == 4001204    assert rv.data == b'{"msg":"W00t"}\n'1205    assert rv.mimetype == 'application/json'12061207    rv = flask.make_response(1208        flask.Response(''), 400)1209    assert rv.status_code == 4001210    assert rv.data == b''1211    assert rv.mimetype == 'text/html'12121213    rv = flask.make_response(1214        flask.Response('', headers={'Content-Type': 'text/html'}),1215        400, [('X-Foo', 'bar')])1216    assert rv.status_code == 4001217    assert rv.headers['Content-Type'] == 'text/html'1218    assert rv.headers['X-Foo'] == 'bar'121912201221def test_jsonify_no_prettyprint(app, req_ctx):1222    app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1223    compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1224    uncompressed_msg = {1225        "msg": {1226            "submsg": "W00t"1227        },1228        "msg2": "foobar"1229    }12301231    rv = flask.make_response(1232        flask.jsonify(uncompressed_msg), 200)1233    assert rv.data == compressed_msg123412351236def test_jsonify_prettyprint(app, req_ctx):1237    app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1238    compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1239    pretty_response = \1240        b'{\n  "msg": {\n    "submsg": "W00t"\n  }, \n  "msg2": "foobar"\n}\n'12411242    rv = flask.make_response(1243        flask.jsonify(compressed_msg), 200)1244    assert rv.data == pretty_response124512461247def test_jsonify_mimetype(app, req_ctx):1248    app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'})1249    msg = {1250        "msg": {"submsg": "W00t"},1251    }1252    rv = flask.make_response(1253        flask.jsonify(msg), 200)1254    assert rv.mimetype == 'application/vnd.api+json'125512561257def test_jsonify_args_and_kwargs_check(app, req_ctx):1258    with pytest.raises(TypeError) as e:1259        flask.jsonify('fake args', kwargs='fake')1260    assert 'behavior undefined' in str(e.value)126112621263def test_url_generation(app, req_ctx):1264    @app.route('/hello/<name>', methods=['POST'])1265    def hello():1266        pass12671268    assert flask.url_for('hello', name='test x') == '/hello/test%20x'1269    assert flask.url_for('hello', name='test x', _external=True) == \1270           'http://localhost/hello/test%20x'127112721273def test_build_error_handler(app):1274    # Test base case, a URL which results in a BuildError.1275    with app.test_request_context():1276        pytest.raises(BuildError, flask.url_for, 'spam')12771278    # Verify the error is re-raised if not the current exception.1279    try:1280        with app.test_request_context():1281            flask.url_for('spam')1282    except BuildError as err:1283        error = err1284    try:1285        raise RuntimeError('Test case where BuildError is not current.')1286    except RuntimeError:1287        pytest.raises(1288            BuildError, app.handle_url_build_error, error, 'spam', {})12891290    # Test a custom handler.1291    def handler(error, endpoint, values):1292        # Just a test.1293        return '/test_handler/'12941295    app.url_build_error_handlers.append(handler)1296    with app.test_request_context():1297        assert flask.url_for('spam') == '/test_handler/'129812991300def test_build_error_handler_reraise(app):1301    # Test a custom handler which reraises the BuildError1302    def handler_raises_build_error(error, endpoint, values):1303        raise error13041305    app.url_build_error_handlers.append(handler_raises_build_error)13061307    with app.test_request_context():1308        pytest.raises(BuildError, flask.url_for, 'not.existing')130913101311def test_url_for_passes_special_values_to_build_error_handler(app):1312    @app.url_build_error_handlers.append1313    def handler(error, endpoint, values):1314        assert values == {1315            '_external': False,1316            '_anchor': None,1317            '_method': None,1318            '_scheme': None,1319        }1320        return 'handled'13211322    with app.test_request_context():1323        flask.url_for('/')132413251326def test_custom_converters(app, client):1327    from werkzeug.routing import BaseConverter13281329    class ListConverter(BaseConverter):1330        def to_python(self, value):1331            return value.split(',')13321333        def to_url(self, value):1334            base_to_url = super(ListConverter, self).to_url1335            return ','.join(base_to_url(x) for x in value)13361337    app.url_map.converters['list'] = ListConverter13381339    @app.route('/<list:args>')1340    def index(args):1341        return '|'.join(args)13421343    assert client.get('/1,2,3').data == b'1|2|3'134413451346def test_static_files(app, client):1347    rv = client.get('/static/index.html')1348    assert rv.status_code == 2001349    assert rv.data.strip() == b'<h1>Hello World!</h1>'1350    with app.test_request_context():1351        assert flask.url_for('static', filename='index.html') == \1352               '/static/index.html'1353    rv.close()135413551356def test_static_path_deprecated(recwarn):1357    app = flask.Flask(__name__, static_path='/foo')1358    recwarn.pop(DeprecationWarning)13591360    app.testing = True1361    rv = app.test_client().get('/foo/index.html')1362    assert rv.status_code == 2001363    rv.close()13641365    with app.test_request_context():1366        assert flask.url_for('static', filename='index.html') == '/foo/index.html'136713681369def test_static_url_path():1370    app = flask.Flask(__name__, static_url_path='/foo')1371    app.testing = True1372    rv = app.test_client().get('/foo/index.html')1373    assert rv.status_code == 2001374    rv.close()13751376    with app.test_request_context():1377        assert flask.url_for('static', filename='index.html') == '/foo/index.html'137813791380def test_static_route_with_host_matching():1381    app = flask.Flask(__name__, host_matching=True, static_host='example.com')1382    c = app.test_client()1383    rv = c.get('http://example.com/static/index.html')1384    assert rv.status_code == 2001385    rv.close()1386    with app.test_request_context():1387        rv = flask.url_for('static', filename='index.html', _external=True)1388        assert rv == 'http://example.com/static/index.html'1389    # Providing static_host without host_matching=True should error.1390    with pytest.raises(Exception):1391        flask.Flask(__name__, static_host='example.com')1392    # Providing host_matching=True with static_folder but without static_host should error.1393    with pytest.raises(Exception):1394        flask.Flask(__name__, host_matching=True)1395    # Providing host_matching=True without static_host but with static_folder=None should not error.1396    flask.Flask(__name__, host_matching=True, static_folder=None)139713981399def test_request_locals():1400    assert repr(flask.g) == '<LocalProxy unbound>'1401    assert not flask.g140214031404def test_test_app_proper_environ(app, client):1405    app.config.update(1406        SERVER_NAME='localhost.localdomain:5000'1407    )14081409    @app.route('/')1410    def index():1411        return 'Foo'14121413    @app.route('/', subdomain='foo')1414    def subdomain():1415        return 'Foo SubDomain'14161417    rv = client.get('/')1418    assert rv.data == b'Foo'14191420    rv = client.get('/', 'http://localhost.localdomain:5000')1421    assert rv.data == b'Foo'14221423    rv = client.get('/', 'https://localhost.localdomain:5000')1424    assert rv.data == b'Foo'14251426    app.config.update(SERVER_NAME='localhost.localdomain')1427    rv = client.get('/', 'https://localhost.localdomain')1428    assert rv.data == b'Foo'14291430    try:1431        app.config.update(SERVER_NAME='localhost.localdomain:443')1432        rv = client.get('/', 'https://localhost.localdomain')1433        # Werkzeug 0.81434        assert rv.status_code == 4041435    except ValueError as e:1436        # Werkzeug 0.71437        assert str(e) == (1438            "the server name provided "1439            "('localhost.localdomain:443') does not match the "1440            "server name from the WSGI environment ('localhost.localdomain')"1441        )14421443    try:1444        app.config.update(SERVER_NAME='localhost.localdomain')1445        rv = client.get('/', 'http://foo.localhost')1446        # Werkzeug 0.81447        assert rv.status_code == 4041448    except ValueError as e:1449        # Werkzeug 0.71450        assert str(e) == (1451            "the server name provided "1452            "('localhost.localdomain') does not match the "1453            "server name from the WSGI environment ('foo.localhost')"1454        )14551456    rv = client.get('/', 'http://foo.localhost.localdomain')1457    assert rv.data == b'Foo SubDomain'145814591460def test_exception_propagation(app, client):1461    def apprunner(config_key):1462        app.config['LOGGER_HANDLER_POLICY'] = 'never'14631464        @app.route('/')1465        def index():1466            1 // 014671468        if config_key is not None:1469            app.config[config_key] = True1470            with pytest.raises(Exception):1471                client.get('/')1472        else:1473            assert client.get('/').status_code == 50014741475    # we have to run this test in an isolated thread because if the1476    # debug flag is set to true and an exception happens the context is1477    # not torn down.  This causes other tests that run after this fail1478    # when they expect no exception on the stack.1479    for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None:1480        t = Thread(target=apprunner, args=(config_key,))1481        t.start()1482        t.join()148314841485@pytest.mark.parametrize('debug', [True, False])1486@pytest.mark.parametrize('use_debugger', [True, False])1487@pytest.mark.parametrize('use_reloader', [True, False])1488@pytest.mark.parametrize('propagate_exceptions', [None, True, False])1489def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1490                                     use_reloader, propagate_exceptions, app):1491    rv = {}14921493    # Mocks werkzeug.serving.run_simple method1494    def run_simple_mock(*args, **kwargs):1495        rv['passthrough_errors'] = kwargs.get('passthrough_errors')14961497    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1498    app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1499    app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)150015011502def test_max_content_length(app, client):1503    app.config['MAX_CONTENT_LENGTH'] = 6415041505    @app.before_request1506    def always_first():1507        flask.request.form['myfile']1508        assert False15091510    @app.route('/accept', methods=['POST'])1511    def accept_file():1512        flask.request.form['myfile']1513        assert False15141515    @app.errorhandler(413)1516    def catcher(error):1517        return '42'15181519    rv = client.post('/accept', data={'myfile': 'foo' * 100})1520    assert rv.data == b'42'152115221523def test_url_processors(app, client):15241525    @app.url_defaults1526    def add_language_code(endpoint, values):1527        if flask.g.lang_code is not None and \1528                app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1529            values.setdefault('lang_code', flask.g.lang_code)15301531    @app.url_value_preprocessor1532    def pull_lang_code(endpoint, values):1533        flask.g.lang_code = values.pop('lang_code', None)15341535    @app.route('/<lang_code>/')1536    def index():1537        return flask.url_for('about')15381539    @app.route('/<lang_code>/about')1540    def about():1541        return flask.url_for('something_else')15421543    @app.route('/foo')1544    def something_else():1545        return flask.url_for('about', lang_code='en')15461547    assert client.get('/de/').data == b'/de/about'1548    assert client.get('/de/about').data == b'/foo'1549    assert client.get('/foo').data == b'/en/about'155015511552def test_inject_blueprint_url_defaults(app):1553    bp = flask.Blueprint('foo.bar.baz', __name__,1554                         template_folder='template')15551556    @bp.url_defaults1557    def bp_defaults(endpoint, values):1558        values['page'] = 'login'15591560    @bp.route('/<page>')1561    def view(page):1562        pass15631564    app.register_blueprint(bp)15651566    values = dict()1567    app.inject_url_defaults('foo.bar.baz.view', values)1568    expected = dict(page='login')1569    assert values == expected15701571    with app.test_request_context('/somepage'):1572        url = flask.url_for('foo.bar.baz.view')1573    expected = '/login'1574    assert url == expected157515761577def test_nonascii_pathinfo(app, client):1578    @app.route(u'/киртест')1579    def index():1580        return 'Hello World!'15811582    rv = client.get(u'/киртест')1583    assert rv.data == b'Hello World!'158415851586def test_debug_mode_complains_after_first_request(app, client):1587    app.debug = True15881589    @app.route('/')1590    def index():1591        return 'Awesome'15921593    assert not app.got_first_request1594    assert client.get('/').data == b'Awesome'1595    with pytest.raises(AssertionError) as e:1596        @app.route('/foo')1597        def broken():1598            return 'Meh'1599    assert 'A setup function was called' in str(e)16001601    app.debug = False16021603    @app.route('/foo')1604    def working():1605        return 'Meh'16061607    assert client.get('/foo').data == b'Meh'1608    assert app.got_first_request160916101611def test_before_first_request_functions(app, client):1612    got = []16131614    @app.before_first_request1615    def foo():1616        got.append(42)16171618    client.get('/')1619    assert got == [42]1620    client.get('/')1621    assert got == [42]1622    assert app.got_first_request162316241625def test_before_first_request_functions_concurrent(app, client):1626    got = []16271628    @app.before_first_request1629    def foo():1630        time.sleep(0.2)1631        got.append(42)16321633    def get_and_assert():1634        client.get("/")1635        assert got == [42]16361637    t = Thread(target=get_and_assert)1638    t.start()1639    get_and_assert()1640    t.join()1641    assert app.got_first_request164216431644def test_routing_redirect_debugging(app, client):1645    app.debug = True16461647    @app.route('/foo/', methods=['GET', 'POST'])1648    def foo():1649        return 'success'16501651    with client:1652        with pytest.raises(AssertionError) as e:1653            client.post('/foo', data={})1654        assert 'http://localhost/foo/' in str(e)1655        assert ('Make sure to directly send '1656                'your POST-request to this URL') in str(e)16571658        rv = client.get('/foo', data={}, follow_redirects=True)1659        assert rv.data == b'success'16601661    app.debug = False1662    with client:1663        rv = client.post('/foo', data={}, follow_redirects=True)1664        assert rv.data == b'success'166516661667def test_route_decorator_custom_endpoint(app, client):1668    app.debug = True16691670    @app.route('/foo/')1671    def foo():1672        return flask.request.endpoint16731674    @app.route('/bar/', endpoint='bar')1675    def for_bar():1676        return flask.request.endpoint16771678    @app.route('/bar/123', endpoint='123')1679    def for_bar_foo():1680        return flask.request.endpoint16811682    with app.test_request_context():1683        assert flask.url_for('foo') == '/foo/'1684        assert flask.url_for('bar') == '/bar/'1685        assert flask.url_for('123') == '/bar/123'16861687    assert client.get('/foo/').data == b'foo'1688    assert client.get('/bar/').data == b'bar'1689    assert client.get('/bar/123').data == b'123'169016911692def test_preserve_only_once(app, client):1693    app.debug = True16941695    @app.route('/fail')1696    def fail_func():1697        1 // 016981699    for x in range(3):1700        with pytest.raises(ZeroDivisionError):1701            client.get('/fail')17021703    assert flask._request_ctx_stack.top is not None1704    assert flask._app_ctx_stack.top is not None1705    # implicit appctx disappears too1706    flask._request_ctx_stack.top.pop()1707    assert flask._request_ctx_stack.top is None1708    assert flask._app_ctx_stack.top is None170917101711def test_preserve_remembers_exception(app, client):1712    app.debug = True1713    errors = []17141715    @app.route('/fail')1716    def fail_func():1717        1 // 017181719    @app.route('/success')1720    def success_func():1721        return 'Okay'17221723    @app.teardown_request1724    def teardown_handler(exc):1725        errors.append(exc)17261727    # After this failure we did not yet call the teardown handler1728    with pytest.raises(ZeroDivisionError):1729        client.get('/fail')1730    assert errors == []17311732    # But this request triggers it, and it's an error1733    client.get('/success')1734    assert len(errors) == 21735    assert isinstance(errors[0], ZeroDivisionError)17361737    # At this point another request does nothing.1738    client.get('/success')1739    assert len(errors) == 31740    assert errors[1] is None174117421743def test_get_method_on_g(app_ctx):1744    assert flask.g.get('x') is None1745    assert flask.g.get('x', 11) == 111746    flask.g.x = 421747    assert flask.g.get('x') == 421748    assert flask.g.x == 42174917501751def test_g_iteration_protocol(app_ctx):1752    flask.g.foo = 231753    flask.g.bar = 421754    assert 'foo' in flask.g1755    assert 'foos' not in flask.g1756    assert sorted(flask.g) == ['bar', 'foo']175717581759def test_subdomain_basic_support(app, client):1760    app.config['SERVER_NAME'] = 'localhost.localdomain'17611762    @app.route('/')1763    def normal_index():1764        return 'normal index'17651766    @app.route('/', subdomain='test')1767    def test_index():1768        return 'test index'17691770    rv = client.get('/', 'http://localhost.localdomain/')1771    assert rv.data == b'normal index'17721773    rv = client.get('/', 'http://test.localhost.localdomain/')1774    assert rv.data == b'test index'177517761777def test_subdomain_matching(app, client):1778    app.config['SERVER_NAME'] = 'localhost.localdomain'17791780    @app.route('/', subdomain='<user>')1781    def index(user):1782        return 'index for %s' % user17831784    rv = client.get('/', 'http://mitsuhiko.localhost.localdomain/')1785    assert rv.data == b'index for mitsuhiko'178617871788def test_subdomain_matching_with_ports(app, client):1789    app.config['SERVER_NAME'] = 'localhost.localdomain:3000'17901791    @app.route('/', subdomain='<user>')1792    def index(user):1793        return 'index for %s' % user17941795    rv = client.get('/', 'http://mitsuhiko.localhost.localdomain:3000/')1796    assert rv.data == b'index for mitsuhiko'179717981799def test_multi_route_rules(app, client):1800    @app.route('/')1801    @app.route('/<test>/')1802    def index(test='a'):1803        return test18041805    rv = client.open('/')1806    assert rv.data == b'a'1807    rv = client.open('/b/')1808    assert rv.data == b'b'180918101811def test_multi_route_class_views(app, client):1812    class View(object):1813        def __init__(self, app):1814            app.add_url_rule('/', 'index', self.index)1815            app.add_url_rule('/<test>/', 'index', self.index)18161817        def index(self, test='a'):1818            return test18191820    _ = View(app)1821    rv = client.open('/')1822    assert rv.data == b'a'1823    rv = client.open('/b/')1824    assert rv.data == b'b'182518261827def test_run_defaults(monkeypatch, app):1828    rv = {}18291830    # Mocks werkzeug.serving.run_simple method1831    def run_simple_mock(*args, **kwargs):1832        rv['result'] = 'running...'18331834    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1835    app.run()1836    assert rv['result'] == 'running...'183718381839def test_run_server_port(monkeypatch, app):1840    rv = {}18411842    # Mocks werkzeug.serving.run_simple method1843    def run_simple_mock(hostname, port, application, *args, **kwargs):1844        rv['result'] = 'running on %s:%s ...' % (hostname, port)18451846    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1847    hostname, port = 'localhost', 80001848    app.run(hostname, port, debug=True)1849    assert rv['result'] == 'running on %s:%s ...' % (hostname, port)185018511852@pytest.mark.parametrize('host,port,expect_host,expect_port', (1853        (None, None, 'pocoo.org', 8080),1854        ('localhost', None, 'localhost', 8080),1855        (None, 80, 'pocoo.org', 80),1856        ('localhost', 80, 'localhost', 80),1857))1858def test_run_from_config(monkeypatch, host, port, expect_host, expect_port, app):1859    def run_simple_mock(hostname, port, *args, **kwargs):1860        assert hostname == expect_host1861        assert port == expect_port18621863    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1864    app.config['SERVER_NAME'] = 'pocoo.org:8080'1865    app.run(host, port)