Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

1,835 lines · 49.1 KiB · Python

Last changed by

Merge branch 'master' into json-object-hookDavid Lordbefore adoptionea2e960

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.after_request439    def modify_session(response):440        flask.session['m'] = flask.Markup('Hello!')441        flask.session['u'] = the_uuid442        flask.session['dt'] = now443        flask.session['b'] = b'\xff'444        flask.session['t'] = (1, 2, 3)445        flask.session['spacefirst'] = {' t': 'not-a-tuple'}446        flask.session['withunderscores'] = {' t__': 'not-a-tuple'}447        flask.session['notadict'] = {' di': 'not-a-dict'}448        return response449450    @app.route('/')451    def dump_session_contents():452        return pickle.dumps(dict(flask.session))453454    client.get('/')455    rv = pickle.loads(client.get('/').data)456    assert rv['m'] == flask.Markup('Hello!')457    assert type(rv['m']) == flask.Markup458    assert rv['dt'] == now459    assert rv['u'] == the_uuid460    assert rv['b'] == b'\xff'461    assert type(rv['b']) == bytes462    assert rv['t'] == (1, 2, 3)463    assert rv['spacefirst'] == {' t': 'not-a-tuple'}464    assert rv['withunderscores'] == {' t__': 'not-a-tuple'}465    assert rv['notadict'] == {' di': 'not-a-dict'}466467468def test_session_cookie_setting(app):469    app.secret_key = 'dev key'470    is_permanent = True471472    @app.route('/bump')473    def bump():474        rv = flask.session['foo'] = flask.session.get('foo', 0) + 1475        flask.session.permanent = is_permanent476        return str(rv)477478    @app.route('/read')479    def read():480        return str(flask.session.get('foo', 0))481482    def run_test(expect_header):483        with app.test_client() as c:484            assert c.get('/bump').data == b'1'485            assert c.get('/bump').data == b'2'486            assert c.get('/bump').data == b'3'487488            rv = c.get('/read')489            set_cookie = rv.headers.get('set-cookie')490            assert (set_cookie is not None) == expect_header491            assert rv.data == b'3'492493    is_permanent = True494    app.config['SESSION_REFRESH_EACH_REQUEST'] = True495    run_test(expect_header=True)496497    is_permanent = True498    app.config['SESSION_REFRESH_EACH_REQUEST'] = False499    run_test(expect_header=False)500501    is_permanent = False502    app.config['SESSION_REFRESH_EACH_REQUEST'] = True503    run_test(expect_header=False)504505    is_permanent = False506    app.config['SESSION_REFRESH_EACH_REQUEST'] = False507    run_test(expect_header=False)508509510def test_session_vary_cookie(app, client):511    app.secret_key = 'testkey'512513    @app.route('/set')514    def set_session():515        flask.session['test'] = 'test'516        return ''517518    @app.route('/get')519    def get():520        return flask.session.get('test')521522    @app.route('/getitem')523    def getitem():524        return flask.session['test']525526    @app.route('/setdefault')527    def setdefault():528        return flask.session.setdefault('test', 'default')529530    @app.route('/vary-cookie-header-set')531    def vary_cookie_header_set():532        response = flask.Response()533        response.vary.add('Cookie')534        flask.session['test'] = 'test'535        return response536537    @app.route('/vary-header-set')538    def vary_header_set():539        response = flask.Response()540        response.vary.update(('Accept-Encoding', 'Accept-Language'))541        flask.session['test'] = 'test'542        return response543544    @app.route('/no-vary-header')545    def no_vary_header():546        return ''547548    def expect(path, header_value='Cookie'):549        rv = client.get(path)550551        if header_value:552            # The 'Vary' key should exist in the headers only once.553            assert len(rv.headers.get_all('Vary')) == 1554            assert rv.headers['Vary'] == header_value555        else:556            assert 'Vary' not in rv.headers557558    expect('/set')559    expect('/get')560    expect('/getitem')561    expect('/setdefault')562    expect('/vary-cookie-header-set')563    expect('/vary-header-set', 'Accept-Encoding, Accept-Language, Cookie')564    expect('/no-vary-header', None)565566567def test_flashes(app, req_ctx):568    app.secret_key = 'testkey'569570    assert not flask.session.modified571    flask.flash('Zap')572    flask.session.modified = False573    flask.flash('Zip')574    assert flask.session.modified575    assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']576577578def test_extended_flashing(app):579    # Be sure app.testing=True below, else tests can fail silently.580    #581    # Specifically, if app.testing is not set to True, the AssertionErrors582    # in the view functions will cause a 500 response to the test client583    # instead of propagating exceptions.584585    app.secret_key = 'testkey'586587    @app.route('/')588    def index():589        flask.flash(u'Hello World')590        flask.flash(u'Hello World', 'error')591        flask.flash(flask.Markup(u'<em>Testing</em>'), 'warning')592        return ''593594    @app.route('/test/')595    def test():596        messages = flask.get_flashed_messages()597        assert list(messages) == [598            u'Hello World',599            u'Hello World',600            flask.Markup(u'<em>Testing</em>')601        ]602        return ''603604    @app.route('/test_with_categories/')605    def test_with_categories():606        messages = flask.get_flashed_messages(with_categories=True)607        assert len(messages) == 3608        assert list(messages) == [609            ('message', u'Hello World'),610            ('error', u'Hello World'),611            ('warning', flask.Markup(u'<em>Testing</em>'))612        ]613        return ''614615    @app.route('/test_filter/')616    def test_filter():617        messages = flask.get_flashed_messages(618            category_filter=['message'], with_categories=True)619        assert list(messages) == [('message', u'Hello World')]620        return ''621622    @app.route('/test_filters/')623    def test_filters():624        messages = flask.get_flashed_messages(625            category_filter=['message', 'warning'], with_categories=True)626        assert list(messages) == [627            ('message', u'Hello World'),628            ('warning', flask.Markup(u'<em>Testing</em>'))629        ]630        return ''631632    @app.route('/test_filters_without_returning_categories/')633    def test_filters2():634        messages = flask.get_flashed_messages(635            category_filter=['message', 'warning'])636        assert len(messages) == 2637        assert messages[0] == u'Hello World'638        assert messages[1] == flask.Markup(u'<em>Testing</em>')639        return ''640641    # Create new test client on each test to clean flashed messages.642643    client = app.test_client()644    client.get('/')645    client.get('/test_with_categories/')646647    client = app.test_client()648    client.get('/')649    client.get('/test_filter/')650651    client = app.test_client()652    client.get('/')653    client.get('/test_filters/')654655    client = app.test_client()656    client.get('/')657    client.get('/test_filters_without_returning_categories/')658659660def test_request_processing(app, client):661    evts = []662663    @app.before_request664    def before_request():665        evts.append('before')666667    @app.after_request668    def after_request(response):669        response.data += b'|after'670        evts.append('after')671        return response672673    @app.route('/')674    def index():675        assert 'before' in evts676        assert 'after' not in evts677        return 'request'678679    assert 'after' not in evts680    rv = client.get('/').data681    assert 'after' in evts682    assert rv == b'request|after'683684685def test_request_preprocessing_early_return(app, client):686    evts = []687688    @app.before_request689    def before_request1():690        evts.append(1)691692    @app.before_request693    def before_request2():694        evts.append(2)695        return "hello"696697    @app.before_request698    def before_request3():699        evts.append(3)700        return "bye"701702    @app.route('/')703    def index():704        evts.append('index')705        return "damnit"706707    rv = client.get('/').data.strip()708    assert rv == b'hello'709    assert evts == [1, 2]710711712def test_after_request_processing(app, client):713    @app.route('/')714    def index():715        @flask.after_this_request716        def foo(response):717            response.headers['X-Foo'] = 'a header'718            return response719720        return 'Test'721722    resp = client.get('/')723    assert resp.status_code == 200724    assert resp.headers['X-Foo'] == 'a header'725726727def test_teardown_request_handler(app, client):728    called = []729730    @app.teardown_request731    def teardown_request(exc):732        called.append(True)733        return "Ignored"734735    @app.route('/')736    def root():737        return "Response"738739    rv = client.get('/')740    assert rv.status_code == 200741    assert b'Response' in rv.data742    assert len(called) == 1743744745def test_teardown_request_handler_debug_mode(app, client):746    called = []747748    @app.teardown_request749    def teardown_request(exc):750        called.append(True)751        return "Ignored"752753    @app.route('/')754    def root():755        return "Response"756757    rv = client.get('/')758    assert rv.status_code == 200759    assert b'Response' in rv.data760    assert len(called) == 1761762763def test_teardown_request_handler_error(app, client):764    called = []765    app.config['LOGGER_HANDLER_POLICY'] = 'never'766    app.testing = False767768    @app.teardown_request769    def teardown_request1(exc):770        assert type(exc) == ZeroDivisionError771        called.append(True)772        # This raises a new error and blows away sys.exc_info(), so we can773        # test that all teardown_requests get passed the same original774        # exception.775        try:776            raise TypeError()777        except:778            pass779780    @app.teardown_request781    def teardown_request2(exc):782        assert type(exc) == ZeroDivisionError783        called.append(True)784        # This raises a new error and blows away sys.exc_info(), so we can785        # test that all teardown_requests get passed the same original786        # exception.787        try:788            raise TypeError()789        except:790            pass791792    @app.route('/')793    def fails():794        1 // 0795796    rv = client.get('/')797    assert rv.status_code == 500798    assert b'Internal Server Error' in rv.data799    assert len(called) == 2800801802def test_before_after_request_order(app, client):803    called = []804805    @app.before_request806    def before1():807        called.append(1)808809    @app.before_request810    def before2():811        called.append(2)812813    @app.after_request814    def after1(response):815        called.append(4)816        return response817818    @app.after_request819    def after2(response):820        called.append(3)821        return response822823    @app.teardown_request824    def finish1(exc):825        called.append(6)826827    @app.teardown_request828    def finish2(exc):829        called.append(5)830831    @app.route('/')832    def index():833        return '42'834835    rv = client.get('/')836    assert rv.data == b'42'837    assert called == [1, 2, 3, 4, 5, 6]838839840def test_error_handling(app, client):841    app.config['LOGGER_HANDLER_POLICY'] = 'never'842    app.testing = False843844    @app.errorhandler(404)845    def not_found(e):846        return 'not found', 404847848    @app.errorhandler(500)849    def internal_server_error(e):850        return 'internal server error', 500851852    @app.errorhandler(Forbidden)853    def forbidden(e):854        return 'forbidden', 403855856    @app.route('/')857    def index():858        flask.abort(404)859860    @app.route('/error')861    def error():862        1 // 0863864    @app.route('/forbidden')865    def error2():866        flask.abort(403)867868    rv = client.get('/')869    assert rv.status_code == 404870    assert rv.data == b'not found'871    rv = client.get('/error')872    assert rv.status_code == 500873    assert b'internal server error' == rv.data874    rv = client.get('/forbidden')875    assert rv.status_code == 403876    assert b'forbidden' == rv.data877878879def test_error_handler_unknown_code(app):880    with pytest.raises(KeyError) as exc_info:881        app.register_error_handler(999, lambda e: ('999', 999))882883    assert 'Use a subclass' in exc_info.value.args[0]884885886def test_error_handling_processing(app, client):887    app.config['LOGGER_HANDLER_POLICY'] = 'never'888    app.testing = False889890    @app.errorhandler(500)891    def internal_server_error(e):892        return 'internal server error', 500893894    @app.route('/')895    def broken_func():896        1 // 0897898    @app.after_request899    def after_request(resp):900        resp.mimetype = 'text/x-special'901        return resp902903    resp = client.get('/')904    assert resp.mimetype == 'text/x-special'905    assert resp.data == b'internal server error'906907908def test_baseexception_error_handling(app, client):909    app.config['LOGGER_HANDLER_POLICY'] = 'never'910    app.testing = False911912    @app.route('/')913    def broken_func():914        raise KeyboardInterrupt()915916    with pytest.raises(KeyboardInterrupt):917        client.get('/')918919        ctx = flask._request_ctx_stack.top920        assert ctx.preserved921        assert type(ctx._preserved_exc) is KeyboardInterrupt922923924def test_before_request_and_routing_errors(app, client):925    @app.before_request926    def attach_something():927        flask.g.something = 'value'928929    @app.errorhandler(404)930    def return_something(error):931        return flask.g.something, 404932933    rv = client.get('/')934    assert rv.status_code == 404935    assert rv.data == b'value'936937938def test_user_error_handling(app, client):939    class MyException(Exception):940        pass941942    @app.errorhandler(MyException)943    def handle_my_exception(e):944        assert isinstance(e, MyException)945        return '42'946947    @app.route('/')948    def index():949        raise MyException()950951    assert client.get('/').data == b'42'952953954def test_http_error_subclass_handling(app, client):955    class ForbiddenSubclass(Forbidden):956        pass957958    @app.errorhandler(ForbiddenSubclass)959    def handle_forbidden_subclass(e):960        assert isinstance(e, ForbiddenSubclass)961        return 'banana'962963    @app.errorhandler(403)964    def handle_forbidden_subclass(e):965        assert not isinstance(e, ForbiddenSubclass)966        assert isinstance(e, Forbidden)967        return 'apple'968969    @app.route('/1')970    def index1():971        raise ForbiddenSubclass()972973    @app.route('/2')974    def index2():975        flask.abort(403)976977    @app.route('/3')978    def index3():979        raise Forbidden()980981    assert client.get('/1').data == b'banana'982    assert client.get('/2').data == b'apple'983    assert client.get('/3').data == b'apple'984985986def test_trapping_of_bad_request_key_errors(app, client):987    @app.route('/fail')988    def fail():989        flask.request.form['missing_key']990991    rv = client.get('/fail')992    assert rv.status_code == 400993    assert b'missing_key' not in rv.data994995    app.config['TRAP_BAD_REQUEST_ERRORS'] = True996997    with pytest.raises(KeyError) as e:998        client.get("/fail")9991000    assert e.errisinstance(BadRequest)1001    assert 'missing_key' in e.value.description100210031004def test_trapping_of_all_http_exceptions(app, client):1005    app.config['TRAP_HTTP_EXCEPTIONS'] = True10061007    @app.route('/fail')1008    def fail():1009        flask.abort(404)10101011    with pytest.raises(NotFound):1012        client.get('/fail')101310141015def test_enctype_debug_helper(app, client):1016    from flask.debughelpers import DebugFilesKeyError1017    app.debug = True10181019    @app.route('/fail', methods=['POST'])1020    def index():1021        return flask.request.files['foo'].filename10221023    # with statement is important because we leave an exception on the1024    # stack otherwise and we want to ensure that this is not the case1025    # to not negatively affect other tests.1026    with client:1027        with pytest.raises(DebugFilesKeyError) as e:1028            client.post('/fail', data={'foo': 'index.txt'})1029        assert 'no file contents were transmitted' in str(e.value)1030        assert 'This was submitted: "index.txt"' in str(e.value)103110321033def test_response_types(app, client):1034    @app.route('/text')1035    def from_text():1036        return u'Hällo Wörld'10371038    @app.route('/bytes')1039    def from_bytes():1040        return u'Hällo Wörld'.encode('utf-8')10411042    @app.route('/full_tuple')1043    def from_full_tuple():1044        return 'Meh', 400, {1045            'X-Foo': 'Testing',1046            'Content-Type': 'text/plain; charset=utf-8'1047        }10481049    @app.route('/text_headers')1050    def from_text_headers():1051        return 'Hello', {1052            'X-Foo': 'Test',1053            'Content-Type': 'text/plain; charset=utf-8'1054        }10551056    @app.route('/text_status')1057    def from_text_status():1058        return 'Hi, status!', 40010591060    @app.route('/response_headers')1061    def from_response_headers():1062        return flask.Response('Hello world', 404, {'X-Foo': 'Baz'}), {1063            "X-Foo": "Bar",1064            "X-Bar": "Foo"1065        }10661067    @app.route('/response_status')1068    def from_response_status():1069        return app.response_class('Hello world', 400), 50010701071    @app.route('/wsgi')1072    def from_wsgi():1073        return NotFound()10741075    assert client.get('/text').data == u'Hällo Wörld'.encode('utf-8')1076    assert client.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')10771078    rv = client.get('/full_tuple')1079    assert rv.data == b'Meh'1080    assert rv.headers['X-Foo'] == 'Testing'1081    assert rv.status_code == 4001082    assert rv.mimetype == 'text/plain'10831084    rv = client.get('/text_headers')1085    assert rv.data == b'Hello'1086    assert rv.headers['X-Foo'] == 'Test'1087    assert rv.status_code == 2001088    assert rv.mimetype == 'text/plain'10891090    rv = client.get('/text_status')1091    assert rv.data == b'Hi, status!'1092    assert rv.status_code == 4001093    assert rv.mimetype == 'text/html'10941095    rv = client.get('/response_headers')1096    assert rv.data == b'Hello world'1097    assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar']1098    assert rv.headers['X-Bar'] == 'Foo'1099    assert rv.status_code == 40411001101    rv = client.get('/response_status')1102    assert rv.data == b'Hello world'1103    assert rv.status_code == 50011041105    rv = client.get('/wsgi')1106    assert b'Not Found' in rv.data1107    assert rv.status_code == 404110811091110def test_response_type_errors():1111    app = flask.Flask(__name__)1112    app.testing = True11131114    @app.route('/none')1115    def from_none():1116        pass11171118    @app.route('/small_tuple')1119    def from_small_tuple():1120        return 'Hello',11211122    @app.route('/large_tuple')1123    def from_large_tuple():1124        return 'Hello', 234, {'X-Foo': 'Bar'}, '???'11251126    @app.route('/bad_type')1127    def from_bad_type():1128        return True11291130    @app.route('/bad_wsgi')1131    def from_bad_wsgi():1132        return lambda: None11331134    c = app.test_client()11351136    with pytest.raises(TypeError) as e:1137        c.get('/none')1138        assert 'returned None' in str(e)11391140    with pytest.raises(TypeError) as e:1141        c.get('/small_tuple')1142        assert 'tuple must have the form' in str(e)11431144    pytest.raises(TypeError, c.get, '/large_tuple')11451146    with pytest.raises(TypeError) as e:1147        c.get('/bad_type')1148        assert 'it was a bool' in str(e)11491150    pytest.raises(TypeError, c.get, '/bad_wsgi')115111521153def test_make_response(app, req_ctx):1154    rv = flask.make_response()1155    assert rv.status_code == 2001156    assert rv.data == b''1157    assert rv.mimetype == 'text/html'11581159    rv = flask.make_response('Awesome')1160    assert rv.status_code == 2001161    assert rv.data == b'Awesome'1162    assert rv.mimetype == 'text/html'11631164    rv = flask.make_response('W00t', 404)1165    assert rv.status_code == 4041166    assert rv.data == b'W00t'1167    assert rv.mimetype == 'text/html'116811691170def test_make_response_with_response_instance(app, req_ctx):1171    rv = flask.make_response(1172        flask.jsonify({'msg': 'W00t'}), 400)1173    assert rv.status_code == 4001174    assert rv.data == b'{"msg":"W00t"}\n'1175    assert rv.mimetype == 'application/json'11761177    rv = flask.make_response(1178        flask.Response(''), 400)1179    assert rv.status_code == 4001180    assert rv.data == b''1181    assert rv.mimetype == 'text/html'11821183    rv = flask.make_response(1184        flask.Response('', headers={'Content-Type': 'text/html'}),1185        400, [('X-Foo', 'bar')])1186    assert rv.status_code == 4001187    assert rv.headers['Content-Type'] == 'text/html'1188    assert rv.headers['X-Foo'] == 'bar'118911901191def test_jsonify_no_prettyprint(app, req_ctx):1192    app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1193    compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1194    uncompressed_msg = {1195        "msg": {1196            "submsg": "W00t"1197        },1198        "msg2": "foobar"1199    }12001201    rv = flask.make_response(1202        flask.jsonify(uncompressed_msg), 200)1203    assert rv.data == compressed_msg120412051206def test_jsonify_prettyprint(app, req_ctx):1207    app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1208    compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1209    pretty_response = \1210        b'{\n  "msg": {\n    "submsg": "W00t"\n  }, \n  "msg2": "foobar"\n}\n'12111212    rv = flask.make_response(1213        flask.jsonify(compressed_msg), 200)1214    assert rv.data == pretty_response121512161217def test_jsonify_mimetype(app, req_ctx):1218    app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'})1219    msg = {1220        "msg": {"submsg": "W00t"},1221    }1222    rv = flask.make_response(1223        flask.jsonify(msg), 200)1224    assert rv.mimetype == 'application/vnd.api+json'122512261227def test_jsonify_args_and_kwargs_check(app, req_ctx):1228    with pytest.raises(TypeError) as e:1229        flask.jsonify('fake args', kwargs='fake')1230    assert 'behavior undefined' in str(e.value)123112321233def test_url_generation(app, req_ctx):1234    @app.route('/hello/<name>', methods=['POST'])1235    def hello():1236        pass12371238    assert flask.url_for('hello', name='test x') == '/hello/test%20x'1239    assert flask.url_for('hello', name='test x', _external=True) == \1240           'http://localhost/hello/test%20x'124112421243def test_build_error_handler(app):1244    # Test base case, a URL which results in a BuildError.1245    with app.test_request_context():1246        pytest.raises(BuildError, flask.url_for, 'spam')12471248    # Verify the error is re-raised if not the current exception.1249    try:1250        with app.test_request_context():1251            flask.url_for('spam')1252    except BuildError as err:1253        error = err1254    try:1255        raise RuntimeError('Test case where BuildError is not current.')1256    except RuntimeError:1257        pytest.raises(1258            BuildError, app.handle_url_build_error, error, 'spam', {})12591260    # Test a custom handler.1261    def handler(error, endpoint, values):1262        # Just a test.1263        return '/test_handler/'12641265    app.url_build_error_handlers.append(handler)1266    with app.test_request_context():1267        assert flask.url_for('spam') == '/test_handler/'126812691270def test_build_error_handler_reraise(app):1271    # Test a custom handler which reraises the BuildError1272    def handler_raises_build_error(error, endpoint, values):1273        raise error12741275    app.url_build_error_handlers.append(handler_raises_build_error)12761277    with app.test_request_context():1278        pytest.raises(BuildError, flask.url_for, 'not.existing')127912801281def test_url_for_passes_special_values_to_build_error_handler(app):1282    @app.url_build_error_handlers.append1283    def handler(error, endpoint, values):1284        assert values == {1285            '_external': False,1286            '_anchor': None,1287            '_method': None,1288            '_scheme': None,1289        }1290        return 'handled'12911292    with app.test_request_context():1293        flask.url_for('/')129412951296def test_custom_converters(app, client):1297    from werkzeug.routing import BaseConverter12981299    class ListConverter(BaseConverter):1300        def to_python(self, value):1301            return value.split(',')13021303        def to_url(self, value):1304            base_to_url = super(ListConverter, self).to_url1305            return ','.join(base_to_url(x) for x in value)13061307    app.url_map.converters['list'] = ListConverter13081309    @app.route('/<list:args>')1310    def index(args):1311        return '|'.join(args)13121313    assert client.get('/1,2,3').data == b'1|2|3'131413151316def test_static_files(app, client):1317    rv = client.get('/static/index.html')1318    assert rv.status_code == 2001319    assert rv.data.strip() == b'<h1>Hello World!</h1>'1320    with app.test_request_context():1321        assert flask.url_for('static', filename='index.html') == \1322               '/static/index.html'1323    rv.close()132413251326def test_static_path_deprecated(recwarn):1327    app = flask.Flask(__name__, static_path='/foo')1328    recwarn.pop(DeprecationWarning)13291330    app.testing = True1331    rv = app.test_client().get('/foo/index.html')1332    assert rv.status_code == 2001333    rv.close()13341335    with app.test_request_context():1336        assert flask.url_for('static', filename='index.html') == '/foo/index.html'133713381339def test_static_url_path():1340    app = flask.Flask(__name__, static_url_path='/foo')1341    app.testing = True1342    rv = app.test_client().get('/foo/index.html')1343    assert rv.status_code == 2001344    rv.close()13451346    with app.test_request_context():1347        assert flask.url_for('static', filename='index.html') == '/foo/index.html'134813491350def test_static_route_with_host_matching():1351    app = flask.Flask(__name__, host_matching=True, static_host='example.com')1352    c = app.test_client()1353    rv = c.get('http://example.com/static/index.html')1354    assert rv.status_code == 2001355    rv.close()1356    with app.test_request_context():1357        rv = flask.url_for('static', filename='index.html', _external=True)1358        assert rv == 'http://example.com/static/index.html'1359    # Providing static_host without host_matching=True should error.1360    with pytest.raises(Exception):1361        flask.Flask(__name__, static_host='example.com')1362    # Providing host_matching=True with static_folder but without static_host should error.1363    with pytest.raises(Exception):1364        flask.Flask(__name__, host_matching=True)1365    # Providing host_matching=True without static_host but with static_folder=None should not error.1366    flask.Flask(__name__, host_matching=True, static_folder=None)136713681369def test_request_locals():1370    assert repr(flask.g) == '<LocalProxy unbound>'1371    assert not flask.g137213731374def test_test_app_proper_environ(app, client):1375    app.config.update(1376        SERVER_NAME='localhost.localdomain:5000'1377    )13781379    @app.route('/')1380    def index():1381        return 'Foo'13821383    @app.route('/', subdomain='foo')1384    def subdomain():1385        return 'Foo SubDomain'13861387    rv = client.get('/')1388    assert rv.data == b'Foo'13891390    rv = client.get('/', 'http://localhost.localdomain:5000')1391    assert rv.data == b'Foo'13921393    rv = client.get('/', 'https://localhost.localdomain:5000')1394    assert rv.data == b'Foo'13951396    app.config.update(SERVER_NAME='localhost.localdomain')1397    rv = client.get('/', 'https://localhost.localdomain')1398    assert rv.data == b'Foo'13991400    try:1401        app.config.update(SERVER_NAME='localhost.localdomain:443')1402        rv = client.get('/', 'https://localhost.localdomain')1403        # Werkzeug 0.81404        assert rv.status_code == 4041405    except ValueError as e:1406        # Werkzeug 0.71407        assert str(e) == (1408            "the server name provided "1409            "('localhost.localdomain:443') does not match the "1410            "server name from the WSGI environment ('localhost.localdomain')"1411        )14121413    try:1414        app.config.update(SERVER_NAME='localhost.localdomain')1415        rv = client.get('/', 'http://foo.localhost')1416        # Werkzeug 0.81417        assert rv.status_code == 4041418    except ValueError as e:1419        # Werkzeug 0.71420        assert str(e) == (1421            "the server name provided "1422            "('localhost.localdomain') does not match the "1423            "server name from the WSGI environment ('foo.localhost')"1424        )14251426    rv = client.get('/', 'http://foo.localhost.localdomain')1427    assert rv.data == b'Foo SubDomain'142814291430def test_exception_propagation(app, client):1431    def apprunner(config_key):1432        app.config['LOGGER_HANDLER_POLICY'] = 'never'14331434        @app.route('/')1435        def index():1436            1 // 014371438        if config_key is not None:1439            app.config[config_key] = True1440            with pytest.raises(Exception):1441                client.get('/')1442        else:1443            assert client.get('/').status_code == 50014441445    # we have to run this test in an isolated thread because if the1446    # debug flag is set to true and an exception happens the context is1447    # not torn down.  This causes other tests that run after this fail1448    # when they expect no exception on the stack.1449    for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None:1450        t = Thread(target=apprunner, args=(config_key,))1451        t.start()1452        t.join()145314541455@pytest.mark.parametrize('debug', [True, False])1456@pytest.mark.parametrize('use_debugger', [True, False])1457@pytest.mark.parametrize('use_reloader', [True, False])1458@pytest.mark.parametrize('propagate_exceptions', [None, True, False])1459def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1460                                     use_reloader, propagate_exceptions, app):1461    rv = {}14621463    # Mocks werkzeug.serving.run_simple method1464    def run_simple_mock(*args, **kwargs):1465        rv['passthrough_errors'] = kwargs.get('passthrough_errors')14661467    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1468    app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1469    app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)147014711472def test_max_content_length(app, client):1473    app.config['MAX_CONTENT_LENGTH'] = 6414741475    @app.before_request1476    def always_first():1477        flask.request.form['myfile']1478        assert False14791480    @app.route('/accept', methods=['POST'])1481    def accept_file():1482        flask.request.form['myfile']1483        assert False14841485    @app.errorhandler(413)1486    def catcher(error):1487        return '42'14881489    rv = client.post('/accept', data={'myfile': 'foo' * 100})1490    assert rv.data == b'42'149114921493def test_url_processors(app, client):14941495    @app.url_defaults1496    def add_language_code(endpoint, values):1497        if flask.g.lang_code is not None and \1498                app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1499            values.setdefault('lang_code', flask.g.lang_code)15001501    @app.url_value_preprocessor1502    def pull_lang_code(endpoint, values):1503        flask.g.lang_code = values.pop('lang_code', None)15041505    @app.route('/<lang_code>/')1506    def index():1507        return flask.url_for('about')15081509    @app.route('/<lang_code>/about')1510    def about():1511        return flask.url_for('something_else')15121513    @app.route('/foo')1514    def something_else():1515        return flask.url_for('about', lang_code='en')15161517    assert client.get('/de/').data == b'/de/about'1518    assert client.get('/de/about').data == b'/foo'1519    assert client.get('/foo').data == b'/en/about'152015211522def test_inject_blueprint_url_defaults(app):1523    bp = flask.Blueprint('foo.bar.baz', __name__,1524                         template_folder='template')15251526    @bp.url_defaults1527    def bp_defaults(endpoint, values):1528        values['page'] = 'login'15291530    @bp.route('/<page>')1531    def view(page):1532        pass15331534    app.register_blueprint(bp)15351536    values = dict()1537    app.inject_url_defaults('foo.bar.baz.view', values)1538    expected = dict(page='login')1539    assert values == expected15401541    with app.test_request_context('/somepage'):1542        url = flask.url_for('foo.bar.baz.view')1543    expected = '/login'1544    assert url == expected154515461547def test_nonascii_pathinfo(app, client):1548    @app.route(u'/киртест')1549    def index():1550        return 'Hello World!'15511552    rv = client.get(u'/киртест')1553    assert rv.data == b'Hello World!'155415551556def test_debug_mode_complains_after_first_request(app, client):1557    app.debug = True15581559    @app.route('/')1560    def index():1561        return 'Awesome'15621563    assert not app.got_first_request1564    assert client.get('/').data == b'Awesome'1565    with pytest.raises(AssertionError) as e:1566        @app.route('/foo')1567        def broken():1568            return 'Meh'1569    assert 'A setup function was called' in str(e)15701571    app.debug = False15721573    @app.route('/foo')1574    def working():1575        return 'Meh'15761577    assert client.get('/foo').data == b'Meh'1578    assert app.got_first_request157915801581def test_before_first_request_functions(app, client):1582    got = []15831584    @app.before_first_request1585    def foo():1586        got.append(42)15871588    client.get('/')1589    assert got == [42]1590    client.get('/')1591    assert got == [42]1592    assert app.got_first_request159315941595def test_before_first_request_functions_concurrent(app, client):1596    got = []15971598    @app.before_first_request1599    def foo():1600        time.sleep(0.2)1601        got.append(42)16021603    def get_and_assert():1604        client.get("/")1605        assert got == [42]16061607    t = Thread(target=get_and_assert)1608    t.start()1609    get_and_assert()1610    t.join()1611    assert app.got_first_request161216131614def test_routing_redirect_debugging(app, client):1615    app.debug = True16161617    @app.route('/foo/', methods=['GET', 'POST'])1618    def foo():1619        return 'success'16201621    with client:1622        with pytest.raises(AssertionError) as e:1623            client.post('/foo', data={})1624        assert 'http://localhost/foo/' in str(e)1625        assert ('Make sure to directly send '1626                'your POST-request to this URL') in str(e)16271628        rv = client.get('/foo', data={}, follow_redirects=True)1629        assert rv.data == b'success'16301631    app.debug = False1632    with client:1633        rv = client.post('/foo', data={}, follow_redirects=True)1634        assert rv.data == b'success'163516361637def test_route_decorator_custom_endpoint(app, client):1638    app.debug = True16391640    @app.route('/foo/')1641    def foo():1642        return flask.request.endpoint16431644    @app.route('/bar/', endpoint='bar')1645    def for_bar():1646        return flask.request.endpoint16471648    @app.route('/bar/123', endpoint='123')1649    def for_bar_foo():1650        return flask.request.endpoint16511652    with app.test_request_context():1653        assert flask.url_for('foo') == '/foo/'1654        assert flask.url_for('bar') == '/bar/'1655        assert flask.url_for('123') == '/bar/123'16561657    assert client.get('/foo/').data == b'foo'1658    assert client.get('/bar/').data == b'bar'1659    assert client.get('/bar/123').data == b'123'166016611662def test_preserve_only_once(app, client):1663    app.debug = True16641665    @app.route('/fail')1666    def fail_func():1667        1 // 016681669    for x in range(3):1670        with pytest.raises(ZeroDivisionError):1671            client.get('/fail')16721673    assert flask._request_ctx_stack.top is not None1674    assert flask._app_ctx_stack.top is not None1675    # implicit appctx disappears too1676    flask._request_ctx_stack.top.pop()1677    assert flask._request_ctx_stack.top is None1678    assert flask._app_ctx_stack.top is None167916801681def test_preserve_remembers_exception(app, client):1682    app.debug = True1683    errors = []16841685    @app.route('/fail')1686    def fail_func():1687        1 // 016881689    @app.route('/success')1690    def success_func():1691        return 'Okay'16921693    @app.teardown_request1694    def teardown_handler(exc):1695        errors.append(exc)16961697    # After this failure we did not yet call the teardown handler1698    with pytest.raises(ZeroDivisionError):1699        client.get('/fail')1700    assert errors == []17011702    # But this request triggers it, and it's an error1703    client.get('/success')1704    assert len(errors) == 21705    assert isinstance(errors[0], ZeroDivisionError)17061707    # At this point another request does nothing.1708    client.get('/success')1709    assert len(errors) == 31710    assert errors[1] is None171117121713def test_get_method_on_g(app_ctx):1714    assert flask.g.get('x') is None1715    assert flask.g.get('x', 11) == 111716    flask.g.x = 421717    assert flask.g.get('x') == 421718    assert flask.g.x == 42171917201721def test_g_iteration_protocol(app_ctx):1722    flask.g.foo = 231723    flask.g.bar = 421724    assert 'foo' in flask.g1725    assert 'foos' not in flask.g1726    assert sorted(flask.g) == ['bar', 'foo']172717281729def test_subdomain_basic_support(app, client):1730    app.config['SERVER_NAME'] = 'localhost.localdomain'17311732    @app.route('/')1733    def normal_index():1734        return 'normal index'17351736    @app.route('/', subdomain='test')1737    def test_index():1738        return 'test index'17391740    rv = client.get('/', 'http://localhost.localdomain/')1741    assert rv.data == b'normal index'17421743    rv = client.get('/', 'http://test.localhost.localdomain/')1744    assert rv.data == b'test index'174517461747def test_subdomain_matching(app, client):1748    app.config['SERVER_NAME'] = 'localhost.localdomain'17491750    @app.route('/', subdomain='<user>')1751    def index(user):1752        return 'index for %s' % user17531754    rv = client.get('/', 'http://mitsuhiko.localhost.localdomain/')1755    assert rv.data == b'index for mitsuhiko'175617571758def test_subdomain_matching_with_ports(app, client):1759    app.config['SERVER_NAME'] = 'localhost.localdomain:3000'17601761    @app.route('/', subdomain='<user>')1762    def index(user):1763        return 'index for %s' % user17641765    rv = client.get('/', 'http://mitsuhiko.localhost.localdomain:3000/')1766    assert rv.data == b'index for mitsuhiko'176717681769def test_multi_route_rules(app, client):1770    @app.route('/')1771    @app.route('/<test>/')1772    def index(test='a'):1773        return test17741775    rv = client.open('/')1776    assert rv.data == b'a'1777    rv = client.open('/b/')1778    assert rv.data == b'b'177917801781def test_multi_route_class_views(app, client):1782    class View(object):1783        def __init__(self, app):1784            app.add_url_rule('/', 'index', self.index)1785            app.add_url_rule('/<test>/', 'index', self.index)17861787        def index(self, test='a'):1788            return test17891790    _ = View(app)1791    rv = client.open('/')1792    assert rv.data == b'a'1793    rv = client.open('/b/')1794    assert rv.data == b'b'179517961797def test_run_defaults(monkeypatch, app):1798    rv = {}17991800    # Mocks werkzeug.serving.run_simple method1801    def run_simple_mock(*args, **kwargs):1802        rv['result'] = 'running...'18031804    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1805    app.run()1806    assert rv['result'] == 'running...'180718081809def test_run_server_port(monkeypatch, app):1810    rv = {}18111812    # Mocks werkzeug.serving.run_simple method1813    def run_simple_mock(hostname, port, application, *args, **kwargs):1814        rv['result'] = 'running on %s:%s ...' % (hostname, port)18151816    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1817    hostname, port = 'localhost', 80001818    app.run(hostname, port, debug=True)1819    assert rv['result'] == 'running on %s:%s ...' % (hostname, port)182018211822@pytest.mark.parametrize('host,port,expect_host,expect_port', (1823        (None, None, 'pocoo.org', 8080),1824        ('localhost', None, 'localhost', 8080),1825        (None, 80, 'pocoo.org', 80),1826        ('localhost', 80, 'localhost', 80),1827))1828def test_run_from_config(monkeypatch, host, port, expect_host, expect_port, app):1829    def run_simple_mock(hostname, port, *args, **kwargs):1830        assert hostname == expect_host1831        assert port == expect_port18321833    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1834    app.config['SERVER_NAME'] = 'pocoo.org:8080'1835    app.run(host, port)