Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

1,801 lines · 48.1 KiB · Python

Last changed by

update changelogDavid Lordbefore adoption97e2cd0

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():29    app = flask.Flask(__name__)3031    @app.route('/', methods=['GET', 'POST'])32    def index():33        return 'Hello World'34    rv = app.test_client().open('/', method='OPTIONS')35    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']36    assert rv.data == b''373839def test_options_on_multiple_rules():40    app = flask.Flask(__name__)4142    @app.route('/', methods=['GET', 'POST'])43    def index():44        return 'Hello World'4546    @app.route('/', methods=['PUT'])47    def index_put():48        return 'Aha!'49    rv = app.test_client().open('/', method='OPTIONS')50    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']515253def test_provide_automatic_options_attr():54    app = flask.Flask(__name__)5556    def index():57        return 'Hello World!'58    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!'67    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():74    app = flask.Flask(__name__)7576    def index():77        return flask.request.method7879    def more():80        return flask.request.method8182    app.add_url_rule('/', view_func=index, provide_automatic_options=False)83    app.add_url_rule(84        '/more', view_func=more, methods=['GET', 'POST'],85        provide_automatic_options=False86    )8788    c = app.test_client()89    assert c.get('/').data == b'GET'9091    rv = c.post('/')92    assert rv.status_code == 40593    assert sorted(rv.allow) == ['GET', 'HEAD']9495    # Older versions of Werkzeug.test.Client don't have an options method96    if hasattr(c, 'options'):97        rv = c.options('/')98    else:99        rv = c.open('/', method='OPTIONS')100101    assert rv.status_code == 405102103    rv = c.head('/')104    assert rv.status_code == 200105    assert not rv.data  # head truncates106    assert c.post('/more').data == b'POST'107    assert c.get('/more').data == b'GET'108109    rv = c.delete('/more')110    assert rv.status_code == 405111    assert sorted(rv.allow) == ['GET', 'HEAD', 'POST']112113    if hasattr(c, 'options'):114        rv = c.options('/more')115    else:116        rv = c.open('/more', method='OPTIONS')117118    assert rv.status_code == 405119120121def test_request_dispatching():122    app = flask.Flask(__name__)123124    @app.route('/')125    def index():126        return flask.request.method127128    @app.route('/more', methods=['GET', 'POST'])129    def more():130        return flask.request.method131132    c = app.test_client()133    assert c.get('/').data == b'GET'134    rv = c.post('/')135    assert rv.status_code == 405136    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']137    rv = c.head('/')138    assert rv.status_code == 200139    assert not rv.data  # head truncates140    assert c.post('/more').data == b'POST'141    assert c.get('/more').data == b'GET'142    rv = c.delete('/more')143    assert rv.status_code == 405144    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']145146147def test_disallow_string_for_allowed_methods():148    app = flask.Flask(__name__)149    with pytest.raises(TypeError):150        @app.route('/', methods='GET POST')151        def index():152            return "Hey"153154155def test_url_mapping():156    app = flask.Flask(__name__)157158    random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"159160    def index():161        return flask.request.method162163    def more():164        return flask.request.method165166    def options():167        return random_uuid4168169170    app.add_url_rule('/', 'index', index)171    app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])172173    # Issue 1288: Test that automatic options are not added when non-uppercase 'options' in methods174    app.add_url_rule('/options', 'options', options, methods=['options'])175176    c = app.test_client()177    assert c.get('/').data == b'GET'178    rv = c.post('/')179    assert rv.status_code == 405180    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']181    rv = c.head('/')182    assert rv.status_code == 200183    assert not rv.data  # head truncates184    assert c.post('/more').data == b'POST'185    assert c.get('/more').data == b'GET'186    rv = c.delete('/more')187    assert rv.status_code == 405188    assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']189    rv = c.open('/options', method='OPTIONS')190    assert rv.status_code == 200191    assert random_uuid4 in rv.data.decode("utf-8")192193194def test_werkzeug_routing():195    from werkzeug.routing import Submount, Rule196    app = flask.Flask(__name__)197    app.url_map.add(Submount('/foo', [198        Rule('/bar', endpoint='bar'),199        Rule('/', endpoint='index')200    ]))201202    def bar():203        return 'bar'204205    def index():206        return 'index'207    app.view_functions['bar'] = bar208    app.view_functions['index'] = index209210    c = app.test_client()211    assert c.get('/foo/').data == b'index'212    assert c.get('/foo/bar').data == b'bar'213214215def test_endpoint_decorator():216    from werkzeug.routing import Submount, Rule217    app = flask.Flask(__name__)218    app.url_map.add(Submount('/foo', [219        Rule('/bar', endpoint='bar'),220        Rule('/', endpoint='index')221    ]))222223    @app.endpoint('bar')224    def bar():225        return 'bar'226227    @app.endpoint('index')228    def index():229        return 'index'230231    c = app.test_client()232    assert c.get('/foo/').data == b'index'233    assert c.get('/foo/bar').data == b'bar'234235236def test_session():237    app = flask.Flask(__name__)238    app.secret_key = 'testkey'239240    @app.route('/set', methods=['POST'])241    def set():242        flask.session['value'] = flask.request.form['value']243        return 'value set'244245    @app.route('/get')246    def get():247        return flask.session['value']248249    c = app.test_client()250    assert c.post('/set', data={'value': '42'}).data == b'value set'251    assert c.get('/get').data == b'42'252253254def test_session_using_server_name():255    app = flask.Flask(__name__)256    app.config.update(257        SECRET_KEY='foo',258        SERVER_NAME='example.com'259    )260261    @app.route('/')262    def index():263        flask.session['testing'] = 42264        return 'Hello World'265    rv = app.test_client().get('/', 'http://example.com/')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_and_port():271    app = flask.Flask(__name__)272    app.config.update(273        SECRET_KEY='foo',274        SERVER_NAME='example.com:8080'275    )276277    @app.route('/')278    def index():279        flask.session['testing'] = 42280        return 'Hello World'281    rv = app.test_client().get('/', 'http://example.com:8080/')282    assert 'domain=.example.com' in rv.headers['set-cookie'].lower()283    assert 'httponly' in rv.headers['set-cookie'].lower()284285286def test_session_using_server_name_port_and_path():287    app = flask.Flask(__name__)288    app.config.update(289        SECRET_KEY='foo',290        SERVER_NAME='example.com:8080',291        APPLICATION_ROOT='/foo'292    )293294    @app.route('/')295    def index():296        flask.session['testing'] = 42297        return 'Hello World'298    rv = app.test_client().get('/', 'http://example.com:8080/foo')299    assert 'domain=example.com' in rv.headers['set-cookie'].lower()300    assert 'path=/foo' in rv.headers['set-cookie'].lower()301    assert 'httponly' in rv.headers['set-cookie'].lower()302303304def test_session_using_application_root():305    class PrefixPathMiddleware(object):306307        def __init__(self, app, prefix):308            self.app = app309            self.prefix = prefix310311        def __call__(self, environ, start_response):312            environ['SCRIPT_NAME'] = self.prefix313            return self.app(environ, start_response)314315    app = flask.Flask(__name__)316    app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar')317    app.config.update(318        SECRET_KEY='foo',319        APPLICATION_ROOT='/bar'320    )321322    @app.route('/')323    def index():324        flask.session['testing'] = 42325        return 'Hello World'326    rv = app.test_client().get('/', 'http://example.com:8080/')327    assert 'path=/bar' in rv.headers['set-cookie'].lower()328329330def test_session_using_session_settings():331    app = flask.Flask(__name__)332    app.config.update(333        SECRET_KEY='foo',334        SERVER_NAME='www.example.com:8080',335        APPLICATION_ROOT='/test',336        SESSION_COOKIE_DOMAIN='.example.com',337        SESSION_COOKIE_HTTPONLY=False,338        SESSION_COOKIE_SECURE=True,339        SESSION_COOKIE_PATH='/'340    )341342    @app.route('/')343    def index():344        flask.session['testing'] = 42345        return 'Hello World'346    rv = app.test_client().get('/', 'http://www.example.com:8080/test/')347    cookie = rv.headers['set-cookie'].lower()348    assert 'domain=.example.com' in cookie349    assert 'path=/' in cookie350    assert 'secure' in cookie351    assert 'httponly' not in cookie352353354def test_missing_session():355    app = flask.Flask(__name__)356357    def expect_exception(f, *args, **kwargs):358        e = pytest.raises(RuntimeError, f, *args, **kwargs)359        assert e.value.args and 'session is unavailable' in e.value.args[0]360    with app.test_request_context():361        assert flask.session.get('missing_key') is None362        expect_exception(flask.session.__setitem__, 'foo', 42)363        expect_exception(flask.session.pop, 'foo')364365366def test_session_expiration():367    permanent = True368    app = flask.Flask(__name__)369    app.secret_key = 'testkey'370371    @app.route('/')372    def index():373        flask.session['test'] = 42374        flask.session.permanent = permanent375        return ''376377    @app.route('/test')378    def test():379        return text_type(flask.session.permanent)380381    client = app.test_client()382    rv = client.get('/')383    assert 'set-cookie' in rv.headers384    match = re.search(r'(?i)\bexpires=([^;]+)', rv.headers['set-cookie'])385    expires = parse_date(match.group())386    expected = datetime.utcnow() + app.permanent_session_lifetime387    assert expires.year == expected.year388    assert expires.month == expected.month389    assert expires.day == expected.day390391    rv = client.get('/test')392    assert rv.data == b'True'393394    permanent = False395    rv = app.test_client().get('/')396    assert 'set-cookie' in rv.headers397    match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])398    assert match is None399400401def test_session_stored_last():402    app = flask.Flask(__name__)403    app.secret_key = 'development-key'404    app.testing = True405406    @app.after_request407    def modify_session(response):408        flask.session['foo'] = 42409        return response410411    @app.route('/')412    def dump_session_contents():413        return repr(flask.session.get('foo'))414415    c = app.test_client()416    assert c.get('/').data == b'None'417    assert c.get('/').data == b'42'418419420def test_session_special_types():421    app = flask.Flask(__name__)422    app.secret_key = 'development-key'423    app.testing = True424    now = datetime.utcnow().replace(microsecond=0)425    the_uuid = uuid.uuid4()426427    @app.after_request428    def modify_session(response):429        flask.session['m'] = flask.Markup('Hello!')430        flask.session['u'] = the_uuid431        flask.session['dt'] = now432        flask.session['b'] = b'\xff'433        flask.session['t'] = (1, 2, 3)434        return response435436    @app.route('/')437    def dump_session_contents():438        return pickle.dumps(dict(flask.session))439440    c = app.test_client()441    c.get('/')442    rv = pickle.loads(c.get('/').data)443    assert rv['m'] == flask.Markup('Hello!')444    assert type(rv['m']) == flask.Markup445    assert rv['dt'] == now446    assert rv['u'] == the_uuid447    assert rv['b'] == b'\xff'448    assert type(rv['b']) == bytes449    assert rv['t'] == (1, 2, 3)450451452def test_session_cookie_setting():453    app = flask.Flask(__name__)454    app.testing = True455    app.secret_key = 'dev key'456    is_permanent = True457458    @app.route('/bump')459    def bump():460        rv = flask.session['foo'] = flask.session.get('foo', 0) + 1461        flask.session.permanent = is_permanent462        return str(rv)463464    @app.route('/read')465    def read():466        return str(flask.session.get('foo', 0))467468    def run_test(expect_header):469        with app.test_client() as c:470            assert c.get('/bump').data == b'1'471            assert c.get('/bump').data == b'2'472            assert c.get('/bump').data == b'3'473474            rv = c.get('/read')475            set_cookie = rv.headers.get('set-cookie')476            assert (set_cookie is not None) == expect_header477            assert rv.data == b'3'478479    is_permanent = True480    app.config['SESSION_REFRESH_EACH_REQUEST'] = True481    run_test(expect_header=True)482483    is_permanent = True484    app.config['SESSION_REFRESH_EACH_REQUEST'] = False485    run_test(expect_header=False)486487    is_permanent = False488    app.config['SESSION_REFRESH_EACH_REQUEST'] = True489    run_test(expect_header=False)490491    is_permanent = False492    app.config['SESSION_REFRESH_EACH_REQUEST'] = False493    run_test(expect_header=False)494495496def test_flashes():497    app = flask.Flask(__name__)498    app.secret_key = 'testkey'499500    with app.test_request_context():501        assert not flask.session.modified502        flask.flash('Zap')503        flask.session.modified = False504        flask.flash('Zip')505        assert flask.session.modified506        assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']507508509def test_extended_flashing():510    # Be sure app.testing=True below, else tests can fail silently.511    #512    # Specifically, if app.testing is not set to True, the AssertionErrors513    # in the view functions will cause a 500 response to the test client514    # instead of propagating exceptions.515516    app = flask.Flask(__name__)517    app.secret_key = 'testkey'518    app.testing = True519520    @app.route('/')521    def index():522        flask.flash(u'Hello World')523        flask.flash(u'Hello World', 'error')524        flask.flash(flask.Markup(u'<em>Testing</em>'), 'warning')525        return ''526527    @app.route('/test/')528    def test():529        messages = flask.get_flashed_messages()530        assert list(messages) == [531            u'Hello World',532            u'Hello World',533            flask.Markup(u'<em>Testing</em>')534        ]535        return ''536537    @app.route('/test_with_categories/')538    def test_with_categories():539        messages = flask.get_flashed_messages(with_categories=True)540        assert len(messages) == 3541        assert list(messages) == [542            ('message', u'Hello World'),543            ('error', u'Hello World'),544            ('warning', flask.Markup(u'<em>Testing</em>'))545        ]546        return ''547548    @app.route('/test_filter/')549    def test_filter():550        messages = flask.get_flashed_messages(551            category_filter=['message'], with_categories=True)552        assert list(messages) == [('message', u'Hello World')]553        return ''554555    @app.route('/test_filters/')556    def test_filters():557        messages = flask.get_flashed_messages(558            category_filter=['message', 'warning'], with_categories=True)559        assert list(messages) == [560            ('message', u'Hello World'),561            ('warning', flask.Markup(u'<em>Testing</em>'))562        ]563        return ''564565    @app.route('/test_filters_without_returning_categories/')566    def test_filters2():567        messages = flask.get_flashed_messages(568            category_filter=['message', 'warning'])569        assert len(messages) == 2570        assert messages[0] == u'Hello World'571        assert messages[1] == flask.Markup(u'<em>Testing</em>')572        return ''573574    # Create new test client on each test to clean flashed messages.575576    c = app.test_client()577    c.get('/')578    c.get('/test/')579580    c = app.test_client()581    c.get('/')582    c.get('/test_with_categories/')583584    c = app.test_client()585    c.get('/')586    c.get('/test_filter/')587588    c = app.test_client()589    c.get('/')590    c.get('/test_filters/')591592    c = app.test_client()593    c.get('/')594    c.get('/test_filters_without_returning_categories/')595596597def test_request_processing():598    app = flask.Flask(__name__)599    evts = []600601    @app.before_request602    def before_request():603        evts.append('before')604605    @app.after_request606    def after_request(response):607        response.data += b'|after'608        evts.append('after')609        return response610611    @app.route('/')612    def index():613        assert 'before' in evts614        assert 'after' not in evts615        return 'request'616    assert 'after' not in evts617    rv = app.test_client().get('/').data618    assert 'after' in evts619    assert rv == b'request|after'620621622def test_request_preprocessing_early_return():623    app = flask.Flask(__name__)624    evts = []625626    @app.before_request627    def before_request1():628        evts.append(1)629630    @app.before_request631    def before_request2():632        evts.append(2)633        return "hello"634635    @app.before_request636    def before_request3():637        evts.append(3)638        return "bye"639640    @app.route('/')641    def index():642        evts.append('index')643        return "damnit"644645    rv = app.test_client().get('/').data.strip()646    assert rv == b'hello'647    assert evts == [1, 2]648649650def test_after_request_processing():651    app = flask.Flask(__name__)652    app.testing = True653654    @app.route('/')655    def index():656        @flask.after_this_request657        def foo(response):658            response.headers['X-Foo'] = 'a header'659            return response660        return 'Test'661    c = app.test_client()662    resp = c.get('/')663    assert resp.status_code == 200664    assert resp.headers['X-Foo'] == 'a header'665666667def test_teardown_request_handler():668    called = []669    app = flask.Flask(__name__)670671    @app.teardown_request672    def teardown_request(exc):673        called.append(True)674        return "Ignored"675676    @app.route('/')677    def root():678        return "Response"679    rv = app.test_client().get('/')680    assert rv.status_code == 200681    assert b'Response' in rv.data682    assert len(called) == 1683684685def test_teardown_request_handler_debug_mode():686    called = []687    app = flask.Flask(__name__)688    app.testing = True689690    @app.teardown_request691    def teardown_request(exc):692        called.append(True)693        return "Ignored"694695    @app.route('/')696    def root():697        return "Response"698    rv = app.test_client().get('/')699    assert rv.status_code == 200700    assert b'Response' in rv.data701    assert len(called) == 1702703704def test_teardown_request_handler_error():705    called = []706    app = flask.Flask(__name__)707    app.config['LOGGER_HANDLER_POLICY'] = 'never'708709    @app.teardown_request710    def teardown_request1(exc):711        assert type(exc) == ZeroDivisionError712        called.append(True)713        # This raises a new error and blows away sys.exc_info(), so we can714        # test that all teardown_requests get passed the same original715        # exception.716        try:717            raise TypeError()718        except:719            pass720721    @app.teardown_request722    def teardown_request2(exc):723        assert type(exc) == ZeroDivisionError724        called.append(True)725        # This raises a new error and blows away sys.exc_info(), so we can726        # test that all teardown_requests get passed the same original727        # exception.728        try:729            raise TypeError()730        except:731            pass732733    @app.route('/')734    def fails():735        1 // 0736    rv = app.test_client().get('/')737    assert rv.status_code == 500738    assert b'Internal Server Error' in rv.data739    assert len(called) == 2740741742def test_before_after_request_order():743    called = []744    app = flask.Flask(__name__)745746    @app.before_request747    def before1():748        called.append(1)749750    @app.before_request751    def before2():752        called.append(2)753754    @app.after_request755    def after1(response):756        called.append(4)757        return response758759    @app.after_request760    def after2(response):761        called.append(3)762        return response763764    @app.teardown_request765    def finish1(exc):766        called.append(6)767768    @app.teardown_request769    def finish2(exc):770        called.append(5)771772    @app.route('/')773    def index():774        return '42'775    rv = app.test_client().get('/')776    assert rv.data == b'42'777    assert called == [1, 2, 3, 4, 5, 6]778779780def test_error_handling():781    app = flask.Flask(__name__)782    app.config['LOGGER_HANDLER_POLICY'] = 'never'783784    @app.errorhandler(404)785    def not_found(e):786        return 'not found', 404787788    @app.errorhandler(500)789    def internal_server_error(e):790        return 'internal server error', 500791792    @app.errorhandler(Forbidden)793    def forbidden(e):794        return 'forbidden', 403795796    @app.route('/')797    def index():798        flask.abort(404)799800    @app.route('/error')801    def error():802        1 // 0803804    @app.route('/forbidden')805    def error2():806        flask.abort(403)807    c = app.test_client()808    rv = c.get('/')809    assert rv.status_code == 404810    assert rv.data == b'not found'811    rv = c.get('/error')812    assert rv.status_code == 500813    assert b'internal server error' == rv.data814    rv = c.get('/forbidden')815    assert rv.status_code == 403816    assert b'forbidden' == rv.data817818819def test_error_handling_processing():820    app = flask.Flask(__name__)821    app.config['LOGGER_HANDLER_POLICY'] = 'never'822823    @app.errorhandler(500)824    def internal_server_error(e):825        return 'internal server error', 500826827    @app.route('/')828    def broken_func():829        1 // 0830831    @app.after_request832    def after_request(resp):833        resp.mimetype = 'text/x-special'834        return resp835836    with app.test_client() as c:837        resp = c.get('/')838        assert resp.mimetype == 'text/x-special'839        assert resp.data == b'internal server error'840841842def test_baseexception_error_handling():843    app = flask.Flask(__name__)844    app.config['LOGGER_HANDLER_POLICY'] = 'never'845846    @app.route('/')847    def broken_func():848        raise KeyboardInterrupt()849850    with app.test_client() as c:851        with pytest.raises(KeyboardInterrupt):852            c.get('/')853854        ctx = flask._request_ctx_stack.top855        assert ctx.preserved856        assert type(ctx._preserved_exc) is KeyboardInterrupt857858859def test_before_request_and_routing_errors():860    app = flask.Flask(__name__)861862    @app.before_request863    def attach_something():864        flask.g.something = 'value'865866    @app.errorhandler(404)867    def return_something(error):868        return flask.g.something, 404869    rv = app.test_client().get('/')870    assert rv.status_code == 404871    assert rv.data == b'value'872873874def test_user_error_handling():875    class MyException(Exception):876        pass877878    app = flask.Flask(__name__)879880    @app.errorhandler(MyException)881    def handle_my_exception(e):882        assert isinstance(e, MyException)883        return '42'884885    @app.route('/')886    def index():887        raise MyException()888889    c = app.test_client()890    assert c.get('/').data == b'42'891892893def test_http_error_subclass_handling():894    class ForbiddenSubclass(Forbidden):895        pass896897    app = flask.Flask(__name__)898899    @app.errorhandler(ForbiddenSubclass)900    def handle_forbidden_subclass(e):901        assert isinstance(e, ForbiddenSubclass)902        return 'banana'903904    @app.errorhandler(403)905    def handle_forbidden_subclass(e):906        assert not isinstance(e, ForbiddenSubclass)907        assert isinstance(e, Forbidden)908        return 'apple'909910    @app.route('/1')911    def index1():912        raise ForbiddenSubclass()913914    @app.route('/2')915    def index2():916        flask.abort(403)917918    @app.route('/3')919    def index3():920        raise Forbidden()921922    c = app.test_client()923    assert c.get('/1').data == b'banana'924    assert c.get('/2').data == b'apple'925    assert c.get('/3').data == b'apple'926927928def test_trapping_of_bad_request_key_errors():929    app = flask.Flask(__name__)930    app.testing = True931932    @app.route('/fail')933    def fail():934        flask.request.form['missing_key']935    c = app.test_client()936    assert c.get('/fail').status_code == 400937938    app.config['TRAP_BAD_REQUEST_ERRORS'] = True939    c = app.test_client()940    with pytest.raises(KeyError) as e:941        c.get("/fail")942    assert e.errisinstance(BadRequest)943944945def test_trapping_of_all_http_exceptions():946    app = flask.Flask(__name__)947    app.testing = True948    app.config['TRAP_HTTP_EXCEPTIONS'] = True949950    @app.route('/fail')951    def fail():952        flask.abort(404)953954    c = app.test_client()955    with pytest.raises(NotFound):956        c.get('/fail')957958959def test_enctype_debug_helper():960    from flask.debughelpers import DebugFilesKeyError961    app = flask.Flask(__name__)962    app.debug = True963964    @app.route('/fail', methods=['POST'])965    def index():966        return flask.request.files['foo'].filename967968    # with statement is important because we leave an exception on the969    # stack otherwise and we want to ensure that this is not the case970    # to not negatively affect other tests.971    with app.test_client() as c:972        with pytest.raises(DebugFilesKeyError) as e:973            c.post('/fail', data={'foo': 'index.txt'})974        assert 'no file contents were transmitted' in str(e.value)975        assert 'This was submitted: "index.txt"' in str(e.value)976977978def test_response_creation():979    app = flask.Flask(__name__)980981    @app.route('/unicode')982    def from_unicode():983        return u'Hällo Wörld'984985    @app.route('/string')986    def from_string():987        return u'Hällo Wörld'.encode('utf-8')988989    @app.route('/args')990    def from_tuple():991        return 'Meh', 400, {992            'X-Foo': 'Testing',993            'Content-Type': 'text/plain; charset=utf-8'994        }995996    @app.route('/two_args')997    def from_two_args_tuple():998        return 'Hello', {999            'X-Foo': 'Test',1000            'Content-Type': 'text/plain; charset=utf-8'1001        }10021003    @app.route('/args_status')1004    def from_status_tuple():1005        return 'Hi, status!', 40010061007    @app.route('/args_header')1008    def from_response_instance_status_tuple():1009        return flask.Response('Hello world', 404), {1010            "X-Foo": "Bar",1011            "X-Bar": "Foo"1012        }10131014    c = app.test_client()1015    assert c.get('/unicode').data == u'Hällo Wörld'.encode('utf-8')1016    assert c.get('/string').data == u'Hällo Wörld'.encode('utf-8')1017    rv = c.get('/args')1018    assert rv.data == b'Meh'1019    assert rv.headers['X-Foo'] == 'Testing'1020    assert rv.status_code == 4001021    assert rv.mimetype == 'text/plain'1022    rv2 = c.get('/two_args')1023    assert rv2.data == b'Hello'1024    assert rv2.headers['X-Foo'] == 'Test'1025    assert rv2.status_code == 2001026    assert rv2.mimetype == 'text/plain'1027    rv3 = c.get('/args_status')1028    assert rv3.data == b'Hi, status!'1029    assert rv3.status_code == 4001030    assert rv3.mimetype == 'text/html'1031    rv4 = c.get('/args_header')1032    assert rv4.data == b'Hello world'1033    assert rv4.headers['X-Foo'] == 'Bar'1034    assert rv4.headers['X-Bar'] == 'Foo'1035    assert rv4.status_code == 404103610371038def test_make_response():1039    app = flask.Flask(__name__)1040    with app.test_request_context():1041        rv = flask.make_response()1042        assert rv.status_code == 2001043        assert rv.data == b''1044        assert rv.mimetype == 'text/html'10451046        rv = flask.make_response('Awesome')1047        assert rv.status_code == 2001048        assert rv.data == b'Awesome'1049        assert rv.mimetype == 'text/html'10501051        rv = flask.make_response('W00t', 404)1052        assert rv.status_code == 4041053        assert rv.data == b'W00t'1054        assert rv.mimetype == 'text/html'105510561057def test_make_response_with_response_instance():1058    app = flask.Flask(__name__)1059    with app.test_request_context():1060        rv = flask.make_response(1061            flask.jsonify({'msg': 'W00t'}), 400)1062        assert rv.status_code == 4001063        assert rv.data == b'{"msg":"W00t"}\n'1064        assert rv.mimetype == 'application/json'10651066        rv = flask.make_response(1067            flask.Response(''), 400)1068        assert rv.status_code == 4001069        assert rv.data == b''1070        assert rv.mimetype == 'text/html'10711072        rv = flask.make_response(1073            flask.Response('', headers={'Content-Type': 'text/html'}),1074            400, [('X-Foo', 'bar')])1075        assert rv.status_code == 4001076        assert rv.headers['Content-Type'] == 'text/html'1077        assert rv.headers['X-Foo'] == 'bar'107810791080def test_jsonify_no_prettyprint():1081    app = flask.Flask(__name__)1082    app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1083    with app.test_request_context():1084        compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1085        uncompressed_msg = {1086            "msg": {1087                "submsg": "W00t"1088            },1089            "msg2": "foobar"1090            }10911092        rv = flask.make_response(1093            flask.jsonify(uncompressed_msg), 200)1094        assert rv.data == compressed_msg109510961097def test_jsonify_prettyprint():1098    app = flask.Flask(__name__)1099    app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1100    with app.test_request_context():1101        compressed_msg = {"msg":{"submsg":"W00t"},"msg2":"foobar"}1102        pretty_response =\1103            b'{\n  "msg": {\n    "submsg": "W00t"\n  }, \n  "msg2": "foobar"\n}\n'11041105        rv = flask.make_response(1106            flask.jsonify(compressed_msg), 200)1107        assert rv.data == pretty_response110811091110def test_jsonify_mimetype():1111    app = flask.Flask(__name__)1112    app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'})1113    with app.test_request_context():1114        msg = {1115            "msg": {"submsg": "W00t"},1116        }1117        rv = flask.make_response(1118            flask.jsonify(msg), 200)1119        assert rv.mimetype == 'application/vnd.api+json'112011211122def test_jsonify_args_and_kwargs_check():1123    app = flask.Flask(__name__)1124    with app.test_request_context():1125        with pytest.raises(TypeError) as e:1126            flask.jsonify('fake args', kwargs='fake')1127        assert 'behavior undefined' in str(e.value)112811291130def test_url_generation():1131    app = flask.Flask(__name__)11321133    @app.route('/hello/<name>', methods=['POST'])1134    def hello():1135        pass1136    with app.test_request_context():1137        assert flask.url_for('hello', name='test x') == '/hello/test%20x'1138        assert flask.url_for('hello', name='test x', _external=True) == \1139            'http://localhost/hello/test%20x'114011411142def test_build_error_handler():1143    app = flask.Flask(__name__)11441145    # Test base case, a URL which results in a BuildError.1146    with app.test_request_context():1147        pytest.raises(BuildError, flask.url_for, 'spam')11481149    # Verify the error is re-raised if not the current exception.1150    try:1151        with app.test_request_context():1152            flask.url_for('spam')1153    except BuildError as err:1154        error = err1155    try:1156        raise RuntimeError('Test case where BuildError is not current.')1157    except RuntimeError:1158        pytest.raises(1159            BuildError, app.handle_url_build_error, error, 'spam', {})11601161    # Test a custom handler.1162    def handler(error, endpoint, values):1163        # Just a test.1164        return '/test_handler/'1165    app.url_build_error_handlers.append(handler)1166    with app.test_request_context():1167        assert flask.url_for('spam') == '/test_handler/'116811691170def test_build_error_handler_reraise():1171    app = flask.Flask(__name__)11721173    # Test a custom handler which reraises the BuildError1174    def handler_raises_build_error(error, endpoint, values):1175        raise error1176    app.url_build_error_handlers.append(handler_raises_build_error)11771178    with app.test_request_context():1179        pytest.raises(BuildError, flask.url_for, 'not.existing')118011811182def test_url_for_passes_special_values_to_build_error_handler():1183    app = flask.Flask(__name__)11841185    @app.url_build_error_handlers.append1186    def handler(error, endpoint, values):1187        assert values == {1188            '_external': False,1189            '_anchor': None,1190            '_method': None,1191            '_scheme': None,1192        }1193        return 'handled'11941195    with app.test_request_context():1196        flask.url_for('/')119711981199def test_custom_converters():1200    from werkzeug.routing import BaseConverter12011202    class ListConverter(BaseConverter):12031204        def to_python(self, value):1205            return value.split(',')12061207        def to_url(self, value):1208            base_to_url = super(ListConverter, self).to_url1209            return ','.join(base_to_url(x) for x in value)1210    app = flask.Flask(__name__)1211    app.url_map.converters['list'] = ListConverter12121213    @app.route('/<list:args>')1214    def index(args):1215        return '|'.join(args)1216    c = app.test_client()1217    assert c.get('/1,2,3').data == b'1|2|3'121812191220def test_static_files():1221    app = flask.Flask(__name__)1222    app.testing = True1223    rv = app.test_client().get('/static/index.html')1224    assert rv.status_code == 2001225    assert rv.data.strip() == b'<h1>Hello World!</h1>'1226    with app.test_request_context():1227        assert flask.url_for('static', filename='index.html') == \1228            '/static/index.html'1229    rv.close()123012311232def test_static_path_deprecated(recwarn):1233    app = flask.Flask(__name__, static_path='/foo')1234    recwarn.pop(DeprecationWarning)12351236    app.testing = True1237    rv = app.test_client().get('/foo/index.html')1238    assert rv.status_code == 2001239    rv.close()12401241    with app.test_request_context():1242        assert flask.url_for('static', filename='index.html') == '/foo/index.html'124312441245def test_static_url_path():1246    app = flask.Flask(__name__, static_url_path='/foo')1247    app.testing = True1248    rv = app.test_client().get('/foo/index.html')1249    assert rv.status_code == 2001250    rv.close()12511252    with app.test_request_context():1253        assert flask.url_for('static', filename='index.html') == '/foo/index.html'125412551256def test_static_route_with_host_matching():1257    app = flask.Flask(__name__, host_matching=True, static_host='example.com')1258    c = app.test_client()1259    rv = c.get('http://example.com/static/index.html')1260    assert rv.status_code == 2001261    rv.close()1262    with app.test_request_context():1263       rv = flask.url_for('static', filename='index.html', _external=True)1264       assert rv == 'http://example.com/static/index.html'1265    # Providing static_host without host_matching=True should error.1266    with pytest.raises(Exception):1267        flask.Flask(__name__, static_host='example.com')1268    # Providing host_matching=True with static_folder but without static_host should error.1269    with pytest.raises(Exception):1270        flask.Flask(__name__, host_matching=True)1271    # Providing host_matching=True without static_host but with static_folder=None should not error.1272    flask.Flask(__name__, host_matching=True, static_folder=None)127312741275def test_none_response():1276    app = flask.Flask(__name__)1277    app.testing = True12781279    @app.route('/')1280    def test():1281        return None1282    try:1283        app.test_client().get('/')1284    except ValueError as e:1285        assert str(e) == 'View function did not return a response'1286        pass1287    else:1288        assert "Expected ValueError"128912901291def test_request_locals():1292    assert repr(flask.g) == '<LocalProxy unbound>'1293    assert not flask.g129412951296def test_test_app_proper_environ():1297    app = flask.Flask(__name__)1298    app.config.update(1299        SERVER_NAME='localhost.localdomain:5000'1300    )13011302    @app.route('/')1303    def index():1304        return 'Foo'13051306    @app.route('/', subdomain='foo')1307    def subdomain():1308        return 'Foo SubDomain'13091310    rv = app.test_client().get('/')1311    assert rv.data == b'Foo'13121313    rv = app.test_client().get('/', 'http://localhost.localdomain:5000')1314    assert rv.data == b'Foo'13151316    rv = app.test_client().get('/', 'https://localhost.localdomain:5000')1317    assert rv.data == b'Foo'13181319    app.config.update(SERVER_NAME='localhost.localdomain')1320    rv = app.test_client().get('/', 'https://localhost.localdomain')1321    assert rv.data == b'Foo'13221323    try:1324        app.config.update(SERVER_NAME='localhost.localdomain:443')1325        rv = app.test_client().get('/', 'https://localhost.localdomain')1326        # Werkzeug 0.81327        assert rv.status_code == 4041328    except ValueError as e:1329        # Werkzeug 0.71330        assert str(e) == (1331            "the server name provided "1332            "('localhost.localdomain:443') does not match the "1333            "server name from the WSGI environment ('localhost.localdomain')"1334        )13351336    try:1337        app.config.update(SERVER_NAME='localhost.localdomain')1338        rv = app.test_client().get('/', 'http://foo.localhost')1339        # Werkzeug 0.81340        assert rv.status_code == 4041341    except ValueError as e:1342        # Werkzeug 0.71343        assert str(e) == (1344            "the server name provided "1345            "('localhost.localdomain') does not match the "1346            "server name from the WSGI environment ('foo.localhost')"1347        )13481349    rv = app.test_client().get('/', 'http://foo.localhost.localdomain')1350    assert rv.data == b'Foo SubDomain'135113521353def test_exception_propagation():1354    def apprunner(config_key):1355        app = flask.Flask(__name__)1356        app.config['LOGGER_HANDLER_POLICY'] = 'never'13571358        @app.route('/')1359        def index():1360            1 // 01361        c = app.test_client()1362        if config_key is not None:1363            app.config[config_key] = True1364            with pytest.raises(Exception):1365                c.get('/')1366        else:1367            assert c.get('/').status_code == 50013681369    # we have to run this test in an isolated thread because if the1370    # debug flag is set to true and an exception happens the context is1371    # not torn down.  This causes other tests that run after this fail1372    # when they expect no exception on the stack.1373    for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None:1374        t = Thread(target=apprunner, args=(config_key,))1375        t.start()1376        t.join()137713781379@pytest.mark.parametrize('debug', [True, False])1380@pytest.mark.parametrize('use_debugger', [True, False])1381@pytest.mark.parametrize('use_reloader', [True, False])1382@pytest.mark.parametrize('propagate_exceptions', [None, True, False])1383def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1384                                     use_reloader, propagate_exceptions):1385    rv = {}13861387    # Mocks werkzeug.serving.run_simple method1388    def run_simple_mock(*args, **kwargs):1389        rv['passthrough_errors'] = kwargs.get('passthrough_errors')13901391    app = flask.Flask(__name__)1392    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1393    app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1394    app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)139513961397def test_max_content_length():1398    app = flask.Flask(__name__)1399    app.config['MAX_CONTENT_LENGTH'] = 6414001401    @app.before_request1402    def always_first():1403        flask.request.form['myfile']1404        assert False14051406    @app.route('/accept', methods=['POST'])1407    def accept_file():1408        flask.request.form['myfile']1409        assert False14101411    @app.errorhandler(413)1412    def catcher(error):1413        return '42'14141415    c = app.test_client()1416    rv = c.post('/accept', data={'myfile': 'foo' * 100})1417    assert rv.data == b'42'141814191420def test_url_processors():1421    app = flask.Flask(__name__)14221423    @app.url_defaults1424    def add_language_code(endpoint, values):1425        if flask.g.lang_code is not None and \1426           app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1427            values.setdefault('lang_code', flask.g.lang_code)14281429    @app.url_value_preprocessor1430    def pull_lang_code(endpoint, values):1431        flask.g.lang_code = values.pop('lang_code', None)14321433    @app.route('/<lang_code>/')1434    def index():1435        return flask.url_for('about')14361437    @app.route('/<lang_code>/about')1438    def about():1439        return flask.url_for('something_else')14401441    @app.route('/foo')1442    def something_else():1443        return flask.url_for('about', lang_code='en')14441445    c = app.test_client()14461447    assert c.get('/de/').data == b'/de/about'1448    assert c.get('/de/about').data == b'/foo'1449    assert c.get('/foo').data == b'/en/about'145014511452def test_inject_blueprint_url_defaults():1453    app = flask.Flask(__name__)1454    bp = flask.Blueprint('foo.bar.baz', __name__,1455                         template_folder='template')14561457    @bp.url_defaults1458    def bp_defaults(endpoint, values):1459        values['page'] = 'login'14601461    @bp.route('/<page>')1462    def view(page):1463        pass14641465    app.register_blueprint(bp)14661467    values = dict()1468    app.inject_url_defaults('foo.bar.baz.view', values)1469    expected = dict(page='login')1470    assert values == expected14711472    with app.test_request_context('/somepage'):1473        url = flask.url_for('foo.bar.baz.view')1474    expected = '/login'1475    assert url == expected147614771478def test_nonascii_pathinfo():1479    app = flask.Flask(__name__)1480    app.testing = True14811482    @app.route(u'/киртест')1483    def index():1484        return 'Hello World!'14851486    c = app.test_client()1487    rv = c.get(u'/киртест')1488    assert rv.data == b'Hello World!'148914901491def test_debug_mode_complains_after_first_request():1492    app = flask.Flask(__name__)1493    app.debug = True14941495    @app.route('/')1496    def index():1497        return 'Awesome'1498    assert not app.got_first_request1499    assert app.test_client().get('/').data == b'Awesome'1500    with pytest.raises(AssertionError) as e:1501        @app.route('/foo')1502        def broken():1503            return 'Meh'1504    assert 'A setup function was called' in str(e)15051506    app.debug = False15071508    @app.route('/foo')1509    def working():1510        return 'Meh'1511    assert app.test_client().get('/foo').data == b'Meh'1512    assert app.got_first_request151315141515def test_before_first_request_functions():1516    got = []1517    app = flask.Flask(__name__)15181519    @app.before_first_request1520    def foo():1521        got.append(42)1522    c = app.test_client()1523    c.get('/')1524    assert got == [42]1525    c.get('/')1526    assert got == [42]1527    assert app.got_first_request152815291530def test_before_first_request_functions_concurrent():1531    got = []1532    app = flask.Flask(__name__)15331534    @app.before_first_request1535    def foo():1536        time.sleep(0.2)1537        got.append(42)15381539    c = app.test_client()15401541    def get_and_assert():1542        c.get("/")1543        assert got == [42]15441545    t = Thread(target=get_and_assert)1546    t.start()1547    get_and_assert()1548    t.join()1549    assert app.got_first_request155015511552def test_routing_redirect_debugging():1553    app = flask.Flask(__name__)1554    app.debug = True15551556    @app.route('/foo/', methods=['GET', 'POST'])1557    def foo():1558        return 'success'1559    with app.test_client() as c:1560        with pytest.raises(AssertionError) as e:1561            c.post('/foo', data={})1562        assert 'http://localhost/foo/' in str(e)1563        assert ('Make sure to directly send '1564                'your POST-request to this URL') in str(e)15651566        rv = c.get('/foo', data={}, follow_redirects=True)1567        assert rv.data == b'success'15681569    app.debug = False1570    with app.test_client() as c:1571        rv = c.post('/foo', data={}, follow_redirects=True)1572        assert rv.data == b'success'157315741575def test_route_decorator_custom_endpoint():1576    app = flask.Flask(__name__)1577    app.debug = True15781579    @app.route('/foo/')1580    def foo():1581        return flask.request.endpoint15821583    @app.route('/bar/', endpoint='bar')1584    def for_bar():1585        return flask.request.endpoint15861587    @app.route('/bar/123', endpoint='123')1588    def for_bar_foo():1589        return flask.request.endpoint15901591    with app.test_request_context():1592        assert flask.url_for('foo') == '/foo/'1593        assert flask.url_for('bar') == '/bar/'1594        assert flask.url_for('123') == '/bar/123'15951596    c = app.test_client()1597    assert c.get('/foo/').data == b'foo'1598    assert c.get('/bar/').data == b'bar'1599    assert c.get('/bar/123').data == b'123'160016011602def test_preserve_only_once():1603    app = flask.Flask(__name__)1604    app.debug = True16051606    @app.route('/fail')1607    def fail_func():1608        1 // 016091610    c = app.test_client()1611    for x in range(3):1612        with pytest.raises(ZeroDivisionError):1613            c.get('/fail')16141615    assert flask._request_ctx_stack.top is not None1616    assert flask._app_ctx_stack.top is not None1617    # implicit appctx disappears too1618    flask._request_ctx_stack.top.pop()1619    assert flask._request_ctx_stack.top is None1620    assert flask._app_ctx_stack.top is None162116221623def test_preserve_remembers_exception():1624    app = flask.Flask(__name__)1625    app.debug = True1626    errors = []16271628    @app.route('/fail')1629    def fail_func():1630        1 // 016311632    @app.route('/success')1633    def success_func():1634        return 'Okay'16351636    @app.teardown_request1637    def teardown_handler(exc):1638        errors.append(exc)16391640    c = app.test_client()16411642    # After this failure we did not yet call the teardown handler1643    with pytest.raises(ZeroDivisionError):1644        c.get('/fail')1645    assert errors == []16461647    # But this request triggers it, and it's an error1648    c.get('/success')1649    assert len(errors) == 21650    assert isinstance(errors[0], ZeroDivisionError)16511652    # At this point another request does nothing.1653    c.get('/success')1654    assert len(errors) == 31655    assert errors[1] is None165616571658def test_get_method_on_g():1659    app = flask.Flask(__name__)1660    app.testing = True16611662    with app.app_context():1663        assert flask.g.get('x') is None1664        assert flask.g.get('x', 11) == 111665        flask.g.x = 421666        assert flask.g.get('x') == 421667        assert flask.g.x == 42166816691670def test_g_iteration_protocol():1671    app = flask.Flask(__name__)1672    app.testing = True16731674    with app.app_context():1675        flask.g.foo = 231676        flask.g.bar = 421677        assert 'foo' in flask.g1678        assert 'foos' not in flask.g1679        assert sorted(flask.g) == ['bar', 'foo']168016811682def test_subdomain_basic_support():1683    app = flask.Flask(__name__)1684    app.config['SERVER_NAME'] = 'localhost'16851686    @app.route('/')1687    def normal_index():1688        return 'normal index'16891690    @app.route('/', subdomain='test')1691    def test_index():1692        return 'test index'16931694    c = app.test_client()1695    rv = c.get('/', 'http://localhost/')1696    assert rv.data == b'normal index'16971698    rv = c.get('/', 'http://test.localhost/')1699    assert rv.data == b'test index'170017011702def test_subdomain_matching():1703    app = flask.Flask(__name__)1704    app.config['SERVER_NAME'] = 'localhost'17051706    @app.route('/', subdomain='<user>')1707    def index(user):1708        return 'index for %s' % user17091710    c = app.test_client()1711    rv = c.get('/', 'http://mitsuhiko.localhost/')1712    assert rv.data == b'index for mitsuhiko'171317141715def test_subdomain_matching_with_ports():1716    app = flask.Flask(__name__)1717    app.config['SERVER_NAME'] = 'localhost:3000'17181719    @app.route('/', subdomain='<user>')1720    def index(user):1721        return 'index for %s' % user17221723    c = app.test_client()1724    rv = c.get('/', 'http://mitsuhiko.localhost:3000/')1725    assert rv.data == b'index for mitsuhiko'172617271728def test_multi_route_rules():1729    app = flask.Flask(__name__)17301731    @app.route('/')1732    @app.route('/<test>/')1733    def index(test='a'):1734        return test17351736    rv = app.test_client().open('/')1737    assert rv.data == b'a'1738    rv = app.test_client().open('/b/')1739    assert rv.data == b'b'174017411742def test_multi_route_class_views():1743    class View(object):17441745        def __init__(self, app):1746            app.add_url_rule('/', 'index', self.index)1747            app.add_url_rule('/<test>/', 'index', self.index)17481749        def index(self, test='a'):1750            return test17511752    app = flask.Flask(__name__)1753    _ = View(app)1754    rv = app.test_client().open('/')1755    assert rv.data == b'a'1756    rv = app.test_client().open('/b/')1757    assert rv.data == b'b'175817591760def test_run_defaults(monkeypatch):1761    rv = {}17621763    # Mocks werkzeug.serving.run_simple method1764    def run_simple_mock(*args, **kwargs):1765        rv['result'] = 'running...'17661767    app = flask.Flask(__name__)1768    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1769    app.run()1770    assert rv['result'] == 'running...'177117721773def test_run_server_port(monkeypatch):1774    rv = {}17751776    # Mocks werkzeug.serving.run_simple method1777    def run_simple_mock(hostname, port, application, *args, **kwargs):1778        rv['result'] = 'running on %s:%s ...' % (hostname, port)17791780    app = flask.Flask(__name__)1781    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1782    hostname, port = 'localhost', 80001783    app.run(hostname, port, debug=True)1784    assert rv['result'] == 'running on %s:%s ...' % (hostname, port)178517861787@pytest.mark.parametrize('host,port,expect_host,expect_port', (1788    (None, None, 'pocoo.org', 8080),1789    ('localhost', None, 'localhost', 8080),1790    (None, 80, 'pocoo.org', 80),1791    ('localhost', 80, 'localhost', 80),1792))1793def test_run_from_config(monkeypatch, host, port, expect_host, expect_port):1794    def run_simple_mock(hostname, port, *args, **kwargs):1795        assert hostname == expect_host1796        assert port == expect_port17971798    monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1799    app = flask.Flask(__name__)1800    app.config['SERVER_NAME'] = 'pocoo.org:8080'1801    app.run(host, port)