test_basic.py
This file
Path
tests/test_basic.py
1,855 lines · 49.2 KiB · Python
Last changed by
DRYing up the test suite using pytest fixtures (#2306)Christian Stade-Schuldtbefore adoption5b0b971
History of this fileTake it
1# -*- coding: utf-8 -*-2"""3 tests.basic4 ~~~~~~~~~~~~~~~~~~~~~56 The basic functionality.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314import re15import uuid16import time17import flask18import pickle19from datetime import datetime20from threading import Thread21from flask._compat import text_type22from werkzeug.exceptions import BadRequest, NotFound, Forbidden23from werkzeug.http import parse_date24from werkzeug.routing import BuildError25import werkzeug.serving262728def test_options_work(app, client):29 @app.route('/', methods=['GET', 'POST'])30 def index():31 return 'Hello World'3233 rv = client.open('/', method='OPTIONS')34 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']35 assert rv.data == b''363738def test_options_on_multiple_rules(app, client):39 @app.route('/', methods=['GET', 'POST'])40 def index():41 return 'Hello World'4243 @app.route('/', methods=['PUT'])44 def index_put():45 return 'Aha!'4647 rv = client.open('/', method='OPTIONS')48 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']495051def test_provide_automatic_options_attr():52 app = flask.Flask(__name__)5354 def index():55 return 'Hello World!'5657 index.provide_automatic_options = False58 app.route('/')(index)59 rv = app.test_client().open('/', method='OPTIONS')60 assert rv.status_code == 4056162 app = flask.Flask(__name__)6364 def index2():65 return 'Hello World!'6667 index2.provide_automatic_options = True68 app.route('/', methods=['OPTIONS'])(index2)69 rv = app.test_client().open('/', method='OPTIONS')70 assert sorted(rv.allow) == ['OPTIONS']717273def test_provide_automatic_options_kwarg(app, client):74 def index():75 return flask.request.method7677 def more():78 return flask.request.method7980 app.add_url_rule('/', view_func=index, provide_automatic_options=False)81 app.add_url_rule(82 '/more', view_func=more, methods=['GET', 'POST'],83 provide_automatic_options=False84 )85 assert client.get('/').data == b'GET'8687 rv = client.post('/')88 assert rv.status_code == 40589 assert sorted(rv.allow) == ['GET', 'HEAD']9091 # Older versions of Werkzeug.test.Client don't have an options method92 if hasattr(client, 'options'):93 rv = client.options('/')94 else:95 rv = client.open('/', method='OPTIONS')9697 assert rv.status_code == 4059899 rv = client.head('/')100 assert rv.status_code == 200101 assert not rv.data # head truncates102 assert client.post('/more').data == b'POST'103 assert client.get('/more').data == b'GET'104105 rv = client.delete('/more')106 assert rv.status_code == 405107 assert sorted(rv.allow) == ['GET', 'HEAD', 'POST']108109 if hasattr(client, 'options'):110 rv = client.options('/more')111 else:112 rv = client.open('/more', method='OPTIONS')113114 assert rv.status_code == 405115116117def test_request_dispatching(app, client):118 @app.route('/')119 def index():120 return flask.request.method121122 @app.route('/more', methods=['GET', 'POST'])123 def more():124 return flask.request.method125126 assert client.get('/').data == b'GET'127 rv = client.post('/')128 assert rv.status_code == 405129 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']130 rv = client.head('/')131 assert rv.status_code == 200132 assert not rv.data # head truncates133 assert client.post('/more').data == b'POST'134 assert client.get('/more').data == b'GET'135 rv = client.delete('/more')136 assert rv.status_code == 405137 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']138139140def test_disallow_string_for_allowed_methods(app):141 with pytest.raises(TypeError):142 @app.route('/', methods='GET POST')143 def index():144 return "Hey"145146147def test_url_mapping(app, client):148 random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"149150 def index():151 return flask.request.method152153 def more():154 return flask.request.method155156 def options():157 return random_uuid4158159 app.add_url_rule('/', 'index', index)160 app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])161162 # Issue 1288: Test that automatic options are not added when non-uppercase 'options' in methods163 app.add_url_rule('/options', 'options', options, methods=['options'])164165 assert client.get('/').data == b'GET'166 rv = client.post('/')167 assert rv.status_code == 405168 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']169 rv = client.head('/')170 assert rv.status_code == 200171 assert not rv.data # head truncates172 assert client.post('/more').data == b'POST'173 assert client.get('/more').data == b'GET'174 rv = client.delete('/more')175 assert rv.status_code == 405176 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']177 rv = client.open('/options', method='OPTIONS')178 assert rv.status_code == 200179 assert random_uuid4 in rv.data.decode("utf-8")180181182def test_werkzeug_routing(app, client):183 from werkzeug.routing import Submount, Rule184 app.url_map.add(Submount('/foo', [185 Rule('/bar', endpoint='bar'),186 Rule('/', endpoint='index')187 ]))188189 def bar():190 return 'bar'191192 def index():193 return 'index'194195 app.view_functions['bar'] = bar196 app.view_functions['index'] = index197198 assert client.get('/foo/').data == b'index'199 assert client.get('/foo/bar').data == b'bar'200201202def test_endpoint_decorator(app, client):203 from werkzeug.routing import Submount, Rule204 app.url_map.add(Submount('/foo', [205 Rule('/bar', endpoint='bar'),206 Rule('/', endpoint='index')207 ]))208209 @app.endpoint('bar')210 def bar():211 return 'bar'212213 @app.endpoint('index')214 def index():215 return 'index'216217 assert client.get('/foo/').data == b'index'218 assert client.get('/foo/bar').data == b'bar'219220221def test_session(app, client):222 app.secret_key = 'testkey'223224 @app.route('/set', methods=['POST'])225 def set():226 flask.session['value'] = flask.request.form['value']227 return 'value set'228229 @app.route('/get')230 def get():231 return flask.session['value']232233 assert client.post('/set', data={'value': '42'}).data == b'value set'234 assert client.get('/get').data == b'42'235236237def test_session_using_server_name(app, client):238 app.config.update(239 SECRET_KEY='foo',240 SERVER_NAME='example.com'241 )242243 @app.route('/')244 def index():245 flask.session['testing'] = 42246 return 'Hello World'247248 rv = client.get('/', 'http://example.com/')249 assert 'domain=.example.com' in rv.headers['set-cookie'].lower()250 assert 'httponly' in rv.headers['set-cookie'].lower()251252253def test_session_using_server_name_and_port(app, client):254 app.config.update(255 SECRET_KEY='foo',256 SERVER_NAME='example.com:8080'257 )258259 @app.route('/')260 def index():261 flask.session['testing'] = 42262 return 'Hello World'263264 rv = client.get('/', 'http://example.com:8080/')265 assert 'domain=.example.com' in rv.headers['set-cookie'].lower()266 assert 'httponly' in rv.headers['set-cookie'].lower()267268269def test_session_using_server_name_port_and_path(app, client):270 app.config.update(271 SECRET_KEY='foo',272 SERVER_NAME='example.com:8080',273 APPLICATION_ROOT='/foo'274 )275276 @app.route('/')277 def index():278 flask.session['testing'] = 42279 return 'Hello World'280281 rv = client.get('/', 'http://example.com:8080/foo')282 assert 'domain=example.com' in rv.headers['set-cookie'].lower()283 assert 'path=/foo' in rv.headers['set-cookie'].lower()284 assert 'httponly' in rv.headers['set-cookie'].lower()285286287def test_session_using_application_root(app, client):288 class PrefixPathMiddleware(object):289 def __init__(self, app, prefix):290 self.app = app291 self.prefix = prefix292293 def __call__(self, environ, start_response):294 environ['SCRIPT_NAME'] = self.prefix295 return self.app(environ, start_response)296297 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar')298 app.config.update(299 SECRET_KEY='foo',300 APPLICATION_ROOT='/bar'301 )302303 @app.route('/')304 def index():305 flask.session['testing'] = 42306 return 'Hello World'307308 rv = client.get('/', 'http://example.com:8080/')309 assert 'path=/bar' in rv.headers['set-cookie'].lower()310311312def test_session_using_session_settings(app, client):313 app.config.update(314 SECRET_KEY='foo',315 SERVER_NAME='www.example.com:8080',316 APPLICATION_ROOT='/test',317 SESSION_COOKIE_DOMAIN='.example.com',318 SESSION_COOKIE_HTTPONLY=False,319 SESSION_COOKIE_SECURE=True,320 SESSION_COOKIE_PATH='/'321 )322323 @app.route('/')324 def index():325 flask.session['testing'] = 42326 return 'Hello World'327328 rv = client.get('/', 'http://www.example.com:8080/test/')329 cookie = rv.headers['set-cookie'].lower()330 assert 'domain=.example.com' in cookie331 assert 'path=/' in cookie332 assert 'secure' in cookie333 assert 'httponly' not in cookie334335336def test_session_localhost_warning(recwarn, app, client):337 app.config.update(338 SECRET_KEY='testing',339 SERVER_NAME='localhost:5000',340 )341342 @app.route('/')343 def index():344 flask.session['testing'] = 42345 return 'testing'346347 rv = client.get('/', 'http://localhost:5000/')348 assert 'domain' not in rv.headers['set-cookie'].lower()349 w = recwarn.pop(UserWarning)350 assert '"localhost" is not a valid cookie domain' in str(w.message)351352353def test_session_ip_warning(recwarn, app, client):354 app.config.update(355 SECRET_KEY='testing',356 SERVER_NAME='127.0.0.1:5000',357 )358359 @app.route('/')360 def index():361 flask.session['testing'] = 42362 return 'testing'363364 rv = client.get('/', 'http://127.0.0.1:5000/')365 assert 'domain=127.0.0.1' in rv.headers['set-cookie'].lower()366 w = recwarn.pop(UserWarning)367 assert 'cookie domain is an IP' in str(w.message)368369370def test_missing_session():371 app = flask.Flask(__name__)372373 def expect_exception(f, *args, **kwargs):374 e = pytest.raises(RuntimeError, f, *args, **kwargs)375 assert e.value.args and 'session is unavailable' in e.value.args[0]376377 with app.test_request_context():378 assert flask.session.get('missing_key') is None379 expect_exception(flask.session.__setitem__, 'foo', 42)380 expect_exception(flask.session.pop, 'foo')381382383def test_session_expiration(app, client):384 permanent = True385 app.secret_key = 'testkey'386387 @app.route('/')388 def index():389 flask.session['test'] = 42390 flask.session.permanent = permanent391 return ''392393 @app.route('/test')394 def test():395 return text_type(flask.session.permanent)396397 rv = client.get('/')398 assert 'set-cookie' in rv.headers399 match = re.search(r'(?i)\bexpires=([^;]+)', rv.headers['set-cookie'])400 expires = parse_date(match.group())401 expected = datetime.utcnow() + app.permanent_session_lifetime402 assert expires.year == expected.year403 assert expires.month == expected.month404 assert expires.day == expected.day405406 rv = client.get('/test')407 assert rv.data == b'True'408409 permanent = False410 rv = client.get('/')411 assert 'set-cookie' in rv.headers412 match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])413 assert match is None414415416def test_session_stored_last(app, client):417 app.secret_key = 'development-key'418419 @app.after_request420 def modify_session(response):421 flask.session['foo'] = 42422 return response423424 @app.route('/')425 def dump_session_contents():426 return repr(flask.session.get('foo'))427428 assert client.get('/').data == b'None'429 assert client.get('/').data == b'42'430431432def test_session_special_types(app, client):433 app.secret_key = 'development-key'434 now = datetime.utcnow().replace(microsecond=0)435 the_uuid = uuid.uuid4()436437 @app.after_request438 def modify_session(response):439 flask.session['m'] = flask.Markup('Hello!')440 flask.session['u'] = the_uuid441 flask.session['dt'] = now442 flask.session['b'] = b'\xff'443 flask.session['t'] = (1, 2, 3)444 return response445446 @app.route('/')447 def dump_session_contents():448 return pickle.dumps(dict(flask.session))449450 client.get('/')451 rv = pickle.loads(client.get('/').data)452 assert rv['m'] == flask.Markup('Hello!')453 assert type(rv['m']) == flask.Markup454 assert rv['dt'] == now455 assert rv['u'] == the_uuid456 assert rv['b'] == b'\xff'457 assert type(rv['b']) == bytes458 assert rv['t'] == (1, 2, 3)459460461def test_session_cookie_setting(app):462 app.secret_key = 'dev key'463 is_permanent = True464465 @app.route('/bump')466 def bump():467 rv = flask.session['foo'] = flask.session.get('foo', 0) + 1468 flask.session.permanent = is_permanent469 return str(rv)470471 @app.route('/read')472 def read():473 return str(flask.session.get('foo', 0))474475 def run_test(expect_header):476 with app.test_client() as c:477 assert c.get('/bump').data == b'1'478 assert c.get('/bump').data == b'2'479 assert c.get('/bump').data == b'3'480481 rv = c.get('/read')482 set_cookie = rv.headers.get('set-cookie')483 assert (set_cookie is not None) == expect_header484 assert rv.data == b'3'485486 is_permanent = True487 app.config['SESSION_REFRESH_EACH_REQUEST'] = True488 run_test(expect_header=True)489490 is_permanent = True491 app.config['SESSION_REFRESH_EACH_REQUEST'] = False492 run_test(expect_header=False)493494 is_permanent = False495 app.config['SESSION_REFRESH_EACH_REQUEST'] = True496 run_test(expect_header=False)497498 is_permanent = False499 app.config['SESSION_REFRESH_EACH_REQUEST'] = False500 run_test(expect_header=False)501502503def test_session_vary_cookie(app, client):504 app.secret_key = 'testkey'505506 @app.route('/set')507 def set_session():508 flask.session['test'] = 'test'509 return ''510511 @app.route('/get')512 def get():513 return flask.session.get('test')514515 @app.route('/getitem')516 def getitem():517 return flask.session['test']518519 @app.route('/setdefault')520 def setdefault():521 return flask.session.setdefault('test', 'default')522523 @app.route('/no-vary-header')524 def no_vary_header():525 return ''526527 def expect(path, header=True):528 rv = client.get(path)529530 if header:531 assert rv.headers['Vary'] == 'Cookie'532 else:533 assert 'Vary' not in rv.headers534535 expect('/set')536 expect('/get')537 expect('/getitem')538 expect('/setdefault')539 expect('/no-vary-header', False)540541542def test_flashes(app, req_ctx):543 app.secret_key = 'testkey'544545 assert not flask.session.modified546 flask.flash('Zap')547 flask.session.modified = False548 flask.flash('Zip')549 assert flask.session.modified550 assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']551552553def test_extended_flashing(app):554 # Be sure app.testing=True below, else tests can fail silently.555 #556 # Specifically, if app.testing is not set to True, the AssertionErrors557 # in the view functions will cause a 500 response to the test client558 # instead of propagating exceptions.559560 app.secret_key = 'testkey'561562 @app.route('/')563 def index():564 flask.flash(u'Hello World')565 flask.flash(u'Hello World', 'error')566 flask.flash(flask.Markup(u'<em>Testing</em>'), 'warning')567 return ''568569 @app.route('/test/')570 def test():571 messages = flask.get_flashed_messages()572 assert list(messages) == [573 u'Hello World',574 u'Hello World',575 flask.Markup(u'<em>Testing</em>')576 ]577 return ''578579 @app.route('/test_with_categories/')580 def test_with_categories():581 messages = flask.get_flashed_messages(with_categories=True)582 assert len(messages) == 3583 assert list(messages) == [584 ('message', u'Hello World'),585 ('error', u'Hello World'),586 ('warning', flask.Markup(u'<em>Testing</em>'))587 ]588 return ''589590 @app.route('/test_filter/')591 def test_filter():592 messages = flask.get_flashed_messages(593 category_filter=['message'], with_categories=True)594 assert list(messages) == [('message', u'Hello World')]595 return ''596597 @app.route('/test_filters/')598 def test_filters():599 messages = flask.get_flashed_messages(600 category_filter=['message', 'warning'], with_categories=True)601 assert list(messages) == [602 ('message', u'Hello World'),603 ('warning', flask.Markup(u'<em>Testing</em>'))604 ]605 return ''606607 @app.route('/test_filters_without_returning_categories/')608 def test_filters2():609 messages = flask.get_flashed_messages(610 category_filter=['message', 'warning'])611 assert len(messages) == 2612 assert messages[0] == u'Hello World'613 assert messages[1] == flask.Markup(u'<em>Testing</em>')614 return ''615616 # Create new test client on each test to clean flashed messages.617618 client = app.test_client()619 client.get('/')620 client.get('/test_with_categories/')621622 client = app.test_client()623 client.get('/')624 client.get('/test_filter/')625626 client = app.test_client()627 client.get('/')628 client.get('/test_filters/')629630 client = app.test_client()631 client.get('/')632 client.get('/test_filters_without_returning_categories/')633634635def test_request_processing(app, client):636 evts = []637638 @app.before_request639 def before_request():640 evts.append('before')641642 @app.after_request643 def after_request(response):644 response.data += b'|after'645 evts.append('after')646 return response647648 @app.route('/')649 def index():650 assert 'before' in evts651 assert 'after' not in evts652 return 'request'653654 assert 'after' not in evts655 rv = client.get('/').data656 assert 'after' in evts657 assert rv == b'request|after'658659660def test_request_preprocessing_early_return(app, client):661 evts = []662663 @app.before_request664 def before_request1():665 evts.append(1)666667 @app.before_request668 def before_request2():669 evts.append(2)670 return "hello"671672 @app.before_request673 def before_request3():674 evts.append(3)675 return "bye"676677 @app.route('/')678 def index():679 evts.append('index')680 return "damnit"681682 rv = client.get('/').data.strip()683 assert rv == b'hello'684 assert evts == [1, 2]685686687def test_after_request_processing(app, client):688 @app.route('/')689 def index():690 @flask.after_this_request691 def foo(response):692 response.headers['X-Foo'] = 'a header'693 return response694695 return 'Test'696697 resp = client.get('/')698 assert resp.status_code == 200699 assert resp.headers['X-Foo'] == 'a header'700701702def test_teardown_request_handler(app, client):703 called = []704705 @app.teardown_request706 def teardown_request(exc):707 called.append(True)708 return "Ignored"709710 @app.route('/')711 def root():712 return "Response"713714 rv = client.get('/')715 assert rv.status_code == 200716 assert b'Response' in rv.data717 assert len(called) == 1718719720def test_teardown_request_handler_debug_mode(app, client):721 called = []722723 @app.teardown_request724 def teardown_request(exc):725 called.append(True)726 return "Ignored"727728 @app.route('/')729 def root():730 return "Response"731732 rv = client.get('/')733 assert rv.status_code == 200734 assert b'Response' in rv.data735 assert len(called) == 1736737738def test_teardown_request_handler_error(app, client):739 called = []740 app.config['LOGGER_HANDLER_POLICY'] = 'never'741 app.testing = False742743 @app.teardown_request744 def teardown_request1(exc):745 assert type(exc) == ZeroDivisionError746 called.append(True)747 # This raises a new error and blows away sys.exc_info(), so we can748 # test that all teardown_requests get passed the same original749 # exception.750 try:751 raise TypeError()752 except:753 pass754755 @app.teardown_request756 def teardown_request2(exc):757 assert type(exc) == ZeroDivisionError758 called.append(True)759 # This raises a new error and blows away sys.exc_info(), so we can760 # test that all teardown_requests get passed the same original761 # exception.762 try:763 raise TypeError()764 except:765 pass766767 @app.route('/')768 def fails():769 1 // 0770771 rv = client.get('/')772 assert rv.status_code == 500773 assert b'Internal Server Error' in rv.data774 assert len(called) == 2775776777def test_before_after_request_order(app, client):778 called = []779780 @app.before_request781 def before1():782 called.append(1)783784 @app.before_request785 def before2():786 called.append(2)787788 @app.after_request789 def after1(response):790 called.append(4)791 return response792793 @app.after_request794 def after2(response):795 called.append(3)796 return response797798 @app.teardown_request799 def finish1(exc):800 called.append(6)801802 @app.teardown_request803 def finish2(exc):804 called.append(5)805806 @app.route('/')807 def index():808 return '42'809810 rv = client.get('/')811 assert rv.data == b'42'812 assert called == [1, 2, 3, 4, 5, 6]813814815def test_error_handling(app, client):816 app.config['LOGGER_HANDLER_POLICY'] = 'never'817 app.testing = False818819 @app.errorhandler(404)820 def not_found(e):821 return 'not found', 404822823 @app.errorhandler(500)824 def internal_server_error(e):825 return 'internal server error', 500826827 @app.errorhandler(Forbidden)828 def forbidden(e):829 return 'forbidden', 403830831 @app.route('/')832 def index():833 flask.abort(404)834835 @app.route('/error')836 def error():837 1 // 0838839 @app.route('/forbidden')840 def error2():841 flask.abort(403)842843 rv = client.get('/')844 assert rv.status_code == 404845 assert rv.data == b'not found'846 rv = client.get('/error')847 assert rv.status_code == 500848 assert b'internal server error' == rv.data849 rv = client.get('/forbidden')850 assert rv.status_code == 403851 assert b'forbidden' == rv.data852853854def test_error_handling_processing(app, client):855 app.config['LOGGER_HANDLER_POLICY'] = 'never'856 app.testing = False857858 @app.errorhandler(500)859 def internal_server_error(e):860 return 'internal server error', 500861862 @app.route('/')863 def broken_func():864 1 // 0865866 @app.after_request867 def after_request(resp):868 resp.mimetype = 'text/x-special'869 return resp870871 resp = client.get('/')872 assert resp.mimetype == 'text/x-special'873 assert resp.data == b'internal server error'874875876def test_baseexception_error_handling(app, client):877 app.config['LOGGER_HANDLER_POLICY'] = 'never'878 app.testing = False879880 @app.route('/')881 def broken_func():882 raise KeyboardInterrupt()883884 with pytest.raises(KeyboardInterrupt):885 client.get('/')886887 ctx = flask._request_ctx_stack.top888 assert ctx.preserved889 assert type(ctx._preserved_exc) is KeyboardInterrupt890891892def test_before_request_and_routing_errors(app, client):893 @app.before_request894 def attach_something():895 flask.g.something = 'value'896897 @app.errorhandler(404)898 def return_something(error):899 return flask.g.something, 404900901 rv = client.get('/')902 assert rv.status_code == 404903 assert rv.data == b'value'904905906def test_user_error_handling(app, client):907 class MyException(Exception):908 pass909910 @app.errorhandler(MyException)911 def handle_my_exception(e):912 assert isinstance(e, MyException)913 return '42'914915 @app.route('/')916 def index():917 raise MyException()918919 assert client.get('/').data == b'42'920921922def test_http_error_subclass_handling(app, client):923 class ForbiddenSubclass(Forbidden):924 pass925926 @app.errorhandler(ForbiddenSubclass)927 def handle_forbidden_subclass(e):928 assert isinstance(e, ForbiddenSubclass)929 return 'banana'930931 @app.errorhandler(403)932 def handle_forbidden_subclass(e):933 assert not isinstance(e, ForbiddenSubclass)934 assert isinstance(e, Forbidden)935 return 'apple'936937 @app.route('/1')938 def index1():939 raise ForbiddenSubclass()940941 @app.route('/2')942 def index2():943 flask.abort(403)944945 @app.route('/3')946 def index3():947 raise Forbidden()948949 assert client.get('/1').data == b'banana'950 assert client.get('/2').data == b'apple'951 assert client.get('/3').data == b'apple'952953954def test_trapping_of_bad_request_key_errors(app):955 @app.route('/fail')956 def fail():957 flask.request.form['missing_key']958959 c = app.test_client()960 assert c.get('/fail').status_code == 400961962 app.config['TRAP_BAD_REQUEST_ERRORS'] = True963 c = app.test_client()964 with pytest.raises(KeyError) as e:965 c.get("/fail")966 assert e.errisinstance(BadRequest)967968969def test_trapping_of_all_http_exceptions(app, client):970 app.config['TRAP_HTTP_EXCEPTIONS'] = True971972 @app.route('/fail')973 def fail():974 flask.abort(404)975976 with pytest.raises(NotFound):977 client.get('/fail')978979980def test_enctype_debug_helper(app, client):981 from flask.debughelpers import DebugFilesKeyError982 app.debug = True983984 @app.route('/fail', methods=['POST'])985 def index():986 return flask.request.files['foo'].filename987988 # with statement is important because we leave an exception on the989 # stack otherwise and we want to ensure that this is not the case990 # to not negatively affect other tests.991 with client as c:992 with pytest.raises(DebugFilesKeyError) as e:993 c.post('/fail', data={'foo': 'index.txt'})994 assert 'no file contents were transmitted' in str(e.value)995 assert 'This was submitted: "index.txt"' in str(e.value)996997998def test_response_types():999 app = flask.Flask(__name__)1000 app.testing = True10011002 @app.route('/text')1003 def from_text():1004 return u'Hällo Wörld'10051006 @app.route('/bytes')1007 def from_bytes():1008 return u'Hällo Wörld'.encode('utf-8')10091010 @app.route('/full_tuple')1011 def from_full_tuple():1012 return 'Meh', 400, {1013 'X-Foo': 'Testing',1014 'Content-Type': 'text/plain; charset=utf-8'1015 }10161017 @app.route('/text_headers')1018 def from_text_headers():1019 return 'Hello', {1020 'X-Foo': 'Test',1021 'Content-Type': 'text/plain; charset=utf-8'1022 }10231024 @app.route('/text_status')1025 def from_text_status():1026 return 'Hi, status!', 40010271028 @app.route('/response_headers')1029 def from_response_headers():1030 return flask.Response('Hello world', 404, {'X-Foo': 'Baz'}), {1031 "X-Foo": "Bar",1032 "X-Bar": "Foo"1033 }10341035 @app.route('/response_status')1036 def from_response_status():1037 return app.response_class('Hello world', 400), 50010381039 @app.route('/wsgi')1040 def from_wsgi():1041 return NotFound()10421043 c = app.test_client()10441045 assert c.get('/text').data == u'Hällo Wörld'.encode('utf-8')1046 assert c.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')10471048 rv = c.get('/full_tuple')1049 assert rv.data == b'Meh'1050 assert rv.headers['X-Foo'] == 'Testing'1051 assert rv.status_code == 4001052 assert rv.mimetype == 'text/plain'10531054 rv = c.get('/text_headers')1055 assert rv.data == b'Hello'1056 assert rv.headers['X-Foo'] == 'Test'1057 assert rv.status_code == 2001058 assert rv.mimetype == 'text/plain'10591060 rv = c.get('/text_status')1061 assert rv.data == b'Hi, status!'1062 assert rv.status_code == 4001063 assert rv.mimetype == 'text/html'10641065 rv = c.get('/response_headers')1066 assert rv.data == b'Hello world'1067 assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar']1068 assert rv.headers['X-Bar'] == 'Foo'1069 assert rv.status_code == 40410701071 rv = c.get('/response_status')1072 assert rv.data == b'Hello world'1073 assert rv.status_code == 50010741075 rv = c.get('/wsgi')1076 assert b'Not Found' in rv.data1077 assert rv.status_code == 404107810791080def test_response_type_errors():1081 app = flask.Flask(__name__)1082 app.testing = True10831084 @app.route('/none')1085 def from_none():1086 pass10871088 @app.route('/small_tuple')1089 def from_small_tuple():1090 return 'Hello',10911092 @app.route('/large_tuple')1093 def from_large_tuple():1094 return 'Hello', 234, {'X-Foo': 'Bar'}, '???'10951096 @app.route('/bad_type')1097 def from_bad_type():1098 return True10991100 @app.route('/bad_wsgi')1101 def from_bad_wsgi():1102 return lambda: None11031104 c = app.test_client()11051106 with pytest.raises(TypeError) as e:1107 c.get('/none')1108 assert 'returned None' in str(e)11091110 with pytest.raises(TypeError) as e:1111 c.get('/small_tuple')1112 assert 'tuple must have the form' in str(e)11131114 pytest.raises(TypeError, c.get, '/large_tuple')11151116 with pytest.raises(TypeError) as e:1117 c.get('/bad_type')1118 assert 'it was a bool' in str(e)11191120 pytest.raises(TypeError, c.get, '/bad_wsgi')112111221123def test_make_response():1124 app = flask.Flask(__name__)1125 with app.test_request_context():1126 rv = flask.make_response()1127 assert rv.status_code == 2001128 assert rv.data == b''1129 assert rv.mimetype == 'text/html'11301131 rv = flask.make_response('Awesome')1132 assert rv.status_code == 2001133 assert rv.data == b'Awesome'1134 assert rv.mimetype == 'text/html'11351136 rv = flask.make_response('W00t', 404)1137 assert rv.status_code == 4041138 assert rv.data == b'W00t'1139 assert rv.mimetype == 'text/html'114011411142def test_make_response_with_response_instance():1143 app = flask.Flask(__name__)1144 with app.test_request_context():1145 rv = flask.make_response(1146 flask.jsonify({'msg': 'W00t'}), 400)1147 assert rv.status_code == 4001148 assert rv.data == b'{"msg":"W00t"}\n'1149 assert rv.mimetype == 'application/json'11501151 rv = flask.make_response(1152 flask.Response(''), 400)1153 assert rv.status_code == 4001154 assert rv.data == b''1155 assert rv.mimetype == 'text/html'11561157 rv = flask.make_response(1158 flask.Response('', headers={'Content-Type': 'text/html'}),1159 400, [('X-Foo', 'bar')])1160 assert rv.status_code == 4001161 assert rv.headers['Content-Type'] == 'text/html'1162 assert rv.headers['X-Foo'] == 'bar'116311641165def test_jsonify_no_prettyprint():1166 app = flask.Flask(__name__)1167 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1168 with app.test_request_context():1169 compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1170 uncompressed_msg = {1171 "msg": {1172 "submsg": "W00t"1173 },1174 "msg2": "foobar"1175 }11761177 rv = flask.make_response(1178 flask.jsonify(uncompressed_msg), 200)1179 assert rv.data == compressed_msg118011811182def test_jsonify_prettyprint():1183 app = flask.Flask(__name__)1184 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1185 with app.test_request_context():1186 compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1187 pretty_response = \1188 b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'11891190 rv = flask.make_response(1191 flask.jsonify(compressed_msg), 200)1192 assert rv.data == pretty_response119311941195def test_jsonify_mimetype():1196 app = flask.Flask(__name__)1197 app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'})1198 with app.test_request_context():1199 msg = {1200 "msg": {"submsg": "W00t"},1201 }1202 rv = flask.make_response(1203 flask.jsonify(msg), 200)1204 assert rv.mimetype == 'application/vnd.api+json'120512061207def test_jsonify_args_and_kwargs_check():1208 app = flask.Flask(__name__)1209 with app.test_request_context():1210 with pytest.raises(TypeError) as e:1211 flask.jsonify('fake args', kwargs='fake')1212 assert 'behavior undefined' in str(e.value)121312141215def test_url_generation():1216 app = flask.Flask(__name__)12171218 @app.route('/hello/<name>', methods=['POST'])1219 def hello():1220 pass12211222 with app.test_request_context():1223 assert flask.url_for('hello', name='test x') == '/hello/test%20x'1224 assert flask.url_for('hello', name='test x', _external=True) == \1225 'http://localhost/hello/test%20x'122612271228def test_build_error_handler():1229 app = flask.Flask(__name__)12301231 # Test base case, a URL which results in a BuildError.1232 with app.test_request_context():1233 pytest.raises(BuildError, flask.url_for, 'spam')12341235 # Verify the error is re-raised if not the current exception.1236 try:1237 with app.test_request_context():1238 flask.url_for('spam')1239 except BuildError as err:1240 error = err1241 try:1242 raise RuntimeError('Test case where BuildError is not current.')1243 except RuntimeError:1244 pytest.raises(1245 BuildError, app.handle_url_build_error, error, 'spam', {})12461247 # Test a custom handler.1248 def handler(error, endpoint, values):1249 # Just a test.1250 return '/test_handler/'12511252 app.url_build_error_handlers.append(handler)1253 with app.test_request_context():1254 assert flask.url_for('spam') == '/test_handler/'125512561257def test_build_error_handler_reraise():1258 app = flask.Flask(__name__)12591260 # Test a custom handler which reraises the BuildError1261 def handler_raises_build_error(error, endpoint, values):1262 raise error12631264 app.url_build_error_handlers.append(handler_raises_build_error)12651266 with app.test_request_context():1267 pytest.raises(BuildError, flask.url_for, 'not.existing')126812691270def test_url_for_passes_special_values_to_build_error_handler():1271 app = flask.Flask(__name__)12721273 @app.url_build_error_handlers.append1274 def handler(error, endpoint, values):1275 assert values == {1276 '_external': False,1277 '_anchor': None,1278 '_method': None,1279 '_scheme': None,1280 }1281 return 'handled'12821283 with app.test_request_context():1284 flask.url_for('/')128512861287def test_custom_converters():1288 from werkzeug.routing import BaseConverter12891290 class ListConverter(BaseConverter):1291 def to_python(self, value):1292 return value.split(',')12931294 def to_url(self, value):1295 base_to_url = super(ListConverter, self).to_url1296 return ','.join(base_to_url(x) for x in value)12971298 app = flask.Flask(__name__)1299 app.url_map.converters['list'] = ListConverter13001301 @app.route('/<list:args>')1302 def index(args):1303 return '|'.join(args)13041305 c = app.test_client()1306 assert c.get('/1,2,3').data == b'1|2|3'130713081309def test_static_files():1310 app = flask.Flask(__name__)1311 app.testing = True1312 rv = app.test_client().get('/static/index.html')1313 assert rv.status_code == 2001314 assert rv.data.strip() == b'<h1>Hello World!</h1>'1315 with app.test_request_context():1316 assert flask.url_for('static', filename='index.html') == \1317 '/static/index.html'1318 rv.close()131913201321def test_static_path_deprecated(recwarn):1322 app = flask.Flask(__name__, static_path='/foo')1323 recwarn.pop(DeprecationWarning)13241325 app.testing = True1326 rv = app.test_client().get('/foo/index.html')1327 assert rv.status_code == 2001328 rv.close()13291330 with app.test_request_context():1331 assert flask.url_for('static', filename='index.html') == '/foo/index.html'133213331334def test_static_url_path():1335 app = flask.Flask(__name__, static_url_path='/foo')1336 app.testing = True1337 rv = app.test_client().get('/foo/index.html')1338 assert rv.status_code == 2001339 rv.close()13401341 with app.test_request_context():1342 assert flask.url_for('static', filename='index.html') == '/foo/index.html'134313441345def test_static_route_with_host_matching():1346 app = flask.Flask(__name__, host_matching=True, static_host='example.com')1347 c = app.test_client()1348 rv = c.get('http://example.com/static/index.html')1349 assert rv.status_code == 2001350 rv.close()1351 with app.test_request_context():1352 rv = flask.url_for('static', filename='index.html', _external=True)1353 assert rv == 'http://example.com/static/index.html'1354 # Providing static_host without host_matching=True should error.1355 with pytest.raises(Exception):1356 flask.Flask(__name__, static_host='example.com')1357 # Providing host_matching=True with static_folder but without static_host should error.1358 with pytest.raises(Exception):1359 flask.Flask(__name__, host_matching=True)1360 # Providing host_matching=True without static_host but with static_folder=None should not error.1361 flask.Flask(__name__, host_matching=True, static_folder=None)136213631364def test_request_locals():1365 assert repr(flask.g) == '<LocalProxy unbound>'1366 assert not flask.g136713681369def test_test_app_proper_environ():1370 app = flask.Flask(__name__)1371 app.config.update(1372 SERVER_NAME='localhost.localdomain:5000'1373 )13741375 @app.route('/')1376 def index():1377 return 'Foo'13781379 @app.route('/', subdomain='foo')1380 def subdomain():1381 return 'Foo SubDomain'13821383 rv = app.test_client().get('/')1384 assert rv.data == b'Foo'13851386 rv = app.test_client().get('/', 'http://localhost.localdomain:5000')1387 assert rv.data == b'Foo'13881389 rv = app.test_client().get('/', 'https://localhost.localdomain:5000')1390 assert rv.data == b'Foo'13911392 app.config.update(SERVER_NAME='localhost.localdomain')1393 rv = app.test_client().get('/', 'https://localhost.localdomain')1394 assert rv.data == b'Foo'13951396 try:1397 app.config.update(SERVER_NAME='localhost.localdomain:443')1398 rv = app.test_client().get('/', 'https://localhost.localdomain')1399 # Werkzeug 0.81400 assert rv.status_code == 4041401 except ValueError as e:1402 # Werkzeug 0.71403 assert str(e) == (1404 "the server name provided "1405 "('localhost.localdomain:443') does not match the "1406 "server name from the WSGI environment ('localhost.localdomain')"1407 )14081409 try:1410 app.config.update(SERVER_NAME='localhost.localdomain')1411 rv = app.test_client().get('/', 'http://foo.localhost')1412 # Werkzeug 0.81413 assert rv.status_code == 4041414 except ValueError as e:1415 # Werkzeug 0.71416 assert str(e) == (1417 "the server name provided "1418 "('localhost.localdomain') does not match the "1419 "server name from the WSGI environment ('foo.localhost')"1420 )14211422 rv = app.test_client().get('/', 'http://foo.localhost.localdomain')1423 assert rv.data == b'Foo SubDomain'142414251426def test_exception_propagation():1427 def apprunner(config_key):1428 app = flask.Flask(__name__)1429 app.config['LOGGER_HANDLER_POLICY'] = 'never'14301431 @app.route('/')1432 def index():1433 1 // 014341435 c = app.test_client()1436 if config_key is not None:1437 app.config[config_key] = True1438 with pytest.raises(Exception):1439 c.get('/')1440 else:1441 assert c.get('/').status_code == 50014421443 # we have to run this test in an isolated thread because if the1444 # debug flag is set to true and an exception happens the context is1445 # not torn down. This causes other tests that run after this fail1446 # when they expect no exception on the stack.1447 for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None:1448 t = Thread(target=apprunner, args=(config_key,))1449 t.start()1450 t.join()145114521453@pytest.mark.parametrize('debug', [True, False])1454@pytest.mark.parametrize('use_debugger', [True, False])1455@pytest.mark.parametrize('use_reloader', [True, False])1456@pytest.mark.parametrize('propagate_exceptions', [None, True, False])1457def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1458 use_reloader, propagate_exceptions):1459 rv = {}14601461 # Mocks werkzeug.serving.run_simple method1462 def run_simple_mock(*args, **kwargs):1463 rv['passthrough_errors'] = kwargs.get('passthrough_errors')14641465 app = flask.Flask(__name__)1466 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1467 app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1468 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)146914701471def test_max_content_length():1472 app = flask.Flask(__name__)1473 app.config['MAX_CONTENT_LENGTH'] = 6414741475 @app.before_request1476 def always_first():1477 flask.request.form['myfile']1478 assert False14791480 @app.route('/accept', methods=['POST'])1481 def accept_file():1482 flask.request.form['myfile']1483 assert False14841485 @app.errorhandler(413)1486 def catcher(error):1487 return '42'14881489 c = app.test_client()1490 rv = c.post('/accept', data={'myfile': 'foo' * 100})1491 assert rv.data == b'42'149214931494def test_url_processors():1495 app = flask.Flask(__name__)14961497 @app.url_defaults1498 def add_language_code(endpoint, values):1499 if flask.g.lang_code is not None and \1500 app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1501 values.setdefault('lang_code', flask.g.lang_code)15021503 @app.url_value_preprocessor1504 def pull_lang_code(endpoint, values):1505 flask.g.lang_code = values.pop('lang_code', None)15061507 @app.route('/<lang_code>/')1508 def index():1509 return flask.url_for('about')15101511 @app.route('/<lang_code>/about')1512 def about():1513 return flask.url_for('something_else')15141515 @app.route('/foo')1516 def something_else():1517 return flask.url_for('about', lang_code='en')15181519 c = app.test_client()15201521 assert c.get('/de/').data == b'/de/about'1522 assert c.get('/de/about').data == b'/foo'1523 assert c.get('/foo').data == b'/en/about'152415251526def test_inject_blueprint_url_defaults():1527 app = flask.Flask(__name__)1528 bp = flask.Blueprint('foo.bar.baz', __name__,1529 template_folder='template')15301531 @bp.url_defaults1532 def bp_defaults(endpoint, values):1533 values['page'] = 'login'15341535 @bp.route('/<page>')1536 def view(page):1537 pass15381539 app.register_blueprint(bp)15401541 values = dict()1542 app.inject_url_defaults('foo.bar.baz.view', values)1543 expected = dict(page='login')1544 assert values == expected15451546 with app.test_request_context('/somepage'):1547 url = flask.url_for('foo.bar.baz.view')1548 expected = '/login'1549 assert url == expected155015511552def test_nonascii_pathinfo():1553 app = flask.Flask(__name__)1554 app.testing = True15551556 @app.route(u'/киртест')1557 def index():1558 return 'Hello World!'15591560 c = app.test_client()1561 rv = c.get(u'/киртест')1562 assert rv.data == b'Hello World!'156315641565def test_debug_mode_complains_after_first_request():1566 app = flask.Flask(__name__)1567 app.debug = True15681569 @app.route('/')1570 def index():1571 return 'Awesome'15721573 assert not app.got_first_request1574 assert app.test_client().get('/').data == b'Awesome'1575 with pytest.raises(AssertionError) as e:1576 @app.route('/foo')1577 def broken():1578 return 'Meh'1579 assert 'A setup function was called' in str(e)15801581 app.debug = False15821583 @app.route('/foo')1584 def working():1585 return 'Meh'15861587 assert app.test_client().get('/foo').data == b'Meh'1588 assert app.got_first_request158915901591def test_before_first_request_functions():1592 got = []1593 app = flask.Flask(__name__)15941595 @app.before_first_request1596 def foo():1597 got.append(42)15981599 c = app.test_client()1600 c.get('/')1601 assert got == [42]1602 c.get('/')1603 assert got == [42]1604 assert app.got_first_request160516061607def test_before_first_request_functions_concurrent():1608 got = []1609 app = flask.Flask(__name__)16101611 @app.before_first_request1612 def foo():1613 time.sleep(0.2)1614 got.append(42)16151616 c = app.test_client()16171618 def get_and_assert():1619 c.get("/")1620 assert got == [42]16211622 t = Thread(target=get_and_assert)1623 t.start()1624 get_and_assert()1625 t.join()1626 assert app.got_first_request162716281629def test_routing_redirect_debugging():1630 app = flask.Flask(__name__)1631 app.debug = True16321633 @app.route('/foo/', methods=['GET', 'POST'])1634 def foo():1635 return 'success'16361637 with app.test_client() as c:1638 with pytest.raises(AssertionError) as e:1639 c.post('/foo', data={})1640 assert 'http://localhost/foo/' in str(e)1641 assert ('Make sure to directly send '1642 'your POST-request to this URL') in str(e)16431644 rv = c.get('/foo', data={}, follow_redirects=True)1645 assert rv.data == b'success'16461647 app.debug = False1648 with app.test_client() as c:1649 rv = c.post('/foo', data={}, follow_redirects=True)1650 assert rv.data == b'success'165116521653def test_route_decorator_custom_endpoint():1654 app = flask.Flask(__name__)1655 app.debug = True16561657 @app.route('/foo/')1658 def foo():1659 return flask.request.endpoint16601661 @app.route('/bar/', endpoint='bar')1662 def for_bar():1663 return flask.request.endpoint16641665 @app.route('/bar/123', endpoint='123')1666 def for_bar_foo():1667 return flask.request.endpoint16681669 with app.test_request_context():1670 assert flask.url_for('foo') == '/foo/'1671 assert flask.url_for('bar') == '/bar/'1672 assert flask.url_for('123') == '/bar/123'16731674 c = app.test_client()1675 assert c.get('/foo/').data == b'foo'1676 assert c.get('/bar/').data == b'bar'1677 assert c.get('/bar/123').data == b'123'167816791680def test_preserve_only_once():1681 app = flask.Flask(__name__)1682 app.debug = True16831684 @app.route('/fail')1685 def fail_func():1686 1 // 016871688 c = app.test_client()1689 for x in range(3):1690 with pytest.raises(ZeroDivisionError):1691 c.get('/fail')16921693 assert flask._request_ctx_stack.top is not None1694 assert flask._app_ctx_stack.top is not None1695 # implicit appctx disappears too1696 flask._request_ctx_stack.top.pop()1697 assert flask._request_ctx_stack.top is None1698 assert flask._app_ctx_stack.top is None169917001701def test_preserve_remembers_exception(app, client):1702 app.debug = True1703 errors = []17041705 @app.route('/fail')1706 def fail_func():1707 1 // 017081709 @app.route('/success')1710 def success_func():1711 return 'Okay'17121713 @app.teardown_request1714 def teardown_handler(exc):1715 errors.append(exc)17161717 # After this failure we did not yet call the teardown handler1718 with pytest.raises(ZeroDivisionError):1719 client.get('/fail')1720 assert errors == []17211722 # But this request triggers it, and it's an error1723 client.get('/success')1724 assert len(errors) == 21725 assert isinstance(errors[0], ZeroDivisionError)17261727 # At this point another request does nothing.1728 client.get('/success')1729 assert len(errors) == 31730 assert errors[1] is None173117321733def test_get_method_on_g(app_ctx):1734 assert flask.g.get('x') is None1735 assert flask.g.get('x', 11) == 111736 flask.g.x = 421737 assert flask.g.get('x') == 421738 assert flask.g.x == 42173917401741def test_g_iteration_protocol(app_ctx):1742 flask.g.foo = 231743 flask.g.bar = 421744 assert 'foo' in flask.g1745 assert 'foos' not in flask.g1746 assert sorted(flask.g) == ['bar', 'foo']174717481749def test_subdomain_basic_support(app, client):1750 app.config['SERVER_NAME'] = 'localhost.localdomain'17511752 @app.route('/')1753 def normal_index():1754 return 'normal index'17551756 @app.route('/', subdomain='test')1757 def test_index():1758 return 'test index'17591760 rv = client.get('/', 'http://localhost.localdomain/')1761 assert rv.data == b'normal index'17621763 rv = client.get('/', 'http://test.localhost.localdomain/')1764 assert rv.data == b'test index'176517661767def test_subdomain_matching(app, client):1768 app.config['SERVER_NAME'] = 'localhost.localdomain'17691770 @app.route('/', subdomain='<user>')1771 def index(user):1772 return 'index for %s' % user17731774 rv = client.get('/', 'http://mitsuhiko.localhost.localdomain/')1775 assert rv.data == b'index for mitsuhiko'177617771778def test_subdomain_matching_with_ports(app, client):1779 app.config['SERVER_NAME'] = 'localhost.localdomain:3000'17801781 @app.route('/', subdomain='<user>')1782 def index(user):1783 return 'index for %s' % user17841785 rv = client.get('/', 'http://mitsuhiko.localhost.localdomain:3000/')1786 assert rv.data == b'index for mitsuhiko'178717881789def test_multi_route_rules(app, client):1790 @app.route('/')1791 @app.route('/<test>/')1792 def index(test='a'):1793 return test17941795 rv = client.open('/')1796 assert rv.data == b'a'1797 rv = client.open('/b/')1798 assert rv.data == b'b'179918001801def test_multi_route_class_views(app, client):1802 class View(object):1803 def __init__(self, app):1804 app.add_url_rule('/', 'index', self.index)1805 app.add_url_rule('/<test>/', 'index', self.index)18061807 def index(self, test='a'):1808 return test18091810 _ = View(app)1811 rv = client.open('/')1812 assert rv.data == b'a'1813 rv = client.open('/b/')1814 assert rv.data == b'b'181518161817def test_run_defaults(monkeypatch, app):1818 rv = {}18191820 # Mocks werkzeug.serving.run_simple method1821 def run_simple_mock(*args, **kwargs):1822 rv['result'] = 'running...'18231824 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1825 app.run()1826 assert rv['result'] == 'running...'182718281829def test_run_server_port(monkeypatch, app):1830 rv = {}18311832 # Mocks werkzeug.serving.run_simple method1833 def run_simple_mock(hostname, port, application, *args, **kwargs):1834 rv['result'] = 'running on %s:%s ...' % (hostname, port)18351836 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1837 hostname, port = 'localhost', 80001838 app.run(hostname, port, debug=True)1839 assert rv['result'] == 'running on %s:%s ...' % (hostname, port)184018411842@pytest.mark.parametrize('host,port,expect_host,expect_port', (1843 (None, None, 'pocoo.org', 8080),1844 ('localhost', None, 'localhost', 8080),1845 (None, 80, 'pocoo.org', 80),1846 ('localhost', 80, 'localhost', 80),1847))1848def test_run_from_config(monkeypatch, host, port, expect_host, expect_port, app):1849 def run_simple_mock(hostname, port, *args, **kwargs):1850 assert hostname == expect_host1851 assert port == expect_port18521853 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1854 app.config['SERVER_NAME'] = 'pocoo.org:8080'1855 app.run(host, port)