Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

1,852 lines · 49.2 KiB · Python

Last changed by

Merge pull request #2394 from davidism/remove-deprecatedDavid Lordbefore adoption4c56477

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_url_path():1357    app = flask.Flask(__name__, static_url_path='/foo')1358    app.testing = True1359    rv = app.test_client().get('/foo/index.html')1360    assert rv.status_code == 2001361    rv.close()13621363    with app.test_request_context():1364        assert flask.url_for('static', filename='index.html') == '/foo/index.html'136513661367def test_static_route_with_host_matching():1368    app = flask.Flask(__name__, host_matching=True, static_host='example.com')1369    c = app.test_client()1370    rv = c.get('http://example.com/static/index.html')1371    assert rv.status_code == 2001372    rv.close()1373    with app.test_request_context():1374        rv = flask.url_for('static', filename='index.html', _external=True)1375        assert rv == 'http://example.com/static/index.html'1376    # Providing static_host without host_matching=True should error.1377    with pytest.raises(Exception):1378        flask.Flask(__name__, static_host='example.com')1379    # Providing host_matching=True with static_folder but without static_host should error.1380    with pytest.raises(Exception):1381        flask.Flask(__name__, host_matching=True)1382    # Providing host_matching=True without static_host but with static_folder=None should not error.1383    flask.Flask(__name__, host_matching=True, static_folder=None)138413851386def test_request_locals():1387    assert repr(flask.g) == '<LocalProxy unbound>'1388    assert not flask.g138913901391def test_test_app_proper_environ(app, client):1392    app.config.update(1393        SERVER_NAME='localhost.localdomain:5000'1394    )13951396    @app.route('/')1397    def index():1398        return 'Foo'13991400    @app.route('/', subdomain='foo')1401    def subdomain():1402        return 'Foo SubDomain'14031404    rv = client.get('/')1405    assert rv.data == b'Foo'14061407    rv = client.get('/', 'http://localhost.localdomain:5000')1408    assert rv.data == b'Foo'14091410    rv = client.get('/', 'https://localhost.localdomain:5000')1411    assert rv.data == b'Foo'14121413    app.config.update(SERVER_NAME='localhost.localdomain')1414    rv = client.get('/', 'https://localhost.localdomain')1415    assert rv.data == b'Foo'14161417    try:1418        app.config.update(SERVER_NAME='localhost.localdomain:443')1419        rv = client.get('/', 'https://localhost.localdomain')1420        # Werkzeug 0.81421        assert rv.status_code == 4041422    except ValueError as e:1423        # Werkzeug 0.71424        assert str(e) == (1425            "the server name provided "1426            "('localhost.localdomain:443') does not match the "1427            "server name from the WSGI environment ('localhost.localdomain')"1428        )14291430    try:1431        app.config.update(SERVER_NAME='localhost.localdomain')1432        rv = client.get('/', 'http://foo.localhost')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') does not match the "1440            "server name from the WSGI environment ('foo.localhost')"1441        )14421443    rv = client.get('/', 'http://foo.localhost.localdomain')1444    assert rv.data == b'Foo SubDomain'144514461447def test_exception_propagation(app, client):1448    def apprunner(config_key):1449        app.config['LOGGER_HANDLER_POLICY'] = 'never'14501451        @app.route('/')1452        def index():1453            1 // 014541455        if config_key is not None:1456            app.config[config_key] = True1457            with pytest.raises(Exception):1458                client.get('/')1459        else:1460            assert client.get('/').status_code == 50014611462    # we have to run this test in an isolated thread because if the1463    # debug flag is set to true and an exception happens the context is1464    # not torn down.  This causes other tests that run after this fail1465    # when they expect no exception on the stack.1466    for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None:1467        t = Thread(target=apprunner, args=(config_key,))1468        t.start()1469        t.join()147014711472@pytest.mark.parametrize('debug', [True, False])1473@pytest.mark.parametrize('use_debugger', [True, False])1474@pytest.mark.parametrize('use_reloader', [True, False])1475@pytest.mark.parametrize('propagate_exceptions', [None, True, False])1476def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1477                                     use_reloader, propagate_exceptions, app):1478    rv = {}14791480    # Mocks werkzeug.serving.run_simple method1481    def run_simple_mock(*args, **kwargs):1482        rv['passthrough_errors'] = kwargs.get('passthrough_errors')14831484    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1485    app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1486    app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)148714881489def test_max_content_length(app, client):1490    app.config['MAX_CONTENT_LENGTH'] = 6414911492    @app.before_request1493    def always_first():1494        flask.request.form['myfile']1495        assert False14961497    @app.route('/accept', methods=['POST'])1498    def accept_file():1499        flask.request.form['myfile']1500        assert False15011502    @app.errorhandler(413)1503    def catcher(error):1504        return '42'15051506    rv = client.post('/accept', data={'myfile': 'foo' * 100})1507    assert rv.data == b'42'150815091510def test_url_processors(app, client):15111512    @app.url_defaults1513    def add_language_code(endpoint, values):1514        if flask.g.lang_code is not None and \1515                app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1516            values.setdefault('lang_code', flask.g.lang_code)15171518    @app.url_value_preprocessor1519    def pull_lang_code(endpoint, values):1520        flask.g.lang_code = values.pop('lang_code', None)15211522    @app.route('/<lang_code>/')1523    def index():1524        return flask.url_for('about')15251526    @app.route('/<lang_code>/about')1527    def about():1528        return flask.url_for('something_else')15291530    @app.route('/foo')1531    def something_else():1532        return flask.url_for('about', lang_code='en')15331534    assert client.get('/de/').data == b'/de/about'1535    assert client.get('/de/about').data == b'/foo'1536    assert client.get('/foo').data == b'/en/about'153715381539def test_inject_blueprint_url_defaults(app):1540    bp = flask.Blueprint('foo.bar.baz', __name__,1541                         template_folder='template')15421543    @bp.url_defaults1544    def bp_defaults(endpoint, values):1545        values['page'] = 'login'15461547    @bp.route('/<page>')1548    def view(page):1549        pass15501551    app.register_blueprint(bp)15521553    values = dict()1554    app.inject_url_defaults('foo.bar.baz.view', values)1555    expected = dict(page='login')1556    assert values == expected15571558    with app.test_request_context('/somepage'):1559        url = flask.url_for('foo.bar.baz.view')1560    expected = '/login'1561    assert url == expected156215631564def test_nonascii_pathinfo(app, client):1565    @app.route(u'/киртест')1566    def index():1567        return 'Hello World!'15681569    rv = client.get(u'/киртест')1570    assert rv.data == b'Hello World!'157115721573def test_debug_mode_complains_after_first_request(app, client):1574    app.debug = True15751576    @app.route('/')1577    def index():1578        return 'Awesome'15791580    assert not app.got_first_request1581    assert client.get('/').data == b'Awesome'1582    with pytest.raises(AssertionError) as e:1583        @app.route('/foo')1584        def broken():1585            return 'Meh'1586    assert 'A setup function was called' in str(e)15871588    app.debug = False15891590    @app.route('/foo')1591    def working():1592        return 'Meh'15931594    assert client.get('/foo').data == b'Meh'1595    assert app.got_first_request159615971598def test_before_first_request_functions(app, client):1599    got = []16001601    @app.before_first_request1602    def foo():1603        got.append(42)16041605    client.get('/')1606    assert got == [42]1607    client.get('/')1608    assert got == [42]1609    assert app.got_first_request161016111612def test_before_first_request_functions_concurrent(app, client):1613    got = []16141615    @app.before_first_request1616    def foo():1617        time.sleep(0.2)1618        got.append(42)16191620    def get_and_assert():1621        client.get("/")1622        assert got == [42]16231624    t = Thread(target=get_and_assert)1625    t.start()1626    get_and_assert()1627    t.join()1628    assert app.got_first_request162916301631def test_routing_redirect_debugging(app, client):1632    app.debug = True16331634    @app.route('/foo/', methods=['GET', 'POST'])1635    def foo():1636        return 'success'16371638    with client:1639        with pytest.raises(AssertionError) as e:1640            client.post('/foo', data={})1641        assert 'http://localhost/foo/' in str(e)1642        assert ('Make sure to directly send '1643                'your POST-request to this URL') in str(e)16441645        rv = client.get('/foo', data={}, follow_redirects=True)1646        assert rv.data == b'success'16471648    app.debug = False1649    with client:1650        rv = client.post('/foo', data={}, follow_redirects=True)1651        assert rv.data == b'success'165216531654def test_route_decorator_custom_endpoint(app, client):1655    app.debug = True16561657    @app.route('/foo/')1658    def foo():1659        return flask.request.endpoint16601661    @app.route('/bar/', endpoint='bar')1662    def for_bar():1663        return flask.request.endpoint16641665    @app.route('/bar/123', endpoint='123')1666    def for_bar_foo():1667        return flask.request.endpoint16681669    with app.test_request_context():1670        assert flask.url_for('foo') == '/foo/'1671        assert flask.url_for('bar') == '/bar/'1672        assert flask.url_for('123') == '/bar/123'16731674    assert client.get('/foo/').data == b'foo'1675    assert client.get('/bar/').data == b'bar'1676    assert client.get('/bar/123').data == b'123'167716781679def test_preserve_only_once(app, client):1680    app.debug = True16811682    @app.route('/fail')1683    def fail_func():1684        1 // 016851686    for x in range(3):1687        with pytest.raises(ZeroDivisionError):1688            client.get('/fail')16891690    assert flask._request_ctx_stack.top is not None1691    assert flask._app_ctx_stack.top is not None1692    # implicit appctx disappears too1693    flask._request_ctx_stack.top.pop()1694    assert flask._request_ctx_stack.top is None1695    assert flask._app_ctx_stack.top is None169616971698def test_preserve_remembers_exception(app, client):1699    app.debug = True1700    errors = []17011702    @app.route('/fail')1703    def fail_func():1704        1 // 017051706    @app.route('/success')1707    def success_func():1708        return 'Okay'17091710    @app.teardown_request1711    def teardown_handler(exc):1712        errors.append(exc)17131714    # After this failure we did not yet call the teardown handler1715    with pytest.raises(ZeroDivisionError):1716        client.get('/fail')1717    assert errors == []17181719    # But this request triggers it, and it's an error1720    client.get('/success')1721    assert len(errors) == 21722    assert isinstance(errors[0], ZeroDivisionError)17231724    # At this point another request does nothing.1725    client.get('/success')1726    assert len(errors) == 31727    assert errors[1] is None172817291730def test_get_method_on_g(app_ctx):1731    assert flask.g.get('x') is None1732    assert flask.g.get('x', 11) == 111733    flask.g.x = 421734    assert flask.g.get('x') == 421735    assert flask.g.x == 42173617371738def test_g_iteration_protocol(app_ctx):1739    flask.g.foo = 231740    flask.g.bar = 421741    assert 'foo' in flask.g1742    assert 'foos' not in flask.g1743    assert sorted(flask.g) == ['bar', 'foo']174417451746def test_subdomain_basic_support(app, client):1747    app.config['SERVER_NAME'] = 'localhost.localdomain'17481749    @app.route('/')1750    def normal_index():1751        return 'normal index'17521753    @app.route('/', subdomain='test')1754    def test_index():1755        return 'test index'17561757    rv = client.get('/', 'http://localhost.localdomain/')1758    assert rv.data == b'normal index'17591760    rv = client.get('/', 'http://test.localhost.localdomain/')1761    assert rv.data == b'test index'176217631764def test_subdomain_matching(app, client):1765    app.config['SERVER_NAME'] = 'localhost.localdomain'17661767    @app.route('/', subdomain='<user>')1768    def index(user):1769        return 'index for %s' % user17701771    rv = client.get('/', 'http://mitsuhiko.localhost.localdomain/')1772    assert rv.data == b'index for mitsuhiko'177317741775def test_subdomain_matching_with_ports(app, client):1776    app.config['SERVER_NAME'] = 'localhost.localdomain:3000'17771778    @app.route('/', subdomain='<user>')1779    def index(user):1780        return 'index for %s' % user17811782    rv = client.get('/', 'http://mitsuhiko.localhost.localdomain:3000/')1783    assert rv.data == b'index for mitsuhiko'178417851786def test_multi_route_rules(app, client):1787    @app.route('/')1788    @app.route('/<test>/')1789    def index(test='a'):1790        return test17911792    rv = client.open('/')1793    assert rv.data == b'a'1794    rv = client.open('/b/')1795    assert rv.data == b'b'179617971798def test_multi_route_class_views(app, client):1799    class View(object):1800        def __init__(self, app):1801            app.add_url_rule('/', 'index', self.index)1802            app.add_url_rule('/<test>/', 'index', self.index)18031804        def index(self, test='a'):1805            return test18061807    _ = View(app)1808    rv = client.open('/')1809    assert rv.data == b'a'1810    rv = client.open('/b/')1811    assert rv.data == b'b'181218131814def test_run_defaults(monkeypatch, app):1815    rv = {}18161817    # Mocks werkzeug.serving.run_simple method1818    def run_simple_mock(*args, **kwargs):1819        rv['result'] = 'running...'18201821    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1822    app.run()1823    assert rv['result'] == 'running...'182418251826def test_run_server_port(monkeypatch, app):1827    rv = {}18281829    # Mocks werkzeug.serving.run_simple method1830    def run_simple_mock(hostname, port, application, *args, **kwargs):1831        rv['result'] = 'running on %s:%s ...' % (hostname, port)18321833    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1834    hostname, port = 'localhost', 80001835    app.run(hostname, port, debug=True)1836    assert rv['result'] == 'running on %s:%s ...' % (hostname, port)183718381839@pytest.mark.parametrize('host,port,expect_host,expect_port', (1840        (None, None, 'pocoo.org', 8080),1841        ('localhost', None, 'localhost', 8080),1842        (None, 80, 'pocoo.org', 80),1843        ('localhost', 80, 'localhost', 80),1844))1845def test_run_from_config(monkeypatch, host, port, expect_host, expect_port, app):1846    def run_simple_mock(hostname, port, *args, **kwargs):1847        assert hostname == expect_host1848        assert port == expect_port18491850    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1851    app.config['SERVER_NAME'] = 'pocoo.org:8080'1852    app.run(host, port)