Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

1,816 lines · 48.4 KiB · Python

Last changed by

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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 pytest1314import re15import uuid16import time17import flask18import pickle19from datetime import datetime20from threading import Thread21from flask._compat import text_type22from werkzeug.exceptions import BadRequest, NotFound, Forbidden23from werkzeug.http import parse_date24from werkzeug.routing import BuildError25import werkzeug.serving262728def test_options_work(app, client):29    @app.route('/', methods=['GET', 'POST'])30    def index():31        return 'Hello World'3233    rv = client.open('/', method='OPTIONS')34    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']35    assert rv.data == b''363738def test_options_on_multiple_rules(app, client):39    @app.route('/', methods=['GET', 'POST'])40    def index():41        return 'Hello World'4243    @app.route('/', methods=['PUT'])44    def index_put():45        return 'Aha!'4647    rv = client.open('/', method='OPTIONS')48    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']495051def test_provide_automatic_options_attr():52    app = flask.Flask(__name__)5354    def index():55        return 'Hello World!'5657    index.provide_automatic_options = False58    app.route('/')(index)59    rv = app.test_client().open('/', method='OPTIONS')60    assert rv.status_code == 4056162    app = flask.Flask(__name__)6364    def index2():65        return 'Hello World!'6667    index2.provide_automatic_options = True68    app.route('/', methods=['OPTIONS'])(index2)69    rv = app.test_client().open('/', method='OPTIONS')70    assert sorted(rv.allow) == ['OPTIONS']717273def test_provide_automatic_options_kwarg(app, client):74    def index():75        return flask.request.method7677    def more():78        return flask.request.method7980    app.add_url_rule('/', view_func=index, provide_automatic_options=False)81    app.add_url_rule(82        '/more', view_func=more, methods=['GET', 'POST'],83        provide_automatic_options=False84    )85    assert client.get('/').data == b'GET'8687    rv = client.post('/')88    assert rv.status_code == 40589    assert sorted(rv.allow) == ['GET', 'HEAD']9091    # Older versions of Werkzeug.test.Client don't have an options method92    if hasattr(client, 'options'):93        rv = client.options('/')94    else:95        rv = client.open('/', method='OPTIONS')9697    assert rv.status_code == 4059899    rv = client.head('/')100    assert rv.status_code == 200101    assert not rv.data  # head truncates102    assert client.post('/more').data == b'POST'103    assert client.get('/more').data == b'GET'104105    rv = client.delete('/more')106    assert rv.status_code == 405107    assert sorted(rv.allow) == ['GET', 'HEAD', 'POST']108109    if hasattr(client, 'options'):110        rv = client.options('/more')111    else:112        rv = client.open('/more', method='OPTIONS')113114    assert rv.status_code == 405115116117def test_request_dispatching(app, client):118    @app.route('/')119    def index():120        return flask.request.method121122    @app.route('/more', methods=['GET', 'POST'])123    def more():124        return flask.request.method125126    assert client.get('/').data == b'GET'127    rv = client.post('/')128    assert rv.status_code == 405129    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']130    rv = client.head('/')131    assert rv.status_code == 200132    assert not rv.data  # head truncates133    assert client.post('/more').data == b'POST'134    assert client.get('/more').data == b'GET'135    rv = client.delete('/more')136    assert rv.status_code == 405137    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']138139140def test_disallow_string_for_allowed_methods(app):141    with pytest.raises(TypeError):142        @app.route('/', methods='GET POST')143        def index():144            return "Hey"145146147def test_url_mapping(app, client):148    random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"149150    def index():151        return flask.request.method152153    def more():154        return flask.request.method155156    def options():157        return random_uuid4158159    app.add_url_rule('/', 'index', index)160    app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])161162    # Issue 1288: Test that automatic options are not added when non-uppercase 'options' in methods163    app.add_url_rule('/options', 'options', options, methods=['options'])164165    assert client.get('/').data == b'GET'166    rv = client.post('/')167    assert rv.status_code == 405168    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']169    rv = client.head('/')170    assert rv.status_code == 200171    assert not rv.data  # head truncates172    assert client.post('/more').data == b'POST'173    assert client.get('/more').data == b'GET'174    rv = client.delete('/more')175    assert rv.status_code == 405176    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']177    rv = client.open('/options', method='OPTIONS')178    assert rv.status_code == 200179    assert random_uuid4 in rv.data.decode("utf-8")180181182def test_werkzeug_routing(app, client):183    from werkzeug.routing import Submount, Rule184    app.url_map.add(Submount('/foo', [185        Rule('/bar', endpoint='bar'),186        Rule('/', endpoint='index')187    ]))188189    def bar():190        return 'bar'191192    def index():193        return 'index'194195    app.view_functions['bar'] = bar196    app.view_functions['index'] = index197198    assert client.get('/foo/').data == b'index'199    assert client.get('/foo/bar').data == b'bar'200201202def test_endpoint_decorator(app, client):203    from werkzeug.routing import Submount, Rule204    app.url_map.add(Submount('/foo', [205        Rule('/bar', endpoint='bar'),206        Rule('/', endpoint='index')207    ]))208209    @app.endpoint('bar')210    def bar():211        return 'bar'212213    @app.endpoint('index')214    def index():215        return 'index'216217    assert client.get('/foo/').data == b'index'218    assert client.get('/foo/bar').data == b'bar'219220221def test_session(app, client):222    app.secret_key = 'testkey'223224    @app.route('/set', methods=['POST'])225    def set():226        flask.session['value'] = flask.request.form['value']227        return 'value set'228229    @app.route('/get')230    def get():231        return flask.session['value']232233    assert client.post('/set', data={'value': '42'}).data == b'value set'234    assert client.get('/get').data == b'42'235236237def test_session_using_server_name(app, client):238    app.config.update(239        SECRET_KEY='foo',240        SERVER_NAME='example.com'241    )242243    @app.route('/')244    def index():245        flask.session['testing'] = 42246        return 'Hello World'247248    rv = client.get('/', 'http://example.com/')249    assert 'domain=.example.com' in rv.headers['set-cookie'].lower()250    assert 'httponly' in rv.headers['set-cookie'].lower()251252253def test_session_using_server_name_and_port(app, client):254    app.config.update(255        SECRET_KEY='foo',256        SERVER_NAME='example.com:8080'257    )258259    @app.route('/')260    def index():261        flask.session['testing'] = 42262        return 'Hello World'263264    rv = client.get('/', 'http://example.com:8080/')265    assert 'domain=.example.com' in rv.headers['set-cookie'].lower()266    assert 'httponly' in rv.headers['set-cookie'].lower()267268269def test_session_using_server_name_port_and_path(app, client):270    app.config.update(271        SECRET_KEY='foo',272        SERVER_NAME='example.com:8080',273        APPLICATION_ROOT='/foo'274    )275276    @app.route('/')277    def index():278        flask.session['testing'] = 42279        return 'Hello World'280281    rv = client.get('/', 'http://example.com:8080/foo')282    assert 'domain=example.com' in rv.headers['set-cookie'].lower()283    assert 'path=/foo' in rv.headers['set-cookie'].lower()284    assert 'httponly' in rv.headers['set-cookie'].lower()285286287def test_session_using_application_root(app, client):288    class PrefixPathMiddleware(object):289        def __init__(self, app, prefix):290            self.app = app291            self.prefix = prefix292293        def __call__(self, environ, start_response):294            environ['SCRIPT_NAME'] = self.prefix295            return self.app(environ, start_response)296297    app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar')298    app.config.update(299        SECRET_KEY='foo',300        APPLICATION_ROOT='/bar'301    )302303    @app.route('/')304    def index():305        flask.session['testing'] = 42306        return 'Hello World'307308    rv = client.get('/', 'http://example.com:8080/')309    assert 'path=/bar' in rv.headers['set-cookie'].lower()310311312def test_session_using_session_settings(app, client):313    app.config.update(314        SECRET_KEY='foo',315        SERVER_NAME='www.example.com:8080',316        APPLICATION_ROOT='/test',317        SESSION_COOKIE_DOMAIN='.example.com',318        SESSION_COOKIE_HTTPONLY=False,319        SESSION_COOKIE_SECURE=True,320        SESSION_COOKIE_PATH='/'321    )322323    @app.route('/')324    def index():325        flask.session['testing'] = 42326        return 'Hello World'327328    rv = client.get('/', 'http://www.example.com:8080/test/')329    cookie = rv.headers['set-cookie'].lower()330    assert 'domain=.example.com' in cookie331    assert 'path=/' in cookie332    assert 'secure' in cookie333    assert 'httponly' not in cookie334335336def test_session_localhost_warning(recwarn, app, client):337    app.config.update(338        SECRET_KEY='testing',339        SERVER_NAME='localhost:5000',340    )341342    @app.route('/')343    def index():344        flask.session['testing'] = 42345        return 'testing'346347    rv = client.get('/', 'http://localhost:5000/')348    assert 'domain' not in rv.headers['set-cookie'].lower()349    w = recwarn.pop(UserWarning)350    assert '"localhost" is not a valid cookie domain' in str(w.message)351352353def test_session_ip_warning(recwarn, app, client):354    app.config.update(355        SECRET_KEY='testing',356        SERVER_NAME='127.0.0.1:5000',357    )358359    @app.route('/')360    def index():361        flask.session['testing'] = 42362        return 'testing'363364    rv = client.get('/', 'http://127.0.0.1:5000/')365    assert 'domain=127.0.0.1' in rv.headers['set-cookie'].lower()366    w = recwarn.pop(UserWarning)367    assert 'cookie domain is an IP' in str(w.message)368369370def test_missing_session():371    app = flask.Flask(__name__)372373    def expect_exception(f, *args, **kwargs):374        e = pytest.raises(RuntimeError, f, *args, **kwargs)375        assert e.value.args and 'session is unavailable' in e.value.args[0]376377    with app.test_request_context():378        assert flask.session.get('missing_key') is None379        expect_exception(flask.session.__setitem__, 'foo', 42)380        expect_exception(flask.session.pop, 'foo')381382383def test_session_expiration(app, client):384    permanent = True385    app.secret_key = 'testkey'386387    @app.route('/')388    def index():389        flask.session['test'] = 42390        flask.session.permanent = permanent391        return ''392393    @app.route('/test')394    def test():395        return text_type(flask.session.permanent)396397    rv = client.get('/')398    assert 'set-cookie' in rv.headers399    match = re.search(r'(?i)\bexpires=([^;]+)', rv.headers['set-cookie'])400    expires = parse_date(match.group())401    expected = datetime.utcnow() + app.permanent_session_lifetime402    assert expires.year == expected.year403    assert expires.month == expected.month404    assert expires.day == expected.day405406    rv = client.get('/test')407    assert rv.data == b'True'408409    permanent = False410    rv = client.get('/')411    assert 'set-cookie' in rv.headers412    match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])413    assert match is None414415416def test_session_stored_last(app, client):417    app.secret_key = 'development-key'418419    @app.after_request420    def modify_session(response):421        flask.session['foo'] = 42422        return response423424    @app.route('/')425    def dump_session_contents():426        return repr(flask.session.get('foo'))427428    assert client.get('/').data == b'None'429    assert client.get('/').data == b'42'430431432def test_session_special_types(app, client):433    app.secret_key = 'development-key'434    now = datetime.utcnow().replace(microsecond=0)435    the_uuid = uuid.uuid4()436437    @app.after_request438    def modify_session(response):439        flask.session['m'] = flask.Markup('Hello!')440        flask.session['u'] = the_uuid441        flask.session['dt'] = now442        flask.session['b'] = b'\xff'443        flask.session['t'] = (1, 2, 3)444        return response445446    @app.route('/')447    def dump_session_contents():448        return pickle.dumps(dict(flask.session))449450    client.get('/')451    rv = pickle.loads(client.get('/').data)452    assert rv['m'] == flask.Markup('Hello!')453    assert type(rv['m']) == flask.Markup454    assert rv['dt'] == now455    assert rv['u'] == the_uuid456    assert rv['b'] == b'\xff'457    assert type(rv['b']) == bytes458    assert rv['t'] == (1, 2, 3)459460461def test_session_cookie_setting(app):462    app.secret_key = 'dev key'463    is_permanent = True464465    @app.route('/bump')466    def bump():467        rv = flask.session['foo'] = flask.session.get('foo', 0) + 1468        flask.session.permanent = is_permanent469        return str(rv)470471    @app.route('/read')472    def read():473        return str(flask.session.get('foo', 0))474475    def run_test(expect_header):476        with app.test_client() as c:477            assert c.get('/bump').data == b'1'478            assert c.get('/bump').data == b'2'479            assert c.get('/bump').data == b'3'480481            rv = c.get('/read')482            set_cookie = rv.headers.get('set-cookie')483            assert (set_cookie is not None) == expect_header484            assert rv.data == b'3'485486    is_permanent = True487    app.config['SESSION_REFRESH_EACH_REQUEST'] = True488    run_test(expect_header=True)489490    is_permanent = True491    app.config['SESSION_REFRESH_EACH_REQUEST'] = False492    run_test(expect_header=False)493494    is_permanent = False495    app.config['SESSION_REFRESH_EACH_REQUEST'] = True496    run_test(expect_header=False)497498    is_permanent = False499    app.config['SESSION_REFRESH_EACH_REQUEST'] = False500    run_test(expect_header=False)501502503def test_session_vary_cookie(app, client):504    app.secret_key = 'testkey'505506    @app.route('/set')507    def set_session():508        flask.session['test'] = 'test'509        return ''510511    @app.route('/get')512    def get():513        return flask.session.get('test')514515    @app.route('/getitem')516    def getitem():517        return flask.session['test']518519    @app.route('/setdefault')520    def setdefault():521        return flask.session.setdefault('test', 'default')522523    @app.route('/vary-cookie-header-set')524    def vary_cookie_header_set():525        response = flask.Response()526        response.headers['Vary'] = 'Cookie'527        flask.session['test'] = 'test'528        return response529530    @app.route('/vary-header-set')531    def vary_header_set():532        response = flask.Response()533        response.headers['Vary'] = 'Accept-Encoding, Accept-Language'534        flask.session['test'] = 'test'535        return response536537    @app.route('/no-vary-header')538    def no_vary_header():539        return ''540541    def expect(path, header_value='Cookie'):542        rv = client.get(path)543544        if header_value:545            # The 'Vary' key should exist in the headers only once.546            assert len(rv.headers.get_all('Vary')) == 1547            assert rv.headers['Vary'] == header_value548        else:549            assert 'Vary' not in rv.headers550551    expect('/set')552    expect('/get')553    expect('/getitem')554    expect('/setdefault')555    expect('/vary-cookie-header-set')556    expect('/vary-header-set', 'Accept-Encoding, Accept-Language, Cookie')557    expect('/no-vary-header', None)558559560def test_flashes(app, req_ctx):561    app.secret_key = 'testkey'562563    assert not flask.session.modified564    flask.flash('Zap')565    flask.session.modified = False566    flask.flash('Zip')567    assert flask.session.modified568    assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']569570571def test_extended_flashing(app):572    # Be sure app.testing=True below, else tests can fail silently.573    #574    # Specifically, if app.testing is not set to True, the AssertionErrors575    # in the view functions will cause a 500 response to the test client576    # instead of propagating exceptions.577578    app.secret_key = 'testkey'579580    @app.route('/')581    def index():582        flask.flash(u'Hello World')583        flask.flash(u'Hello World', 'error')584        flask.flash(flask.Markup(u'<em>Testing</em>'), 'warning')585        return ''586587    @app.route('/test/')588    def test():589        messages = flask.get_flashed_messages()590        assert list(messages) == [591            u'Hello World',592            u'Hello World',593            flask.Markup(u'<em>Testing</em>')594        ]595        return ''596597    @app.route('/test_with_categories/')598    def test_with_categories():599        messages = flask.get_flashed_messages(with_categories=True)600        assert len(messages) == 3601        assert list(messages) == [602            ('message', u'Hello World'),603            ('error', u'Hello World'),604            ('warning', flask.Markup(u'<em>Testing</em>'))605        ]606        return ''607608    @app.route('/test_filter/')609    def test_filter():610        messages = flask.get_flashed_messages(611            category_filter=['message'], with_categories=True)612        assert list(messages) == [('message', u'Hello World')]613        return ''614615    @app.route('/test_filters/')616    def test_filters():617        messages = flask.get_flashed_messages(618            category_filter=['message', 'warning'], with_categories=True)619        assert list(messages) == [620            ('message', u'Hello World'),621            ('warning', flask.Markup(u'<em>Testing</em>'))622        ]623        return ''624625    @app.route('/test_filters_without_returning_categories/')626    def test_filters2():627        messages = flask.get_flashed_messages(628            category_filter=['message', 'warning'])629        assert len(messages) == 2630        assert messages[0] == u'Hello World'631        assert messages[1] == flask.Markup(u'<em>Testing</em>')632        return ''633634    # Create new test client on each test to clean flashed messages.635636    client = app.test_client()637    client.get('/')638    client.get('/test_with_categories/')639640    client = app.test_client()641    client.get('/')642    client.get('/test_filter/')643644    client = app.test_client()645    client.get('/')646    client.get('/test_filters/')647648    client = app.test_client()649    client.get('/')650    client.get('/test_filters_without_returning_categories/')651652653def test_request_processing(app, client):654    evts = []655656    @app.before_request657    def before_request():658        evts.append('before')659660    @app.after_request661    def after_request(response):662        response.data += b'|after'663        evts.append('after')664        return response665666    @app.route('/')667    def index():668        assert 'before' in evts669        assert 'after' not in evts670        return 'request'671672    assert 'after' not in evts673    rv = client.get('/').data674    assert 'after' in evts675    assert rv == b'request|after'676677678def test_request_preprocessing_early_return(app, client):679    evts = []680681    @app.before_request682    def before_request1():683        evts.append(1)684685    @app.before_request686    def before_request2():687        evts.append(2)688        return "hello"689690    @app.before_request691    def before_request3():692        evts.append(3)693        return "bye"694695    @app.route('/')696    def index():697        evts.append('index')698        return "damnit"699700    rv = client.get('/').data.strip()701    assert rv == b'hello'702    assert evts == [1, 2]703704705def test_after_request_processing(app, client):706    @app.route('/')707    def index():708        @flask.after_this_request709        def foo(response):710            response.headers['X-Foo'] = 'a header'711            return response712713        return 'Test'714715    resp = client.get('/')716    assert resp.status_code == 200717    assert resp.headers['X-Foo'] == 'a header'718719720def test_teardown_request_handler(app, client):721    called = []722723    @app.teardown_request724    def teardown_request(exc):725        called.append(True)726        return "Ignored"727728    @app.route('/')729    def root():730        return "Response"731732    rv = client.get('/')733    assert rv.status_code == 200734    assert b'Response' in rv.data735    assert len(called) == 1736737738def test_teardown_request_handler_debug_mode(app, client):739    called = []740741    @app.teardown_request742    def teardown_request(exc):743        called.append(True)744        return "Ignored"745746    @app.route('/')747    def root():748        return "Response"749750    rv = client.get('/')751    assert rv.status_code == 200752    assert b'Response' in rv.data753    assert len(called) == 1754755756def test_teardown_request_handler_error(app, client):757    called = []758    app.config['LOGGER_HANDLER_POLICY'] = 'never'759    app.testing = False760761    @app.teardown_request762    def teardown_request1(exc):763        assert type(exc) == ZeroDivisionError764        called.append(True)765        # This raises a new error and blows away sys.exc_info(), so we can766        # test that all teardown_requests get passed the same original767        # exception.768        try:769            raise TypeError()770        except:771            pass772773    @app.teardown_request774    def teardown_request2(exc):775        assert type(exc) == ZeroDivisionError776        called.append(True)777        # This raises a new error and blows away sys.exc_info(), so we can778        # test that all teardown_requests get passed the same original779        # exception.780        try:781            raise TypeError()782        except:783            pass784785    @app.route('/')786    def fails():787        1 // 0788789    rv = client.get('/')790    assert rv.status_code == 500791    assert b'Internal Server Error' in rv.data792    assert len(called) == 2793794795def test_before_after_request_order(app, client):796    called = []797798    @app.before_request799    def before1():800        called.append(1)801802    @app.before_request803    def before2():804        called.append(2)805806    @app.after_request807    def after1(response):808        called.append(4)809        return response810811    @app.after_request812    def after2(response):813        called.append(3)814        return response815816    @app.teardown_request817    def finish1(exc):818        called.append(6)819820    @app.teardown_request821    def finish2(exc):822        called.append(5)823824    @app.route('/')825    def index():826        return '42'827828    rv = client.get('/')829    assert rv.data == b'42'830    assert called == [1, 2, 3, 4, 5, 6]831832833def test_error_handling(app, client):834    app.config['LOGGER_HANDLER_POLICY'] = 'never'835    app.testing = False836837    @app.errorhandler(404)838    def not_found(e):839        return 'not found', 404840841    @app.errorhandler(500)842    def internal_server_error(e):843        return 'internal server error', 500844845    @app.errorhandler(Forbidden)846    def forbidden(e):847        return 'forbidden', 403848849    @app.route('/')850    def index():851        flask.abort(404)852853    @app.route('/error')854    def error():855        1 // 0856857    @app.route('/forbidden')858    def error2():859        flask.abort(403)860861    rv = client.get('/')862    assert rv.status_code == 404863    assert rv.data == b'not found'864    rv = client.get('/error')865    assert rv.status_code == 500866    assert b'internal server error' == rv.data867    rv = client.get('/forbidden')868    assert rv.status_code == 403869    assert b'forbidden' == rv.data870871872def test_error_handling_processing(app, client):873    app.config['LOGGER_HANDLER_POLICY'] = 'never'874    app.testing = False875876    @app.errorhandler(500)877    def internal_server_error(e):878        return 'internal server error', 500879880    @app.route('/')881    def broken_func():882        1 // 0883884    @app.after_request885    def after_request(resp):886        resp.mimetype = 'text/x-special'887        return resp888889    resp = client.get('/')890    assert resp.mimetype == 'text/x-special'891    assert resp.data == b'internal server error'892893894def test_baseexception_error_handling(app, client):895    app.config['LOGGER_HANDLER_POLICY'] = 'never'896    app.testing = False897898    @app.route('/')899    def broken_func():900        raise KeyboardInterrupt()901902    with pytest.raises(KeyboardInterrupt):903        client.get('/')904905        ctx = flask._request_ctx_stack.top906        assert ctx.preserved907        assert type(ctx._preserved_exc) is KeyboardInterrupt908909910def test_before_request_and_routing_errors(app, client):911    @app.before_request912    def attach_something():913        flask.g.something = 'value'914915    @app.errorhandler(404)916    def return_something(error):917        return flask.g.something, 404918919    rv = client.get('/')920    assert rv.status_code == 404921    assert rv.data == b'value'922923924def test_user_error_handling(app, client):925    class MyException(Exception):926        pass927928    @app.errorhandler(MyException)929    def handle_my_exception(e):930        assert isinstance(e, MyException)931        return '42'932933    @app.route('/')934    def index():935        raise MyException()936937    assert client.get('/').data == b'42'938939940def test_http_error_subclass_handling(app, client):941    class ForbiddenSubclass(Forbidden):942        pass943944    @app.errorhandler(ForbiddenSubclass)945    def handle_forbidden_subclass(e):946        assert isinstance(e, ForbiddenSubclass)947        return 'banana'948949    @app.errorhandler(403)950    def handle_forbidden_subclass(e):951        assert not isinstance(e, ForbiddenSubclass)952        assert isinstance(e, Forbidden)953        return 'apple'954955    @app.route('/1')956    def index1():957        raise ForbiddenSubclass()958959    @app.route('/2')960    def index2():961        flask.abort(403)962963    @app.route('/3')964    def index3():965        raise Forbidden()966967    assert client.get('/1').data == b'banana'968    assert client.get('/2').data == b'apple'969    assert client.get('/3').data == b'apple'970971972def test_trapping_of_bad_request_key_errors(app, client):973    @app.route('/fail')974    def fail():975        flask.request.form['missing_key']976977    assert client.get('/fail').status_code == 400978979    app.config['TRAP_BAD_REQUEST_ERRORS'] = True980    with pytest.raises(KeyError) as e:981        client.get("/fail")982    assert e.errisinstance(BadRequest)983984985def test_trapping_of_all_http_exceptions(app, client):986    app.config['TRAP_HTTP_EXCEPTIONS'] = True987988    @app.route('/fail')989    def fail():990        flask.abort(404)991992    with pytest.raises(NotFound):993        client.get('/fail')994995996def test_enctype_debug_helper(app, client):997    from flask.debughelpers import DebugFilesKeyError998    app.debug = True9991000    @app.route('/fail', methods=['POST'])1001    def index():1002        return flask.request.files['foo'].filename10031004    # with statement is important because we leave an exception on the1005    # stack otherwise and we want to ensure that this is not the case1006    # to not negatively affect other tests.1007    with client:1008        with pytest.raises(DebugFilesKeyError) as e:1009            client.post('/fail', data={'foo': 'index.txt'})1010        assert 'no file contents were transmitted' in str(e.value)1011        assert 'This was submitted: "index.txt"' in str(e.value)101210131014def test_response_types(app, client):1015    @app.route('/text')1016    def from_text():1017        return u'Hällo Wörld'10181019    @app.route('/bytes')1020    def from_bytes():1021        return u'Hällo Wörld'.encode('utf-8')10221023    @app.route('/full_tuple')1024    def from_full_tuple():1025        return 'Meh', 400, {1026            'X-Foo': 'Testing',1027            'Content-Type': 'text/plain; charset=utf-8'1028        }10291030    @app.route('/text_headers')1031    def from_text_headers():1032        return 'Hello', {1033            'X-Foo': 'Test',1034            'Content-Type': 'text/plain; charset=utf-8'1035        }10361037    @app.route('/text_status')1038    def from_text_status():1039        return 'Hi, status!', 40010401041    @app.route('/response_headers')1042    def from_response_headers():1043        return flask.Response('Hello world', 404, {'X-Foo': 'Baz'}), {1044            "X-Foo": "Bar",1045            "X-Bar": "Foo"1046        }10471048    @app.route('/response_status')1049    def from_response_status():1050        return app.response_class('Hello world', 400), 50010511052    @app.route('/wsgi')1053    def from_wsgi():1054        return NotFound()10551056    assert client.get('/text').data == u'Hällo Wörld'.encode('utf-8')1057    assert client.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')10581059    rv = client.get('/full_tuple')1060    assert rv.data == b'Meh'1061    assert rv.headers['X-Foo'] == 'Testing'1062    assert rv.status_code == 4001063    assert rv.mimetype == 'text/plain'10641065    rv = client.get('/text_headers')1066    assert rv.data == b'Hello'1067    assert rv.headers['X-Foo'] == 'Test'1068    assert rv.status_code == 2001069    assert rv.mimetype == 'text/plain'10701071    rv = client.get('/text_status')1072    assert rv.data == b'Hi, status!'1073    assert rv.status_code == 4001074    assert rv.mimetype == 'text/html'10751076    rv = client.get('/response_headers')1077    assert rv.data == b'Hello world'1078    assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar']1079    assert rv.headers['X-Bar'] == 'Foo'1080    assert rv.status_code == 40410811082    rv = client.get('/response_status')1083    assert rv.data == b'Hello world'1084    assert rv.status_code == 50010851086    rv = client.get('/wsgi')1087    assert b'Not Found' in rv.data1088    assert rv.status_code == 404108910901091def test_response_type_errors():1092    app = flask.Flask(__name__)1093    app.testing = True10941095    @app.route('/none')1096    def from_none():1097        pass10981099    @app.route('/small_tuple')1100    def from_small_tuple():1101        return 'Hello',11021103    @app.route('/large_tuple')1104    def from_large_tuple():1105        return 'Hello', 234, {'X-Foo': 'Bar'}, '???'11061107    @app.route('/bad_type')1108    def from_bad_type():1109        return True11101111    @app.route('/bad_wsgi')1112    def from_bad_wsgi():1113        return lambda: None11141115    c = app.test_client()11161117    with pytest.raises(TypeError) as e:1118        c.get('/none')1119        assert 'returned None' in str(e)11201121    with pytest.raises(TypeError) as e:1122        c.get('/small_tuple')1123        assert 'tuple must have the form' in str(e)11241125    pytest.raises(TypeError, c.get, '/large_tuple')11261127    with pytest.raises(TypeError) as e:1128        c.get('/bad_type')1129        assert 'it was a bool' in str(e)11301131    pytest.raises(TypeError, c.get, '/bad_wsgi')113211331134def test_make_response(app, req_ctx):1135    rv = flask.make_response()1136    assert rv.status_code == 2001137    assert rv.data == b''1138    assert rv.mimetype == 'text/html'11391140    rv = flask.make_response('Awesome')1141    assert rv.status_code == 2001142    assert rv.data == b'Awesome'1143    assert rv.mimetype == 'text/html'11441145    rv = flask.make_response('W00t', 404)1146    assert rv.status_code == 4041147    assert rv.data == b'W00t'1148    assert rv.mimetype == 'text/html'114911501151def test_make_response_with_response_instance(app, req_ctx):1152    rv = flask.make_response(1153        flask.jsonify({'msg': 'W00t'}), 400)1154    assert rv.status_code == 4001155    assert rv.data == b'{"msg":"W00t"}\n'1156    assert rv.mimetype == 'application/json'11571158    rv = flask.make_response(1159        flask.Response(''), 400)1160    assert rv.status_code == 4001161    assert rv.data == b''1162    assert rv.mimetype == 'text/html'11631164    rv = flask.make_response(1165        flask.Response('', headers={'Content-Type': 'text/html'}),1166        400, [('X-Foo', 'bar')])1167    assert rv.status_code == 4001168    assert rv.headers['Content-Type'] == 'text/html'1169    assert rv.headers['X-Foo'] == 'bar'117011711172def test_jsonify_no_prettyprint(app, req_ctx):1173    app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1174    compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1175    uncompressed_msg = {1176        "msg": {1177            "submsg": "W00t"1178        },1179        "msg2": "foobar"1180    }11811182    rv = flask.make_response(1183        flask.jsonify(uncompressed_msg), 200)1184    assert rv.data == compressed_msg118511861187def test_jsonify_prettyprint(app, req_ctx):1188    app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1189    compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1190    pretty_response = \1191        b'{\n  "msg": {\n    "submsg": "W00t"\n  }, \n  "msg2": "foobar"\n}\n'11921193    rv = flask.make_response(1194        flask.jsonify(compressed_msg), 200)1195    assert rv.data == pretty_response119611971198def test_jsonify_mimetype(app, req_ctx):1199    app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'})1200    msg = {1201        "msg": {"submsg": "W00t"},1202    }1203    rv = flask.make_response(1204        flask.jsonify(msg), 200)1205    assert rv.mimetype == 'application/vnd.api+json'120612071208def test_jsonify_args_and_kwargs_check(app, req_ctx):1209    with pytest.raises(TypeError) as e:1210        flask.jsonify('fake args', kwargs='fake')1211    assert 'behavior undefined' in str(e.value)121212131214def test_url_generation(app, req_ctx):1215    @app.route('/hello/<name>', methods=['POST'])1216    def hello():1217        pass12181219    assert flask.url_for('hello', name='test x') == '/hello/test%20x'1220    assert flask.url_for('hello', name='test x', _external=True) == \1221           'http://localhost/hello/test%20x'122212231224def test_build_error_handler(app):1225    # Test base case, a URL which results in a BuildError.1226    with app.test_request_context():1227        pytest.raises(BuildError, flask.url_for, 'spam')12281229    # Verify the error is re-raised if not the current exception.1230    try:1231        with app.test_request_context():1232            flask.url_for('spam')1233    except BuildError as err:1234        error = err1235    try:1236        raise RuntimeError('Test case where BuildError is not current.')1237    except RuntimeError:1238        pytest.raises(1239            BuildError, app.handle_url_build_error, error, 'spam', {})12401241    # Test a custom handler.1242    def handler(error, endpoint, values):1243        # Just a test.1244        return '/test_handler/'12451246    app.url_build_error_handlers.append(handler)1247    with app.test_request_context():1248        assert flask.url_for('spam') == '/test_handler/'124912501251def test_build_error_handler_reraise(app):1252    # Test a custom handler which reraises the BuildError1253    def handler_raises_build_error(error, endpoint, values):1254        raise error12551256    app.url_build_error_handlers.append(handler_raises_build_error)12571258    with app.test_request_context():1259        pytest.raises(BuildError, flask.url_for, 'not.existing')126012611262def test_url_for_passes_special_values_to_build_error_handler(app):1263    @app.url_build_error_handlers.append1264    def handler(error, endpoint, values):1265        assert values == {1266            '_external': False,1267            '_anchor': None,1268            '_method': None,1269            '_scheme': None,1270        }1271        return 'handled'12721273    with app.test_request_context():1274        flask.url_for('/')127512761277def test_custom_converters(app, client):1278    from werkzeug.routing import BaseConverter12791280    class ListConverter(BaseConverter):1281        def to_python(self, value):1282            return value.split(',')12831284        def to_url(self, value):1285            base_to_url = super(ListConverter, self).to_url1286            return ','.join(base_to_url(x) for x in value)12871288    app.url_map.converters['list'] = ListConverter12891290    @app.route('/<list:args>')1291    def index(args):1292        return '|'.join(args)12931294    assert client.get('/1,2,3').data == b'1|2|3'129512961297def test_static_files(app, client):1298    rv = client.get('/static/index.html')1299    assert rv.status_code == 2001300    assert rv.data.strip() == b'<h1>Hello World!</h1>'1301    with app.test_request_context():1302        assert flask.url_for('static', filename='index.html') == \1303               '/static/index.html'1304    rv.close()130513061307def test_static_path_deprecated(recwarn):1308    app = flask.Flask(__name__, static_path='/foo')1309    recwarn.pop(DeprecationWarning)13101311    app.testing = True1312    rv = app.test_client().get('/foo/index.html')1313    assert rv.status_code == 2001314    rv.close()13151316    with app.test_request_context():1317        assert flask.url_for('static', filename='index.html') == '/foo/index.html'131813191320def test_static_url_path():1321    app = flask.Flask(__name__, static_url_path='/foo')1322    app.testing = True1323    rv = app.test_client().get('/foo/index.html')1324    assert rv.status_code == 2001325    rv.close()13261327    with app.test_request_context():1328        assert flask.url_for('static', filename='index.html') == '/foo/index.html'132913301331def test_static_route_with_host_matching():1332    app = flask.Flask(__name__, host_matching=True, static_host='example.com')1333    c = app.test_client()1334    rv = c.get('http://example.com/static/index.html')1335    assert rv.status_code == 2001336    rv.close()1337    with app.test_request_context():1338        rv = flask.url_for('static', filename='index.html', _external=True)1339        assert rv == 'http://example.com/static/index.html'1340    # Providing static_host without host_matching=True should error.1341    with pytest.raises(Exception):1342        flask.Flask(__name__, static_host='example.com')1343    # Providing host_matching=True with static_folder but without static_host should error.1344    with pytest.raises(Exception):1345        flask.Flask(__name__, host_matching=True)1346    # Providing host_matching=True without static_host but with static_folder=None should not error.1347    flask.Flask(__name__, host_matching=True, static_folder=None)134813491350def test_request_locals():1351    assert repr(flask.g) == '<LocalProxy unbound>'1352    assert not flask.g135313541355def test_test_app_proper_environ(app, client):1356    app.config.update(1357        SERVER_NAME='localhost.localdomain:5000'1358    )13591360    @app.route('/')1361    def index():1362        return 'Foo'13631364    @app.route('/', subdomain='foo')1365    def subdomain():1366        return 'Foo SubDomain'13671368    rv = client.get('/')1369    assert rv.data == b'Foo'13701371    rv = client.get('/', 'http://localhost.localdomain:5000')1372    assert rv.data == b'Foo'13731374    rv = client.get('/', 'https://localhost.localdomain:5000')1375    assert rv.data == b'Foo'13761377    app.config.update(SERVER_NAME='localhost.localdomain')1378    rv = client.get('/', 'https://localhost.localdomain')1379    assert rv.data == b'Foo'13801381    try:1382        app.config.update(SERVER_NAME='localhost.localdomain:443')1383        rv = client.get('/', 'https://localhost.localdomain')1384        # Werkzeug 0.81385        assert rv.status_code == 4041386    except ValueError as e:1387        # Werkzeug 0.71388        assert str(e) == (1389            "the server name provided "1390            "('localhost.localdomain:443') does not match the "1391            "server name from the WSGI environment ('localhost.localdomain')"1392        )13931394    try:1395        app.config.update(SERVER_NAME='localhost.localdomain')1396        rv = client.get('/', 'http://foo.localhost')1397        # Werkzeug 0.81398        assert rv.status_code == 4041399    except ValueError as e:1400        # Werkzeug 0.71401        assert str(e) == (1402            "the server name provided "1403            "('localhost.localdomain') does not match the "1404            "server name from the WSGI environment ('foo.localhost')"1405        )14061407    rv = client.get('/', 'http://foo.localhost.localdomain')1408    assert rv.data == b'Foo SubDomain'140914101411def test_exception_propagation(app, client):1412    def apprunner(config_key):1413        app.config['LOGGER_HANDLER_POLICY'] = 'never'14141415        @app.route('/')1416        def index():1417            1 // 014181419        if config_key is not None:1420            app.config[config_key] = True1421            with pytest.raises(Exception):1422                client.get('/')1423        else:1424            assert client.get('/').status_code == 50014251426    # we have to run this test in an isolated thread because if the1427    # debug flag is set to true and an exception happens the context is1428    # not torn down.  This causes other tests that run after this fail1429    # when they expect no exception on the stack.1430    for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None:1431        t = Thread(target=apprunner, args=(config_key,))1432        t.start()1433        t.join()143414351436@pytest.mark.parametrize('debug', [True, False])1437@pytest.mark.parametrize('use_debugger', [True, False])1438@pytest.mark.parametrize('use_reloader', [True, False])1439@pytest.mark.parametrize('propagate_exceptions', [None, True, False])1440def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1441                                     use_reloader, propagate_exceptions, app):1442    rv = {}14431444    # Mocks werkzeug.serving.run_simple method1445    def run_simple_mock(*args, **kwargs):1446        rv['passthrough_errors'] = kwargs.get('passthrough_errors')14471448    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1449    app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1450    app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)145114521453def test_max_content_length(app, client):1454    app.config['MAX_CONTENT_LENGTH'] = 6414551456    @app.before_request1457    def always_first():1458        flask.request.form['myfile']1459        assert False14601461    @app.route('/accept', methods=['POST'])1462    def accept_file():1463        flask.request.form['myfile']1464        assert False14651466    @app.errorhandler(413)1467    def catcher(error):1468        return '42'14691470    rv = client.post('/accept', data={'myfile': 'foo' * 100})1471    assert rv.data == b'42'147214731474def test_url_processors(app, client):14751476    @app.url_defaults1477    def add_language_code(endpoint, values):1478        if flask.g.lang_code is not None and \1479                app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1480            values.setdefault('lang_code', flask.g.lang_code)14811482    @app.url_value_preprocessor1483    def pull_lang_code(endpoint, values):1484        flask.g.lang_code = values.pop('lang_code', None)14851486    @app.route('/<lang_code>/')1487    def index():1488        return flask.url_for('about')14891490    @app.route('/<lang_code>/about')1491    def about():1492        return flask.url_for('something_else')14931494    @app.route('/foo')1495    def something_else():1496        return flask.url_for('about', lang_code='en')14971498    assert client.get('/de/').data == b'/de/about'1499    assert client.get('/de/about').data == b'/foo'1500    assert client.get('/foo').data == b'/en/about'150115021503def test_inject_blueprint_url_defaults(app):1504    bp = flask.Blueprint('foo.bar.baz', __name__,1505                         template_folder='template')15061507    @bp.url_defaults1508    def bp_defaults(endpoint, values):1509        values['page'] = 'login'15101511    @bp.route('/<page>')1512    def view(page):1513        pass15141515    app.register_blueprint(bp)15161517    values = dict()1518    app.inject_url_defaults('foo.bar.baz.view', values)1519    expected = dict(page='login')1520    assert values == expected15211522    with app.test_request_context('/somepage'):1523        url = flask.url_for('foo.bar.baz.view')1524    expected = '/login'1525    assert url == expected152615271528def test_nonascii_pathinfo(app, client):1529    @app.route(u'/киртест')1530    def index():1531        return 'Hello World!'15321533    rv = client.get(u'/киртест')1534    assert rv.data == b'Hello World!'153515361537def test_debug_mode_complains_after_first_request(app, client):1538    app.debug = True15391540    @app.route('/')1541    def index():1542        return 'Awesome'15431544    assert not app.got_first_request1545    assert client.get('/').data == b'Awesome'1546    with pytest.raises(AssertionError) as e:1547        @app.route('/foo')1548        def broken():1549            return 'Meh'1550    assert 'A setup function was called' in str(e)15511552    app.debug = False15531554    @app.route('/foo')1555    def working():1556        return 'Meh'15571558    assert client.get('/foo').data == b'Meh'1559    assert app.got_first_request156015611562def test_before_first_request_functions(app, client):1563    got = []15641565    @app.before_first_request1566    def foo():1567        got.append(42)15681569    client.get('/')1570    assert got == [42]1571    client.get('/')1572    assert got == [42]1573    assert app.got_first_request157415751576def test_before_first_request_functions_concurrent(app, client):1577    got = []15781579    @app.before_first_request1580    def foo():1581        time.sleep(0.2)1582        got.append(42)15831584    def get_and_assert():1585        client.get("/")1586        assert got == [42]15871588    t = Thread(target=get_and_assert)1589    t.start()1590    get_and_assert()1591    t.join()1592    assert app.got_first_request159315941595def test_routing_redirect_debugging(app, client):1596    app.debug = True15971598    @app.route('/foo/', methods=['GET', 'POST'])1599    def foo():1600        return 'success'16011602    with client:1603        with pytest.raises(AssertionError) as e:1604            client.post('/foo', data={})1605        assert 'http://localhost/foo/' in str(e)1606        assert ('Make sure to directly send '1607                'your POST-request to this URL') in str(e)16081609        rv = client.get('/foo', data={}, follow_redirects=True)1610        assert rv.data == b'success'16111612    app.debug = False1613    with client:1614        rv = client.post('/foo', data={}, follow_redirects=True)1615        assert rv.data == b'success'161616171618def test_route_decorator_custom_endpoint(app, client):1619    app.debug = True16201621    @app.route('/foo/')1622    def foo():1623        return flask.request.endpoint16241625    @app.route('/bar/', endpoint='bar')1626    def for_bar():1627        return flask.request.endpoint16281629    @app.route('/bar/123', endpoint='123')1630    def for_bar_foo():1631        return flask.request.endpoint16321633    with app.test_request_context():1634        assert flask.url_for('foo') == '/foo/'1635        assert flask.url_for('bar') == '/bar/'1636        assert flask.url_for('123') == '/bar/123'16371638    assert client.get('/foo/').data == b'foo'1639    assert client.get('/bar/').data == b'bar'1640    assert client.get('/bar/123').data == b'123'164116421643def test_preserve_only_once(app, client):1644    app.debug = True16451646    @app.route('/fail')1647    def fail_func():1648        1 // 016491650    for x in range(3):1651        with pytest.raises(ZeroDivisionError):1652            client.get('/fail')16531654    assert flask._request_ctx_stack.top is not None1655    assert flask._app_ctx_stack.top is not None1656    # implicit appctx disappears too1657    flask._request_ctx_stack.top.pop()1658    assert flask._request_ctx_stack.top is None1659    assert flask._app_ctx_stack.top is None166016611662def test_preserve_remembers_exception(app, client):1663    app.debug = True1664    errors = []16651666    @app.route('/fail')1667    def fail_func():1668        1 // 016691670    @app.route('/success')1671    def success_func():1672        return 'Okay'16731674    @app.teardown_request1675    def teardown_handler(exc):1676        errors.append(exc)16771678    # After this failure we did not yet call the teardown handler1679    with pytest.raises(ZeroDivisionError):1680        client.get('/fail')1681    assert errors == []16821683    # But this request triggers it, and it's an error1684    client.get('/success')1685    assert len(errors) == 21686    assert isinstance(errors[0], ZeroDivisionError)16871688    # At this point another request does nothing.1689    client.get('/success')1690    assert len(errors) == 31691    assert errors[1] is None169216931694def test_get_method_on_g(app_ctx):1695    assert flask.g.get('x') is None1696    assert flask.g.get('x', 11) == 111697    flask.g.x = 421698    assert flask.g.get('x') == 421699    assert flask.g.x == 42170017011702def test_g_iteration_protocol(app_ctx):1703    flask.g.foo = 231704    flask.g.bar = 421705    assert 'foo' in flask.g1706    assert 'foos' not in flask.g1707    assert sorted(flask.g) == ['bar', 'foo']170817091710def test_subdomain_basic_support(app, client):1711    app.config['SERVER_NAME'] = 'localhost.localdomain'17121713    @app.route('/')1714    def normal_index():1715        return 'normal index'17161717    @app.route('/', subdomain='test')1718    def test_index():1719        return 'test index'17201721    rv = client.get('/', 'http://localhost.localdomain/')1722    assert rv.data == b'normal index'17231724    rv = client.get('/', 'http://test.localhost.localdomain/')1725    assert rv.data == b'test index'172617271728def test_subdomain_matching(app, client):1729    app.config['SERVER_NAME'] = 'localhost.localdomain'17301731    @app.route('/', subdomain='<user>')1732    def index(user):1733        return 'index for %s' % user17341735    rv = client.get('/', 'http://mitsuhiko.localhost.localdomain/')1736    assert rv.data == b'index for mitsuhiko'173717381739def test_subdomain_matching_with_ports(app, client):1740    app.config['SERVER_NAME'] = 'localhost.localdomain:3000'17411742    @app.route('/', subdomain='<user>')1743    def index(user):1744        return 'index for %s' % user17451746    rv = client.get('/', 'http://mitsuhiko.localhost.localdomain:3000/')1747    assert rv.data == b'index for mitsuhiko'174817491750def test_multi_route_rules(app, client):1751    @app.route('/')1752    @app.route('/<test>/')1753    def index(test='a'):1754        return test17551756    rv = client.open('/')1757    assert rv.data == b'a'1758    rv = client.open('/b/')1759    assert rv.data == b'b'176017611762def test_multi_route_class_views(app, client):1763    class View(object):1764        def __init__(self, app):1765            app.add_url_rule('/', 'index', self.index)1766            app.add_url_rule('/<test>/', 'index', self.index)17671768        def index(self, test='a'):1769            return test17701771    _ = View(app)1772    rv = client.open('/')1773    assert rv.data == b'a'1774    rv = client.open('/b/')1775    assert rv.data == b'b'177617771778def test_run_defaults(monkeypatch, app):1779    rv = {}17801781    # Mocks werkzeug.serving.run_simple method1782    def run_simple_mock(*args, **kwargs):1783        rv['result'] = 'running...'17841785    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1786    app.run()1787    assert rv['result'] == 'running...'178817891790def test_run_server_port(monkeypatch, app):1791    rv = {}17921793    # Mocks werkzeug.serving.run_simple method1794    def run_simple_mock(hostname, port, application, *args, **kwargs):1795        rv['result'] = 'running on %s:%s ...' % (hostname, port)17961797    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1798    hostname, port = 'localhost', 80001799    app.run(hostname, port, debug=True)1800    assert rv['result'] == 'running on %s:%s ...' % (hostname, port)180118021803@pytest.mark.parametrize('host,port,expect_host,expect_port', (1804        (None, None, 'pocoo.org', 8080),1805        ('localhost', None, 'localhost', 8080),1806        (None, 80, 'pocoo.org', 80),1807        ('localhost', 80, 'localhost', 80),1808))1809def test_run_from_config(monkeypatch, host, port, expect_host, expect_port, app):1810    def run_simple_mock(hostname, port, *args, **kwargs):1811        assert hostname == expect_host1812        assert port == expect_port18131814    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1815    app.config['SERVER_NAME'] = 'pocoo.org:8080'1816    app.run(host, port)