Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

1,832 lines · 49.0 KiB · Python

Last changed by

Merge pull request #2352 from davidism/json-object-hookDavid Lordbefore adoption62406e6

History of this file

Take it

1# -*- coding: utf-8 -*-2"""3    tests.basic4    ~~~~~~~~~~~~~~~~~~~~~56    The basic functionality.78    :copyright: (c) 2015 by Armin Ronacher.9    :license: BSD, see LICENSE for more details.10"""1112import pickle13import re14import time15import uuid16from datetime import datetime17from threading import Thread1819import pytest20import werkzeug.serving21from werkzeug.exceptions import BadRequest, Forbidden, NotFound22from werkzeug.http import parse_date23from werkzeug.routing import BuildError2425import flask26from flask._compat import text_type272829def test_options_work(app, client):30    @app.route('/', methods=['GET', 'POST'])31    def index():32        return 'Hello World'3334    rv = client.open('/', method='OPTIONS')35    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']36    assert rv.data == b''373839def test_options_on_multiple_rules(app, client):40    @app.route('/', methods=['GET', 'POST'])41    def index():42        return 'Hello World'4344    @app.route('/', methods=['PUT'])45    def index_put():46        return 'Aha!'4748    rv = client.open('/', method='OPTIONS')49    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']505152def test_provide_automatic_options_attr():53    app = flask.Flask(__name__)5455    def index():56        return 'Hello World!'5758    index.provide_automatic_options = False59    app.route('/')(index)60    rv = app.test_client().open('/', method='OPTIONS')61    assert rv.status_code == 4056263    app = flask.Flask(__name__)6465    def index2():66        return 'Hello World!'6768    index2.provide_automatic_options = True69    app.route('/', methods=['OPTIONS'])(index2)70    rv = app.test_client().open('/', method='OPTIONS')71    assert sorted(rv.allow) == ['OPTIONS']727374def test_provide_automatic_options_kwarg(app, client):75    def index():76        return flask.request.method7778    def more():79        return flask.request.method8081    app.add_url_rule('/', view_func=index, provide_automatic_options=False)82    app.add_url_rule(83        '/more', view_func=more, methods=['GET', 'POST'],84        provide_automatic_options=False85    )86    assert client.get('/').data == b'GET'8788    rv = client.post('/')89    assert rv.status_code == 40590    assert sorted(rv.allow) == ['GET', 'HEAD']9192    # Older versions of Werkzeug.test.Client don't have an options method93    if hasattr(client, 'options'):94        rv = client.options('/')95    else:96        rv = client.open('/', method='OPTIONS')9798    assert rv.status_code == 40599100    rv = client.head('/')101    assert rv.status_code == 200102    assert not rv.data  # head truncates103    assert client.post('/more').data == b'POST'104    assert client.get('/more').data == b'GET'105106    rv = client.delete('/more')107    assert rv.status_code == 405108    assert sorted(rv.allow) == ['GET', 'HEAD', 'POST']109110    if hasattr(client, 'options'):111        rv = client.options('/more')112    else:113        rv = client.open('/more', method='OPTIONS')114115    assert rv.status_code == 405116117118def test_request_dispatching(app, client):119    @app.route('/')120    def index():121        return flask.request.method122123    @app.route('/more', methods=['GET', 'POST'])124    def more():125        return flask.request.method126127    assert client.get('/').data == b'GET'128    rv = client.post('/')129    assert rv.status_code == 405130    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']131    rv = client.head('/')132    assert rv.status_code == 200133    assert not rv.data  # head truncates134    assert client.post('/more').data == b'POST'135    assert client.get('/more').data == b'GET'136    rv = client.delete('/more')137    assert rv.status_code == 405138    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']139140141def test_disallow_string_for_allowed_methods(app):142    with pytest.raises(TypeError):143        @app.route('/', methods='GET POST')144        def index():145            return "Hey"146147148def test_url_mapping(app, client):149    random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"150151    def index():152        return flask.request.method153154    def more():155        return flask.request.method156157    def options():158        return random_uuid4159160    app.add_url_rule('/', 'index', index)161    app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])162163    # Issue 1288: Test that automatic options are not added when non-uppercase 'options' in methods164    app.add_url_rule('/options', 'options', options, methods=['options'])165166    assert client.get('/').data == b'GET'167    rv = client.post('/')168    assert rv.status_code == 405169    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']170    rv = client.head('/')171    assert rv.status_code == 200172    assert not rv.data  # head truncates173    assert client.post('/more').data == b'POST'174    assert client.get('/more').data == b'GET'175    rv = client.delete('/more')176    assert rv.status_code == 405177    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']178    rv = client.open('/options', method='OPTIONS')179    assert rv.status_code == 200180    assert random_uuid4 in rv.data.decode("utf-8")181182183def test_werkzeug_routing(app, client):184    from werkzeug.routing import Submount, Rule185    app.url_map.add(Submount('/foo', [186        Rule('/bar', endpoint='bar'),187        Rule('/', endpoint='index')188    ]))189190    def bar():191        return 'bar'192193    def index():194        return 'index'195196    app.view_functions['bar'] = bar197    app.view_functions['index'] = index198199    assert client.get('/foo/').data == b'index'200    assert client.get('/foo/bar').data == b'bar'201202203def test_endpoint_decorator(app, client):204    from werkzeug.routing import Submount, Rule205    app.url_map.add(Submount('/foo', [206        Rule('/bar', endpoint='bar'),207        Rule('/', endpoint='index')208    ]))209210    @app.endpoint('bar')211    def bar():212        return 'bar'213214    @app.endpoint('index')215    def index():216        return 'index'217218    assert client.get('/foo/').data == b'index'219    assert client.get('/foo/bar').data == b'bar'220221222def test_session(app, client):223    app.secret_key = 'testkey'224225    @app.route('/set', methods=['POST'])226    def set():227        flask.session['value'] = flask.request.form['value']228        return 'value set'229230    @app.route('/get')231    def get():232        return flask.session['value']233234    assert client.post('/set', data={'value': '42'}).data == b'value set'235    assert client.get('/get').data == b'42'236237238def test_session_using_server_name(app, client):239    app.config.update(240        SECRET_KEY='foo',241        SERVER_NAME='example.com'242    )243244    @app.route('/')245    def index():246        flask.session['testing'] = 42247        return 'Hello World'248249    rv = client.get('/', 'http://example.com/')250    assert 'domain=.example.com' in rv.headers['set-cookie'].lower()251    assert 'httponly' in rv.headers['set-cookie'].lower()252253254def test_session_using_server_name_and_port(app, client):255    app.config.update(256        SECRET_KEY='foo',257        SERVER_NAME='example.com:8080'258    )259260    @app.route('/')261    def index():262        flask.session['testing'] = 42263        return 'Hello World'264265    rv = client.get('/', 'http://example.com:8080/')266    assert 'domain=.example.com' in rv.headers['set-cookie'].lower()267    assert 'httponly' in rv.headers['set-cookie'].lower()268269270def test_session_using_server_name_port_and_path(app, client):271    app.config.update(272        SECRET_KEY='foo',273        SERVER_NAME='example.com:8080',274        APPLICATION_ROOT='/foo'275    )276277    @app.route('/')278    def index():279        flask.session['testing'] = 42280        return 'Hello World'281282    rv = client.get('/', 'http://example.com:8080/foo')283    assert 'domain=example.com' in rv.headers['set-cookie'].lower()284    assert 'path=/foo' in rv.headers['set-cookie'].lower()285    assert 'httponly' in rv.headers['set-cookie'].lower()286287288def test_session_using_application_root(app, client):289    class PrefixPathMiddleware(object):290        def __init__(self, app, prefix):291            self.app = app292            self.prefix = prefix293294        def __call__(self, environ, start_response):295            environ['SCRIPT_NAME'] = self.prefix296            return self.app(environ, start_response)297298    app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar')299    app.config.update(300        SECRET_KEY='foo',301        APPLICATION_ROOT='/bar'302    )303304    @app.route('/')305    def index():306        flask.session['testing'] = 42307        return 'Hello World'308309    rv = client.get('/', 'http://example.com:8080/')310    assert 'path=/bar' in rv.headers['set-cookie'].lower()311312313def test_session_using_session_settings(app, client):314    app.config.update(315        SECRET_KEY='foo',316        SERVER_NAME='www.example.com:8080',317        APPLICATION_ROOT='/test',318        SESSION_COOKIE_DOMAIN='.example.com',319        SESSION_COOKIE_HTTPONLY=False,320        SESSION_COOKIE_SECURE=True,321        SESSION_COOKIE_PATH='/'322    )323324    @app.route('/')325    def index():326        flask.session['testing'] = 42327        return 'Hello World'328329    rv = client.get('/', 'http://www.example.com:8080/test/')330    cookie = rv.headers['set-cookie'].lower()331    assert 'domain=.example.com' in cookie332    assert 'path=/' in cookie333    assert 'secure' in cookie334    assert 'httponly' not in cookie335336337def test_session_localhost_warning(recwarn, app, client):338    app.config.update(339        SECRET_KEY='testing',340        SERVER_NAME='localhost:5000',341    )342343    @app.route('/')344    def index():345        flask.session['testing'] = 42346        return 'testing'347348    rv = client.get('/', 'http://localhost:5000/')349    assert 'domain' not in rv.headers['set-cookie'].lower()350    w = recwarn.pop(UserWarning)351    assert '"localhost" is not a valid cookie domain' in str(w.message)352353354def test_session_ip_warning(recwarn, app, client):355    app.config.update(356        SECRET_KEY='testing',357        SERVER_NAME='127.0.0.1:5000',358    )359360    @app.route('/')361    def index():362        flask.session['testing'] = 42363        return 'testing'364365    rv = client.get('/', 'http://127.0.0.1:5000/')366    assert 'domain=127.0.0.1' in rv.headers['set-cookie'].lower()367    w = recwarn.pop(UserWarning)368    assert 'cookie domain is an IP' in str(w.message)369370371def test_missing_session():372    app = flask.Flask(__name__)373374    def expect_exception(f, *args, **kwargs):375        e = pytest.raises(RuntimeError, f, *args, **kwargs)376        assert e.value.args and 'session is unavailable' in e.value.args[0]377378    with app.test_request_context():379        assert flask.session.get('missing_key') is None380        expect_exception(flask.session.__setitem__, 'foo', 42)381        expect_exception(flask.session.pop, 'foo')382383384def test_session_expiration(app, client):385    permanent = True386    app.secret_key = 'testkey'387388    @app.route('/')389    def index():390        flask.session['test'] = 42391        flask.session.permanent = permanent392        return ''393394    @app.route('/test')395    def test():396        return text_type(flask.session.permanent)397398    rv = client.get('/')399    assert 'set-cookie' in rv.headers400    match = re.search(r'(?i)\bexpires=([^;]+)', rv.headers['set-cookie'])401    expires = parse_date(match.group())402    expected = datetime.utcnow() + app.permanent_session_lifetime403    assert expires.year == expected.year404    assert expires.month == expected.month405    assert expires.day == expected.day406407    rv = client.get('/test')408    assert rv.data == b'True'409410    permanent = False411    rv = client.get('/')412    assert 'set-cookie' in rv.headers413    match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])414    assert match is None415416417def test_session_stored_last(app, client):418    app.secret_key = 'development-key'419420    @app.after_request421    def modify_session(response):422        flask.session['foo'] = 42423        return response424425    @app.route('/')426    def dump_session_contents():427        return repr(flask.session.get('foo'))428429    assert client.get('/').data == b'None'430    assert client.get('/').data == b'42'431432433def test_session_special_types(app, client):434    app.secret_key = 'development-key'435    now = datetime.utcnow().replace(microsecond=0)436    the_uuid = uuid.uuid4()437438    @app.route('/')439    def dump_session_contents():440        flask.session['t'] = (1, 2, 3)441        flask.session['b'] = b'\xff'442        flask.session['m'] = flask.Markup('<html>')443        flask.session['u'] = the_uuid444        flask.session['d'] = now445        flask.session['t_tag'] = {' t': 'not-a-tuple'}446        flask.session['di_t_tag'] = {' t__': 'not-a-tuple'}447        flask.session['di_tag'] = {' di': 'not-a-dict'}448        return '', 204449450    with client:451        client.get('/')452        s = flask.session453        assert s['t'] == (1, 2, 3)454        assert type(s['b']) == bytes455        assert s['b'] == b'\xff'456        assert type(s['m']) == flask.Markup457        assert s['m'] == flask.Markup('<html>')458        assert s['u'] == the_uuid459        assert s['d'] == now460        assert s['t_tag'] == {' t': 'not-a-tuple'}461        assert s['di_t_tag'] == {' t__': 'not-a-tuple'}462        assert s['di_tag'] == {' di': 'not-a-dict'}463464465def test_session_cookie_setting(app):466    app.secret_key = 'dev key'467    is_permanent = True468469    @app.route('/bump')470    def bump():471        rv = flask.session['foo'] = flask.session.get('foo', 0) + 1472        flask.session.permanent = is_permanent473        return str(rv)474475    @app.route('/read')476    def read():477        return str(flask.session.get('foo', 0))478479    def run_test(expect_header):480        with app.test_client() as c:481            assert c.get('/bump').data == b'1'482            assert c.get('/bump').data == b'2'483            assert c.get('/bump').data == b'3'484485            rv = c.get('/read')486            set_cookie = rv.headers.get('set-cookie')487            assert (set_cookie is not None) == expect_header488            assert rv.data == b'3'489490    is_permanent = True491    app.config['SESSION_REFRESH_EACH_REQUEST'] = True492    run_test(expect_header=True)493494    is_permanent = True495    app.config['SESSION_REFRESH_EACH_REQUEST'] = False496    run_test(expect_header=False)497498    is_permanent = False499    app.config['SESSION_REFRESH_EACH_REQUEST'] = True500    run_test(expect_header=False)501502    is_permanent = False503    app.config['SESSION_REFRESH_EACH_REQUEST'] = False504    run_test(expect_header=False)505506507def test_session_vary_cookie(app, client):508    app.secret_key = 'testkey'509510    @app.route('/set')511    def set_session():512        flask.session['test'] = 'test'513        return ''514515    @app.route('/get')516    def get():517        return flask.session.get('test')518519    @app.route('/getitem')520    def getitem():521        return flask.session['test']522523    @app.route('/setdefault')524    def setdefault():525        return flask.session.setdefault('test', 'default')526527    @app.route('/vary-cookie-header-set')528    def vary_cookie_header_set():529        response = flask.Response()530        response.vary.add('Cookie')531        flask.session['test'] = 'test'532        return response533534    @app.route('/vary-header-set')535    def vary_header_set():536        response = flask.Response()537        response.vary.update(('Accept-Encoding', 'Accept-Language'))538        flask.session['test'] = 'test'539        return response540541    @app.route('/no-vary-header')542    def no_vary_header():543        return ''544545    def expect(path, header_value='Cookie'):546        rv = client.get(path)547548        if header_value:549            # The 'Vary' key should exist in the headers only once.550            assert len(rv.headers.get_all('Vary')) == 1551            assert rv.headers['Vary'] == header_value552        else:553            assert 'Vary' not in rv.headers554555    expect('/set')556    expect('/get')557    expect('/getitem')558    expect('/setdefault')559    expect('/vary-cookie-header-set')560    expect('/vary-header-set', 'Accept-Encoding, Accept-Language, Cookie')561    expect('/no-vary-header', None)562563564def test_flashes(app, req_ctx):565    app.secret_key = 'testkey'566567    assert not flask.session.modified568    flask.flash('Zap')569    flask.session.modified = False570    flask.flash('Zip')571    assert flask.session.modified572    assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']573574575def test_extended_flashing(app):576    # Be sure app.testing=True below, else tests can fail silently.577    #578    # Specifically, if app.testing is not set to True, the AssertionErrors579    # in the view functions will cause a 500 response to the test client580    # instead of propagating exceptions.581582    app.secret_key = 'testkey'583584    @app.route('/')585    def index():586        flask.flash(u'Hello World')587        flask.flash(u'Hello World', 'error')588        flask.flash(flask.Markup(u'<em>Testing</em>'), 'warning')589        return ''590591    @app.route('/test/')592    def test():593        messages = flask.get_flashed_messages()594        assert list(messages) == [595            u'Hello World',596            u'Hello World',597            flask.Markup(u'<em>Testing</em>')598        ]599        return ''600601    @app.route('/test_with_categories/')602    def test_with_categories():603        messages = flask.get_flashed_messages(with_categories=True)604        assert len(messages) == 3605        assert list(messages) == [606            ('message', u'Hello World'),607            ('error', u'Hello World'),608            ('warning', flask.Markup(u'<em>Testing</em>'))609        ]610        return ''611612    @app.route('/test_filter/')613    def test_filter():614        messages = flask.get_flashed_messages(615            category_filter=['message'], with_categories=True)616        assert list(messages) == [('message', u'Hello World')]617        return ''618619    @app.route('/test_filters/')620    def test_filters():621        messages = flask.get_flashed_messages(622            category_filter=['message', 'warning'], with_categories=True)623        assert list(messages) == [624            ('message', u'Hello World'),625            ('warning', flask.Markup(u'<em>Testing</em>'))626        ]627        return ''628629    @app.route('/test_filters_without_returning_categories/')630    def test_filters2():631        messages = flask.get_flashed_messages(632            category_filter=['message', 'warning'])633        assert len(messages) == 2634        assert messages[0] == u'Hello World'635        assert messages[1] == flask.Markup(u'<em>Testing</em>')636        return ''637638    # Create new test client on each test to clean flashed messages.639640    client = app.test_client()641    client.get('/')642    client.get('/test_with_categories/')643644    client = app.test_client()645    client.get('/')646    client.get('/test_filter/')647648    client = app.test_client()649    client.get('/')650    client.get('/test_filters/')651652    client = app.test_client()653    client.get('/')654    client.get('/test_filters_without_returning_categories/')655656657def test_request_processing(app, client):658    evts = []659660    @app.before_request661    def before_request():662        evts.append('before')663664    @app.after_request665    def after_request(response):666        response.data += b'|after'667        evts.append('after')668        return response669670    @app.route('/')671    def index():672        assert 'before' in evts673        assert 'after' not in evts674        return 'request'675676    assert 'after' not in evts677    rv = client.get('/').data678    assert 'after' in evts679    assert rv == b'request|after'680681682def test_request_preprocessing_early_return(app, client):683    evts = []684685    @app.before_request686    def before_request1():687        evts.append(1)688689    @app.before_request690    def before_request2():691        evts.append(2)692        return "hello"693694    @app.before_request695    def before_request3():696        evts.append(3)697        return "bye"698699    @app.route('/')700    def index():701        evts.append('index')702        return "damnit"703704    rv = client.get('/').data.strip()705    assert rv == b'hello'706    assert evts == [1, 2]707708709def test_after_request_processing(app, client):710    @app.route('/')711    def index():712        @flask.after_this_request713        def foo(response):714            response.headers['X-Foo'] = 'a header'715            return response716717        return 'Test'718719    resp = client.get('/')720    assert resp.status_code == 200721    assert resp.headers['X-Foo'] == 'a header'722723724def test_teardown_request_handler(app, client):725    called = []726727    @app.teardown_request728    def teardown_request(exc):729        called.append(True)730        return "Ignored"731732    @app.route('/')733    def root():734        return "Response"735736    rv = client.get('/')737    assert rv.status_code == 200738    assert b'Response' in rv.data739    assert len(called) == 1740741742def test_teardown_request_handler_debug_mode(app, client):743    called = []744745    @app.teardown_request746    def teardown_request(exc):747        called.append(True)748        return "Ignored"749750    @app.route('/')751    def root():752        return "Response"753754    rv = client.get('/')755    assert rv.status_code == 200756    assert b'Response' in rv.data757    assert len(called) == 1758759760def test_teardown_request_handler_error(app, client):761    called = []762    app.config['LOGGER_HANDLER_POLICY'] = 'never'763    app.testing = False764765    @app.teardown_request766    def teardown_request1(exc):767        assert type(exc) == ZeroDivisionError768        called.append(True)769        # This raises a new error and blows away sys.exc_info(), so we can770        # test that all teardown_requests get passed the same original771        # exception.772        try:773            raise TypeError()774        except:775            pass776777    @app.teardown_request778    def teardown_request2(exc):779        assert type(exc) == ZeroDivisionError780        called.append(True)781        # This raises a new error and blows away sys.exc_info(), so we can782        # test that all teardown_requests get passed the same original783        # exception.784        try:785            raise TypeError()786        except:787            pass788789    @app.route('/')790    def fails():791        1 // 0792793    rv = client.get('/')794    assert rv.status_code == 500795    assert b'Internal Server Error' in rv.data796    assert len(called) == 2797798799def test_before_after_request_order(app, client):800    called = []801802    @app.before_request803    def before1():804        called.append(1)805806    @app.before_request807    def before2():808        called.append(2)809810    @app.after_request811    def after1(response):812        called.append(4)813        return response814815    @app.after_request816    def after2(response):817        called.append(3)818        return response819820    @app.teardown_request821    def finish1(exc):822        called.append(6)823824    @app.teardown_request825    def finish2(exc):826        called.append(5)827828    @app.route('/')829    def index():830        return '42'831832    rv = client.get('/')833    assert rv.data == b'42'834    assert called == [1, 2, 3, 4, 5, 6]835836837def test_error_handling(app, client):838    app.config['LOGGER_HANDLER_POLICY'] = 'never'839    app.testing = False840841    @app.errorhandler(404)842    def not_found(e):843        return 'not found', 404844845    @app.errorhandler(500)846    def internal_server_error(e):847        return 'internal server error', 500848849    @app.errorhandler(Forbidden)850    def forbidden(e):851        return 'forbidden', 403852853    @app.route('/')854    def index():855        flask.abort(404)856857    @app.route('/error')858    def error():859        1 // 0860861    @app.route('/forbidden')862    def error2():863        flask.abort(403)864865    rv = client.get('/')866    assert rv.status_code == 404867    assert rv.data == b'not found'868    rv = client.get('/error')869    assert rv.status_code == 500870    assert b'internal server error' == rv.data871    rv = client.get('/forbidden')872    assert rv.status_code == 403873    assert b'forbidden' == rv.data874875876def test_error_handler_unknown_code(app):877    with pytest.raises(KeyError) as exc_info:878        app.register_error_handler(999, lambda e: ('999', 999))879880    assert 'Use a subclass' in exc_info.value.args[0]881882883def test_error_handling_processing(app, client):884    app.config['LOGGER_HANDLER_POLICY'] = 'never'885    app.testing = False886887    @app.errorhandler(500)888    def internal_server_error(e):889        return 'internal server error', 500890891    @app.route('/')892    def broken_func():893        1 // 0894895    @app.after_request896    def after_request(resp):897        resp.mimetype = 'text/x-special'898        return resp899900    resp = client.get('/')901    assert resp.mimetype == 'text/x-special'902    assert resp.data == b'internal server error'903904905def test_baseexception_error_handling(app, client):906    app.config['LOGGER_HANDLER_POLICY'] = 'never'907    app.testing = False908909    @app.route('/')910    def broken_func():911        raise KeyboardInterrupt()912913    with pytest.raises(KeyboardInterrupt):914        client.get('/')915916        ctx = flask._request_ctx_stack.top917        assert ctx.preserved918        assert type(ctx._preserved_exc) is KeyboardInterrupt919920921def test_before_request_and_routing_errors(app, client):922    @app.before_request923    def attach_something():924        flask.g.something = 'value'925926    @app.errorhandler(404)927    def return_something(error):928        return flask.g.something, 404929930    rv = client.get('/')931    assert rv.status_code == 404932    assert rv.data == b'value'933934935def test_user_error_handling(app, client):936    class MyException(Exception):937        pass938939    @app.errorhandler(MyException)940    def handle_my_exception(e):941        assert isinstance(e, MyException)942        return '42'943944    @app.route('/')945    def index():946        raise MyException()947948    assert client.get('/').data == b'42'949950951def test_http_error_subclass_handling(app, client):952    class ForbiddenSubclass(Forbidden):953        pass954955    @app.errorhandler(ForbiddenSubclass)956    def handle_forbidden_subclass(e):957        assert isinstance(e, ForbiddenSubclass)958        return 'banana'959960    @app.errorhandler(403)961    def handle_forbidden_subclass(e):962        assert not isinstance(e, ForbiddenSubclass)963        assert isinstance(e, Forbidden)964        return 'apple'965966    @app.route('/1')967    def index1():968        raise ForbiddenSubclass()969970    @app.route('/2')971    def index2():972        flask.abort(403)973974    @app.route('/3')975    def index3():976        raise Forbidden()977978    assert client.get('/1').data == b'banana'979    assert client.get('/2').data == b'apple'980    assert client.get('/3').data == b'apple'981982983def test_trapping_of_bad_request_key_errors(app, client):984    @app.route('/fail')985    def fail():986        flask.request.form['missing_key']987988    rv = client.get('/fail')989    assert rv.status_code == 400990    assert b'missing_key' not in rv.data991992    app.config['TRAP_BAD_REQUEST_ERRORS'] = True993994    with pytest.raises(KeyError) as e:995        client.get("/fail")996997    assert e.errisinstance(BadRequest)998    assert 'missing_key' in e.value.description99910001001def test_trapping_of_all_http_exceptions(app, client):1002    app.config['TRAP_HTTP_EXCEPTIONS'] = True10031004    @app.route('/fail')1005    def fail():1006        flask.abort(404)10071008    with pytest.raises(NotFound):1009        client.get('/fail')101010111012def test_enctype_debug_helper(app, client):1013    from flask.debughelpers import DebugFilesKeyError1014    app.debug = True10151016    @app.route('/fail', methods=['POST'])1017    def index():1018        return flask.request.files['foo'].filename10191020    # with statement is important because we leave an exception on the1021    # stack otherwise and we want to ensure that this is not the case1022    # to not negatively affect other tests.1023    with client:1024        with pytest.raises(DebugFilesKeyError) as e:1025            client.post('/fail', data={'foo': 'index.txt'})1026        assert 'no file contents were transmitted' in str(e.value)1027        assert 'This was submitted: "index.txt"' in str(e.value)102810291030def test_response_types(app, client):1031    @app.route('/text')1032    def from_text():1033        return u'Hällo Wörld'10341035    @app.route('/bytes')1036    def from_bytes():1037        return u'Hällo Wörld'.encode('utf-8')10381039    @app.route('/full_tuple')1040    def from_full_tuple():1041        return 'Meh', 400, {1042            'X-Foo': 'Testing',1043            'Content-Type': 'text/plain; charset=utf-8'1044        }10451046    @app.route('/text_headers')1047    def from_text_headers():1048        return 'Hello', {1049            'X-Foo': 'Test',1050            'Content-Type': 'text/plain; charset=utf-8'1051        }10521053    @app.route('/text_status')1054    def from_text_status():1055        return 'Hi, status!', 40010561057    @app.route('/response_headers')1058    def from_response_headers():1059        return flask.Response('Hello world', 404, {'X-Foo': 'Baz'}), {1060            "X-Foo": "Bar",1061            "X-Bar": "Foo"1062        }10631064    @app.route('/response_status')1065    def from_response_status():1066        return app.response_class('Hello world', 400), 50010671068    @app.route('/wsgi')1069    def from_wsgi():1070        return NotFound()10711072    assert client.get('/text').data == u'Hällo Wörld'.encode('utf-8')1073    assert client.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')10741075    rv = client.get('/full_tuple')1076    assert rv.data == b'Meh'1077    assert rv.headers['X-Foo'] == 'Testing'1078    assert rv.status_code == 4001079    assert rv.mimetype == 'text/plain'10801081    rv = client.get('/text_headers')1082    assert rv.data == b'Hello'1083    assert rv.headers['X-Foo'] == 'Test'1084    assert rv.status_code == 2001085    assert rv.mimetype == 'text/plain'10861087    rv = client.get('/text_status')1088    assert rv.data == b'Hi, status!'1089    assert rv.status_code == 4001090    assert rv.mimetype == 'text/html'10911092    rv = client.get('/response_headers')1093    assert rv.data == b'Hello world'1094    assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar']1095    assert rv.headers['X-Bar'] == 'Foo'1096    assert rv.status_code == 40410971098    rv = client.get('/response_status')1099    assert rv.data == b'Hello world'1100    assert rv.status_code == 50011011102    rv = client.get('/wsgi')1103    assert b'Not Found' in rv.data1104    assert rv.status_code == 404110511061107def test_response_type_errors():1108    app = flask.Flask(__name__)1109    app.testing = True11101111    @app.route('/none')1112    def from_none():1113        pass11141115    @app.route('/small_tuple')1116    def from_small_tuple():1117        return 'Hello',11181119    @app.route('/large_tuple')1120    def from_large_tuple():1121        return 'Hello', 234, {'X-Foo': 'Bar'}, '???'11221123    @app.route('/bad_type')1124    def from_bad_type():1125        return True11261127    @app.route('/bad_wsgi')1128    def from_bad_wsgi():1129        return lambda: None11301131    c = app.test_client()11321133    with pytest.raises(TypeError) as e:1134        c.get('/none')1135        assert 'returned None' in str(e)11361137    with pytest.raises(TypeError) as e:1138        c.get('/small_tuple')1139        assert 'tuple must have the form' in str(e)11401141    pytest.raises(TypeError, c.get, '/large_tuple')11421143    with pytest.raises(TypeError) as e:1144        c.get('/bad_type')1145        assert 'it was a bool' in str(e)11461147    pytest.raises(TypeError, c.get, '/bad_wsgi')114811491150def test_make_response(app, req_ctx):1151    rv = flask.make_response()1152    assert rv.status_code == 2001153    assert rv.data == b''1154    assert rv.mimetype == 'text/html'11551156    rv = flask.make_response('Awesome')1157    assert rv.status_code == 2001158    assert rv.data == b'Awesome'1159    assert rv.mimetype == 'text/html'11601161    rv = flask.make_response('W00t', 404)1162    assert rv.status_code == 4041163    assert rv.data == b'W00t'1164    assert rv.mimetype == 'text/html'116511661167def test_make_response_with_response_instance(app, req_ctx):1168    rv = flask.make_response(1169        flask.jsonify({'msg': 'W00t'}), 400)1170    assert rv.status_code == 4001171    assert rv.data == b'{"msg":"W00t"}\n'1172    assert rv.mimetype == 'application/json'11731174    rv = flask.make_response(1175        flask.Response(''), 400)1176    assert rv.status_code == 4001177    assert rv.data == b''1178    assert rv.mimetype == 'text/html'11791180    rv = flask.make_response(1181        flask.Response('', headers={'Content-Type': 'text/html'}),1182        400, [('X-Foo', 'bar')])1183    assert rv.status_code == 4001184    assert rv.headers['Content-Type'] == 'text/html'1185    assert rv.headers['X-Foo'] == 'bar'118611871188def test_jsonify_no_prettyprint(app, req_ctx):1189    app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1190    compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1191    uncompressed_msg = {1192        "msg": {1193            "submsg": "W00t"1194        },1195        "msg2": "foobar"1196    }11971198    rv = flask.make_response(1199        flask.jsonify(uncompressed_msg), 200)1200    assert rv.data == compressed_msg120112021203def test_jsonify_prettyprint(app, req_ctx):1204    app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1205    compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1206    pretty_response = \1207        b'{\n  "msg": {\n    "submsg": "W00t"\n  }, \n  "msg2": "foobar"\n}\n'12081209    rv = flask.make_response(1210        flask.jsonify(compressed_msg), 200)1211    assert rv.data == pretty_response121212131214def test_jsonify_mimetype(app, req_ctx):1215    app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'})1216    msg = {1217        "msg": {"submsg": "W00t"},1218    }1219    rv = flask.make_response(1220        flask.jsonify(msg), 200)1221    assert rv.mimetype == 'application/vnd.api+json'122212231224def test_jsonify_args_and_kwargs_check(app, req_ctx):1225    with pytest.raises(TypeError) as e:1226        flask.jsonify('fake args', kwargs='fake')1227    assert 'behavior undefined' in str(e.value)122812291230def test_url_generation(app, req_ctx):1231    @app.route('/hello/<name>', methods=['POST'])1232    def hello():1233        pass12341235    assert flask.url_for('hello', name='test x') == '/hello/test%20x'1236    assert flask.url_for('hello', name='test x', _external=True) == \1237           'http://localhost/hello/test%20x'123812391240def test_build_error_handler(app):1241    # Test base case, a URL which results in a BuildError.1242    with app.test_request_context():1243        pytest.raises(BuildError, flask.url_for, 'spam')12441245    # Verify the error is re-raised if not the current exception.1246    try:1247        with app.test_request_context():1248            flask.url_for('spam')1249    except BuildError as err:1250        error = err1251    try:1252        raise RuntimeError('Test case where BuildError is not current.')1253    except RuntimeError:1254        pytest.raises(1255            BuildError, app.handle_url_build_error, error, 'spam', {})12561257    # Test a custom handler.1258    def handler(error, endpoint, values):1259        # Just a test.1260        return '/test_handler/'12611262    app.url_build_error_handlers.append(handler)1263    with app.test_request_context():1264        assert flask.url_for('spam') == '/test_handler/'126512661267def test_build_error_handler_reraise(app):1268    # Test a custom handler which reraises the BuildError1269    def handler_raises_build_error(error, endpoint, values):1270        raise error12711272    app.url_build_error_handlers.append(handler_raises_build_error)12731274    with app.test_request_context():1275        pytest.raises(BuildError, flask.url_for, 'not.existing')127612771278def test_url_for_passes_special_values_to_build_error_handler(app):1279    @app.url_build_error_handlers.append1280    def handler(error, endpoint, values):1281        assert values == {1282            '_external': False,1283            '_anchor': None,1284            '_method': None,1285            '_scheme': None,1286        }1287        return 'handled'12881289    with app.test_request_context():1290        flask.url_for('/')129112921293def test_custom_converters(app, client):1294    from werkzeug.routing import BaseConverter12951296    class ListConverter(BaseConverter):1297        def to_python(self, value):1298            return value.split(',')12991300        def to_url(self, value):1301            base_to_url = super(ListConverter, self).to_url1302            return ','.join(base_to_url(x) for x in value)13031304    app.url_map.converters['list'] = ListConverter13051306    @app.route('/<list:args>')1307    def index(args):1308        return '|'.join(args)13091310    assert client.get('/1,2,3').data == b'1|2|3'131113121313def test_static_files(app, client):1314    rv = client.get('/static/index.html')1315    assert rv.status_code == 2001316    assert rv.data.strip() == b'<h1>Hello World!</h1>'1317    with app.test_request_context():1318        assert flask.url_for('static', filename='index.html') == \1319               '/static/index.html'1320    rv.close()132113221323def test_static_path_deprecated(recwarn):1324    app = flask.Flask(__name__, static_path='/foo')1325    recwarn.pop(DeprecationWarning)13261327    app.testing = True1328    rv = app.test_client().get('/foo/index.html')1329    assert rv.status_code == 2001330    rv.close()13311332    with app.test_request_context():1333        assert flask.url_for('static', filename='index.html') == '/foo/index.html'133413351336def test_static_url_path():1337    app = flask.Flask(__name__, static_url_path='/foo')1338    app.testing = True1339    rv = app.test_client().get('/foo/index.html')1340    assert rv.status_code == 2001341    rv.close()13421343    with app.test_request_context():1344        assert flask.url_for('static', filename='index.html') == '/foo/index.html'134513461347def test_static_route_with_host_matching():1348    app = flask.Flask(__name__, host_matching=True, static_host='example.com')1349    c = app.test_client()1350    rv = c.get('http://example.com/static/index.html')1351    assert rv.status_code == 2001352    rv.close()1353    with app.test_request_context():1354        rv = flask.url_for('static', filename='index.html', _external=True)1355        assert rv == 'http://example.com/static/index.html'1356    # Providing static_host without host_matching=True should error.1357    with pytest.raises(Exception):1358        flask.Flask(__name__, static_host='example.com')1359    # Providing host_matching=True with static_folder but without static_host should error.1360    with pytest.raises(Exception):1361        flask.Flask(__name__, host_matching=True)1362    # Providing host_matching=True without static_host but with static_folder=None should not error.1363    flask.Flask(__name__, host_matching=True, static_folder=None)136413651366def test_request_locals():1367    assert repr(flask.g) == '<LocalProxy unbound>'1368    assert not flask.g136913701371def test_test_app_proper_environ(app, client):1372    app.config.update(1373        SERVER_NAME='localhost.localdomain:5000'1374    )13751376    @app.route('/')1377    def index():1378        return 'Foo'13791380    @app.route('/', subdomain='foo')1381    def subdomain():1382        return 'Foo SubDomain'13831384    rv = client.get('/')1385    assert rv.data == b'Foo'13861387    rv = client.get('/', 'http://localhost.localdomain:5000')1388    assert rv.data == b'Foo'13891390    rv = client.get('/', 'https://localhost.localdomain:5000')1391    assert rv.data == b'Foo'13921393    app.config.update(SERVER_NAME='localhost.localdomain')1394    rv = client.get('/', 'https://localhost.localdomain')1395    assert rv.data == b'Foo'13961397    try:1398        app.config.update(SERVER_NAME='localhost.localdomain:443')1399        rv = client.get('/', 'https://localhost.localdomain')1400        # Werkzeug 0.81401        assert rv.status_code == 4041402    except ValueError as e:1403        # Werkzeug 0.71404        assert str(e) == (1405            "the server name provided "1406            "('localhost.localdomain:443') does not match the "1407            "server name from the WSGI environment ('localhost.localdomain')"1408        )14091410    try:1411        app.config.update(SERVER_NAME='localhost.localdomain')1412        rv = client.get('/', 'http://foo.localhost')1413        # Werkzeug 0.81414        assert rv.status_code == 4041415    except ValueError as e:1416        # Werkzeug 0.71417        assert str(e) == (1418            "the server name provided "1419            "('localhost.localdomain') does not match the "1420            "server name from the WSGI environment ('foo.localhost')"1421        )14221423    rv = client.get('/', 'http://foo.localhost.localdomain')1424    assert rv.data == b'Foo SubDomain'142514261427def test_exception_propagation(app, client):1428    def apprunner(config_key):1429        app.config['LOGGER_HANDLER_POLICY'] = 'never'14301431        @app.route('/')1432        def index():1433            1 // 014341435        if config_key is not None:1436            app.config[config_key] = True1437            with pytest.raises(Exception):1438                client.get('/')1439        else:1440            assert client.get('/').status_code == 50014411442    # we have to run this test in an isolated thread because if the1443    # debug flag is set to true and an exception happens the context is1444    # not torn down.  This causes other tests that run after this fail1445    # when they expect no exception on the stack.1446    for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None:1447        t = Thread(target=apprunner, args=(config_key,))1448        t.start()1449        t.join()145014511452@pytest.mark.parametrize('debug', [True, False])1453@pytest.mark.parametrize('use_debugger', [True, False])1454@pytest.mark.parametrize('use_reloader', [True, False])1455@pytest.mark.parametrize('propagate_exceptions', [None, True, False])1456def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1457                                     use_reloader, propagate_exceptions, app):1458    rv = {}14591460    # Mocks werkzeug.serving.run_simple method1461    def run_simple_mock(*args, **kwargs):1462        rv['passthrough_errors'] = kwargs.get('passthrough_errors')14631464    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1465    app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1466    app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)146714681469def test_max_content_length(app, client):1470    app.config['MAX_CONTENT_LENGTH'] = 6414711472    @app.before_request1473    def always_first():1474        flask.request.form['myfile']1475        assert False14761477    @app.route('/accept', methods=['POST'])1478    def accept_file():1479        flask.request.form['myfile']1480        assert False14811482    @app.errorhandler(413)1483    def catcher(error):1484        return '42'14851486    rv = client.post('/accept', data={'myfile': 'foo' * 100})1487    assert rv.data == b'42'148814891490def test_url_processors(app, client):14911492    @app.url_defaults1493    def add_language_code(endpoint, values):1494        if flask.g.lang_code is not None and \1495                app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1496            values.setdefault('lang_code', flask.g.lang_code)14971498    @app.url_value_preprocessor1499    def pull_lang_code(endpoint, values):1500        flask.g.lang_code = values.pop('lang_code', None)15011502    @app.route('/<lang_code>/')1503    def index():1504        return flask.url_for('about')15051506    @app.route('/<lang_code>/about')1507    def about():1508        return flask.url_for('something_else')15091510    @app.route('/foo')1511    def something_else():1512        return flask.url_for('about', lang_code='en')15131514    assert client.get('/de/').data == b'/de/about'1515    assert client.get('/de/about').data == b'/foo'1516    assert client.get('/foo').data == b'/en/about'151715181519def test_inject_blueprint_url_defaults(app):1520    bp = flask.Blueprint('foo.bar.baz', __name__,1521                         template_folder='template')15221523    @bp.url_defaults1524    def bp_defaults(endpoint, values):1525        values['page'] = 'login'15261527    @bp.route('/<page>')1528    def view(page):1529        pass15301531    app.register_blueprint(bp)15321533    values = dict()1534    app.inject_url_defaults('foo.bar.baz.view', values)1535    expected = dict(page='login')1536    assert values == expected15371538    with app.test_request_context('/somepage'):1539        url = flask.url_for('foo.bar.baz.view')1540    expected = '/login'1541    assert url == expected154215431544def test_nonascii_pathinfo(app, client):1545    @app.route(u'/киртест')1546    def index():1547        return 'Hello World!'15481549    rv = client.get(u'/киртест')1550    assert rv.data == b'Hello World!'155115521553def test_debug_mode_complains_after_first_request(app, client):1554    app.debug = True15551556    @app.route('/')1557    def index():1558        return 'Awesome'15591560    assert not app.got_first_request1561    assert client.get('/').data == b'Awesome'1562    with pytest.raises(AssertionError) as e:1563        @app.route('/foo')1564        def broken():1565            return 'Meh'1566    assert 'A setup function was called' in str(e)15671568    app.debug = False15691570    @app.route('/foo')1571    def working():1572        return 'Meh'15731574    assert client.get('/foo').data == b'Meh'1575    assert app.got_first_request157615771578def test_before_first_request_functions(app, client):1579    got = []15801581    @app.before_first_request1582    def foo():1583        got.append(42)15841585    client.get('/')1586    assert got == [42]1587    client.get('/')1588    assert got == [42]1589    assert app.got_first_request159015911592def test_before_first_request_functions_concurrent(app, client):1593    got = []15941595    @app.before_first_request1596    def foo():1597        time.sleep(0.2)1598        got.append(42)15991600    def get_and_assert():1601        client.get("/")1602        assert got == [42]16031604    t = Thread(target=get_and_assert)1605    t.start()1606    get_and_assert()1607    t.join()1608    assert app.got_first_request160916101611def test_routing_redirect_debugging(app, client):1612    app.debug = True16131614    @app.route('/foo/', methods=['GET', 'POST'])1615    def foo():1616        return 'success'16171618    with client:1619        with pytest.raises(AssertionError) as e:1620            client.post('/foo', data={})1621        assert 'http://localhost/foo/' in str(e)1622        assert ('Make sure to directly send '1623                'your POST-request to this URL') in str(e)16241625        rv = client.get('/foo', data={}, follow_redirects=True)1626        assert rv.data == b'success'16271628    app.debug = False1629    with client:1630        rv = client.post('/foo', data={}, follow_redirects=True)1631        assert rv.data == b'success'163216331634def test_route_decorator_custom_endpoint(app, client):1635    app.debug = True16361637    @app.route('/foo/')1638    def foo():1639        return flask.request.endpoint16401641    @app.route('/bar/', endpoint='bar')1642    def for_bar():1643        return flask.request.endpoint16441645    @app.route('/bar/123', endpoint='123')1646    def for_bar_foo():1647        return flask.request.endpoint16481649    with app.test_request_context():1650        assert flask.url_for('foo') == '/foo/'1651        assert flask.url_for('bar') == '/bar/'1652        assert flask.url_for('123') == '/bar/123'16531654    assert client.get('/foo/').data == b'foo'1655    assert client.get('/bar/').data == b'bar'1656    assert client.get('/bar/123').data == b'123'165716581659def test_preserve_only_once(app, client):1660    app.debug = True16611662    @app.route('/fail')1663    def fail_func():1664        1 // 016651666    for x in range(3):1667        with pytest.raises(ZeroDivisionError):1668            client.get('/fail')16691670    assert flask._request_ctx_stack.top is not None1671    assert flask._app_ctx_stack.top is not None1672    # implicit appctx disappears too1673    flask._request_ctx_stack.top.pop()1674    assert flask._request_ctx_stack.top is None1675    assert flask._app_ctx_stack.top is None167616771678def test_preserve_remembers_exception(app, client):1679    app.debug = True1680    errors = []16811682    @app.route('/fail')1683    def fail_func():1684        1 // 016851686    @app.route('/success')1687    def success_func():1688        return 'Okay'16891690    @app.teardown_request1691    def teardown_handler(exc):1692        errors.append(exc)16931694    # After this failure we did not yet call the teardown handler1695    with pytest.raises(ZeroDivisionError):1696        client.get('/fail')1697    assert errors == []16981699    # But this request triggers it, and it's an error1700    client.get('/success')1701    assert len(errors) == 21702    assert isinstance(errors[0], ZeroDivisionError)17031704    # At this point another request does nothing.1705    client.get('/success')1706    assert len(errors) == 31707    assert errors[1] is None170817091710def test_get_method_on_g(app_ctx):1711    assert flask.g.get('x') is None1712    assert flask.g.get('x', 11) == 111713    flask.g.x = 421714    assert flask.g.get('x') == 421715    assert flask.g.x == 42171617171718def test_g_iteration_protocol(app_ctx):1719    flask.g.foo = 231720    flask.g.bar = 421721    assert 'foo' in flask.g1722    assert 'foos' not in flask.g1723    assert sorted(flask.g) == ['bar', 'foo']172417251726def test_subdomain_basic_support(app, client):1727    app.config['SERVER_NAME'] = 'localhost.localdomain'17281729    @app.route('/')1730    def normal_index():1731        return 'normal index'17321733    @app.route('/', subdomain='test')1734    def test_index():1735        return 'test index'17361737    rv = client.get('/', 'http://localhost.localdomain/')1738    assert rv.data == b'normal index'17391740    rv = client.get('/', 'http://test.localhost.localdomain/')1741    assert rv.data == b'test index'174217431744def test_subdomain_matching(app, client):1745    app.config['SERVER_NAME'] = 'localhost.localdomain'17461747    @app.route('/', subdomain='<user>')1748    def index(user):1749        return 'index for %s' % user17501751    rv = client.get('/', 'http://mitsuhiko.localhost.localdomain/')1752    assert rv.data == b'index for mitsuhiko'175317541755def test_subdomain_matching_with_ports(app, client):1756    app.config['SERVER_NAME'] = 'localhost.localdomain:3000'17571758    @app.route('/', subdomain='<user>')1759    def index(user):1760        return 'index for %s' % user17611762    rv = client.get('/', 'http://mitsuhiko.localhost.localdomain:3000/')1763    assert rv.data == b'index for mitsuhiko'176417651766def test_multi_route_rules(app, client):1767    @app.route('/')1768    @app.route('/<test>/')1769    def index(test='a'):1770        return test17711772    rv = client.open('/')1773    assert rv.data == b'a'1774    rv = client.open('/b/')1775    assert rv.data == b'b'177617771778def test_multi_route_class_views(app, client):1779    class View(object):1780        def __init__(self, app):1781            app.add_url_rule('/', 'index', self.index)1782            app.add_url_rule('/<test>/', 'index', self.index)17831784        def index(self, test='a'):1785            return test17861787    _ = View(app)1788    rv = client.open('/')1789    assert rv.data == b'a'1790    rv = client.open('/b/')1791    assert rv.data == b'b'179217931794def test_run_defaults(monkeypatch, app):1795    rv = {}17961797    # Mocks werkzeug.serving.run_simple method1798    def run_simple_mock(*args, **kwargs):1799        rv['result'] = 'running...'18001801    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1802    app.run()1803    assert rv['result'] == 'running...'180418051806def test_run_server_port(monkeypatch, app):1807    rv = {}18081809    # Mocks werkzeug.serving.run_simple method1810    def run_simple_mock(hostname, port, application, *args, **kwargs):1811        rv['result'] = 'running on %s:%s ...' % (hostname, port)18121813    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1814    hostname, port = 'localhost', 80001815    app.run(hostname, port, debug=True)1816    assert rv['result'] == 'running on %s:%s ...' % (hostname, port)181718181819@pytest.mark.parametrize('host,port,expect_host,expect_port', (1820        (None, None, 'pocoo.org', 8080),1821        ('localhost', None, 'localhost', 8080),1822        (None, 80, 'pocoo.org', 80),1823        ('localhost', 80, 'localhost', 80),1824))1825def test_run_from_config(monkeypatch, host, port, expect_host, expect_port, app):1826    def run_simple_mock(hostname, port, *args, **kwargs):1827        assert hostname == expect_host1828        assert port == expect_port18291830    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1831    app.config['SERVER_NAME'] = 'pocoo.org:8080'1832    app.run(host, port)