test_basic.py
This file
Path
tests/test_basic.py
1,829 lines · 48.7 KiB · Python
Last changed by
Merge pull request #2350 from davidism/errorhandlerDavid Lordbefore adoptionc7f433c
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 pickle13import re14import time15import uuid16from datetime import datetime17from threading import Thread1819import pytest20import werkzeug.serving21from werkzeug.exceptions import BadRequest, Forbidden, NotFound22from werkzeug.http import parse_date23from werkzeug.routing import BuildError2425import flask26from flask._compat import text_type272829def test_options_work(app, client):30 @app.route('/', methods=['GET', 'POST'])31 def index():32 return 'Hello World'3334 rv = client.open('/', method='OPTIONS')35 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']36 assert rv.data == b''373839def test_options_on_multiple_rules(app, client):40 @app.route('/', methods=['GET', 'POST'])41 def index():42 return 'Hello World'4344 @app.route('/', methods=['PUT'])45 def index_put():46 return 'Aha!'4748 rv = client.open('/', method='OPTIONS')49 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']505152def test_provide_automatic_options_attr():53 app = flask.Flask(__name__)5455 def index():56 return 'Hello World!'5758 index.provide_automatic_options = False59 app.route('/')(index)60 rv = app.test_client().open('/', method='OPTIONS')61 assert rv.status_code == 4056263 app = flask.Flask(__name__)6465 def index2():66 return 'Hello World!'6768 index2.provide_automatic_options = True69 app.route('/', methods=['OPTIONS'])(index2)70 rv = app.test_client().open('/', method='OPTIONS')71 assert sorted(rv.allow) == ['OPTIONS']727374def test_provide_automatic_options_kwarg(app, client):75 def index():76 return flask.request.method7778 def more():79 return flask.request.method8081 app.add_url_rule('/', view_func=index, provide_automatic_options=False)82 app.add_url_rule(83 '/more', view_func=more, methods=['GET', 'POST'],84 provide_automatic_options=False85 )86 assert client.get('/').data == b'GET'8788 rv = client.post('/')89 assert rv.status_code == 40590 assert sorted(rv.allow) == ['GET', 'HEAD']9192 # Older versions of Werkzeug.test.Client don't have an options method93 if hasattr(client, 'options'):94 rv = client.options('/')95 else:96 rv = client.open('/', method='OPTIONS')9798 assert rv.status_code == 40599100 rv = client.head('/')101 assert rv.status_code == 200102 assert not rv.data # head truncates103 assert client.post('/more').data == b'POST'104 assert client.get('/more').data == b'GET'105106 rv = client.delete('/more')107 assert rv.status_code == 405108 assert sorted(rv.allow) == ['GET', 'HEAD', 'POST']109110 if hasattr(client, 'options'):111 rv = client.options('/more')112 else:113 rv = client.open('/more', method='OPTIONS')114115 assert rv.status_code == 405116117118def test_request_dispatching(app, client):119 @app.route('/')120 def index():121 return flask.request.method122123 @app.route('/more', methods=['GET', 'POST'])124 def more():125 return flask.request.method126127 assert client.get('/').data == b'GET'128 rv = client.post('/')129 assert rv.status_code == 405130 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']131 rv = client.head('/')132 assert rv.status_code == 200133 assert not rv.data # head truncates134 assert client.post('/more').data == b'POST'135 assert client.get('/more').data == b'GET'136 rv = client.delete('/more')137 assert rv.status_code == 405138 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']139140141def test_disallow_string_for_allowed_methods(app):142 with pytest.raises(TypeError):143 @app.route('/', methods='GET POST')144 def index():145 return "Hey"146147148def test_url_mapping(app, client):149 random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"150151 def index():152 return flask.request.method153154 def more():155 return flask.request.method156157 def options():158 return random_uuid4159160 app.add_url_rule('/', 'index', index)161 app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])162163 # Issue 1288: Test that automatic options are not added when non-uppercase 'options' in methods164 app.add_url_rule('/options', 'options', options, methods=['options'])165166 assert client.get('/').data == b'GET'167 rv = client.post('/')168 assert rv.status_code == 405169 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']170 rv = client.head('/')171 assert rv.status_code == 200172 assert not rv.data # head truncates173 assert client.post('/more').data == b'POST'174 assert client.get('/more').data == b'GET'175 rv = client.delete('/more')176 assert rv.status_code == 405177 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']178 rv = client.open('/options', method='OPTIONS')179 assert rv.status_code == 200180 assert random_uuid4 in rv.data.decode("utf-8")181182183def test_werkzeug_routing(app, client):184 from werkzeug.routing import Submount, Rule185 app.url_map.add(Submount('/foo', [186 Rule('/bar', endpoint='bar'),187 Rule('/', endpoint='index')188 ]))189190 def bar():191 return 'bar'192193 def index():194 return 'index'195196 app.view_functions['bar'] = bar197 app.view_functions['index'] = index198199 assert client.get('/foo/').data == b'index'200 assert client.get('/foo/bar').data == b'bar'201202203def test_endpoint_decorator(app, client):204 from werkzeug.routing import Submount, Rule205 app.url_map.add(Submount('/foo', [206 Rule('/bar', endpoint='bar'),207 Rule('/', endpoint='index')208 ]))209210 @app.endpoint('bar')211 def bar():212 return 'bar'213214 @app.endpoint('index')215 def index():216 return 'index'217218 assert client.get('/foo/').data == b'index'219 assert client.get('/foo/bar').data == b'bar'220221222def test_session(app, client):223 app.secret_key = 'testkey'224225 @app.route('/set', methods=['POST'])226 def set():227 flask.session['value'] = flask.request.form['value']228 return 'value set'229230 @app.route('/get')231 def get():232 return flask.session['value']233234 assert client.post('/set', data={'value': '42'}).data == b'value set'235 assert client.get('/get').data == b'42'236237238def test_session_using_server_name(app, client):239 app.config.update(240 SECRET_KEY='foo',241 SERVER_NAME='example.com'242 )243244 @app.route('/')245 def index():246 flask.session['testing'] = 42247 return 'Hello World'248249 rv = client.get('/', 'http://example.com/')250 assert 'domain=.example.com' in rv.headers['set-cookie'].lower()251 assert 'httponly' in rv.headers['set-cookie'].lower()252253254def test_session_using_server_name_and_port(app, client):255 app.config.update(256 SECRET_KEY='foo',257 SERVER_NAME='example.com:8080'258 )259260 @app.route('/')261 def index():262 flask.session['testing'] = 42263 return 'Hello World'264265 rv = client.get('/', 'http://example.com:8080/')266 assert 'domain=.example.com' in rv.headers['set-cookie'].lower()267 assert 'httponly' in rv.headers['set-cookie'].lower()268269270def test_session_using_server_name_port_and_path(app, client):271 app.config.update(272 SECRET_KEY='foo',273 SERVER_NAME='example.com:8080',274 APPLICATION_ROOT='/foo'275 )276277 @app.route('/')278 def index():279 flask.session['testing'] = 42280 return 'Hello World'281282 rv = client.get('/', 'http://example.com:8080/foo')283 assert 'domain=example.com' in rv.headers['set-cookie'].lower()284 assert 'path=/foo' in rv.headers['set-cookie'].lower()285 assert 'httponly' in rv.headers['set-cookie'].lower()286287288def test_session_using_application_root(app, client):289 class PrefixPathMiddleware(object):290 def __init__(self, app, prefix):291 self.app = app292 self.prefix = prefix293294 def __call__(self, environ, start_response):295 environ['SCRIPT_NAME'] = self.prefix296 return self.app(environ, start_response)297298 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar')299 app.config.update(300 SECRET_KEY='foo',301 APPLICATION_ROOT='/bar'302 )303304 @app.route('/')305 def index():306 flask.session['testing'] = 42307 return 'Hello World'308309 rv = client.get('/', 'http://example.com:8080/')310 assert 'path=/bar' in rv.headers['set-cookie'].lower()311312313def test_session_using_session_settings(app, client):314 app.config.update(315 SECRET_KEY='foo',316 SERVER_NAME='www.example.com:8080',317 APPLICATION_ROOT='/test',318 SESSION_COOKIE_DOMAIN='.example.com',319 SESSION_COOKIE_HTTPONLY=False,320 SESSION_COOKIE_SECURE=True,321 SESSION_COOKIE_PATH='/'322 )323324 @app.route('/')325 def index():326 flask.session['testing'] = 42327 return 'Hello World'328329 rv = client.get('/', 'http://www.example.com:8080/test/')330 cookie = rv.headers['set-cookie'].lower()331 assert 'domain=.example.com' in cookie332 assert 'path=/' in cookie333 assert 'secure' in cookie334 assert 'httponly' not in cookie335336337def test_session_localhost_warning(recwarn, app, client):338 app.config.update(339 SECRET_KEY='testing',340 SERVER_NAME='localhost:5000',341 )342343 @app.route('/')344 def index():345 flask.session['testing'] = 42346 return 'testing'347348 rv = client.get('/', 'http://localhost:5000/')349 assert 'domain' not in rv.headers['set-cookie'].lower()350 w = recwarn.pop(UserWarning)351 assert '"localhost" is not a valid cookie domain' in str(w.message)352353354def test_session_ip_warning(recwarn, app, client):355 app.config.update(356 SECRET_KEY='testing',357 SERVER_NAME='127.0.0.1:5000',358 )359360 @app.route('/')361 def index():362 flask.session['testing'] = 42363 return 'testing'364365 rv = client.get('/', 'http://127.0.0.1:5000/')366 assert 'domain=127.0.0.1' in rv.headers['set-cookie'].lower()367 w = recwarn.pop(UserWarning)368 assert 'cookie domain is an IP' in str(w.message)369370371def test_missing_session():372 app = flask.Flask(__name__)373374 def expect_exception(f, *args, **kwargs):375 e = pytest.raises(RuntimeError, f, *args, **kwargs)376 assert e.value.args and 'session is unavailable' in e.value.args[0]377378 with app.test_request_context():379 assert flask.session.get('missing_key') is None380 expect_exception(flask.session.__setitem__, 'foo', 42)381 expect_exception(flask.session.pop, 'foo')382383384def test_session_expiration(app, client):385 permanent = True386 app.secret_key = 'testkey'387388 @app.route('/')389 def index():390 flask.session['test'] = 42391 flask.session.permanent = permanent392 return ''393394 @app.route('/test')395 def test():396 return text_type(flask.session.permanent)397398 rv = client.get('/')399 assert 'set-cookie' in rv.headers400 match = re.search(r'(?i)\bexpires=([^;]+)', rv.headers['set-cookie'])401 expires = parse_date(match.group())402 expected = datetime.utcnow() + app.permanent_session_lifetime403 assert expires.year == expected.year404 assert expires.month == expected.month405 assert expires.day == expected.day406407 rv = client.get('/test')408 assert rv.data == b'True'409410 permanent = False411 rv = client.get('/')412 assert 'set-cookie' in rv.headers413 match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])414 assert match is None415416417def test_session_stored_last(app, client):418 app.secret_key = 'development-key'419420 @app.after_request421 def modify_session(response):422 flask.session['foo'] = 42423 return response424425 @app.route('/')426 def dump_session_contents():427 return repr(flask.session.get('foo'))428429 assert client.get('/').data == b'None'430 assert client.get('/').data == b'42'431432433def test_session_special_types(app, client):434 app.secret_key = 'development-key'435 now = datetime.utcnow().replace(microsecond=0)436 the_uuid = uuid.uuid4()437438 @app.after_request439 def modify_session(response):440 flask.session['m'] = flask.Markup('Hello!')441 flask.session['u'] = the_uuid442 flask.session['dt'] = now443 flask.session['b'] = b'\xff'444 flask.session['t'] = (1, 2, 3)445 return response446447 @app.route('/')448 def dump_session_contents():449 return pickle.dumps(dict(flask.session))450451 client.get('/')452 rv = pickle.loads(client.get('/').data)453 assert rv['m'] == flask.Markup('Hello!')454 assert type(rv['m']) == flask.Markup455 assert rv['dt'] == now456 assert rv['u'] == the_uuid457 assert rv['b'] == b'\xff'458 assert type(rv['b']) == bytes459 assert rv['t'] == (1, 2, 3)460461462def test_session_cookie_setting(app):463 app.secret_key = 'dev key'464 is_permanent = True465466 @app.route('/bump')467 def bump():468 rv = flask.session['foo'] = flask.session.get('foo', 0) + 1469 flask.session.permanent = is_permanent470 return str(rv)471472 @app.route('/read')473 def read():474 return str(flask.session.get('foo', 0))475476 def run_test(expect_header):477 with app.test_client() as c:478 assert c.get('/bump').data == b'1'479 assert c.get('/bump').data == b'2'480 assert c.get('/bump').data == b'3'481482 rv = c.get('/read')483 set_cookie = rv.headers.get('set-cookie')484 assert (set_cookie is not None) == expect_header485 assert rv.data == b'3'486487 is_permanent = True488 app.config['SESSION_REFRESH_EACH_REQUEST'] = True489 run_test(expect_header=True)490491 is_permanent = True492 app.config['SESSION_REFRESH_EACH_REQUEST'] = False493 run_test(expect_header=False)494495 is_permanent = False496 app.config['SESSION_REFRESH_EACH_REQUEST'] = True497 run_test(expect_header=False)498499 is_permanent = False500 app.config['SESSION_REFRESH_EACH_REQUEST'] = False501 run_test(expect_header=False)502503504def test_session_vary_cookie(app, client):505 app.secret_key = 'testkey'506507 @app.route('/set')508 def set_session():509 flask.session['test'] = 'test'510 return ''511512 @app.route('/get')513 def get():514 return flask.session.get('test')515516 @app.route('/getitem')517 def getitem():518 return flask.session['test']519520 @app.route('/setdefault')521 def setdefault():522 return flask.session.setdefault('test', 'default')523524 @app.route('/vary-cookie-header-set')525 def vary_cookie_header_set():526 response = flask.Response()527 response.vary.add('Cookie')528 flask.session['test'] = 'test'529 return response530531 @app.route('/vary-header-set')532 def vary_header_set():533 response = flask.Response()534 response.vary.update(('Accept-Encoding', 'Accept-Language'))535 flask.session['test'] = 'test'536 return response537538 @app.route('/no-vary-header')539 def no_vary_header():540 return ''541542 def expect(path, header_value='Cookie'):543 rv = client.get(path)544545 if header_value:546 # The 'Vary' key should exist in the headers only once.547 assert len(rv.headers.get_all('Vary')) == 1548 assert rv.headers['Vary'] == header_value549 else:550 assert 'Vary' not in rv.headers551552 expect('/set')553 expect('/get')554 expect('/getitem')555 expect('/setdefault')556 expect('/vary-cookie-header-set')557 expect('/vary-header-set', 'Accept-Encoding, Accept-Language, Cookie')558 expect('/no-vary-header', None)559560561def test_flashes(app, req_ctx):562 app.secret_key = 'testkey'563564 assert not flask.session.modified565 flask.flash('Zap')566 flask.session.modified = False567 flask.flash('Zip')568 assert flask.session.modified569 assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']570571572def test_extended_flashing(app):573 # Be sure app.testing=True below, else tests can fail silently.574 #575 # Specifically, if app.testing is not set to True, the AssertionErrors576 # in the view functions will cause a 500 response to the test client577 # instead of propagating exceptions.578579 app.secret_key = 'testkey'580581 @app.route('/')582 def index():583 flask.flash(u'Hello World')584 flask.flash(u'Hello World', 'error')585 flask.flash(flask.Markup(u'<em>Testing</em>'), 'warning')586 return ''587588 @app.route('/test/')589 def test():590 messages = flask.get_flashed_messages()591 assert list(messages) == [592 u'Hello World',593 u'Hello World',594 flask.Markup(u'<em>Testing</em>')595 ]596 return ''597598 @app.route('/test_with_categories/')599 def test_with_categories():600 messages = flask.get_flashed_messages(with_categories=True)601 assert len(messages) == 3602 assert list(messages) == [603 ('message', u'Hello World'),604 ('error', u'Hello World'),605 ('warning', flask.Markup(u'<em>Testing</em>'))606 ]607 return ''608609 @app.route('/test_filter/')610 def test_filter():611 messages = flask.get_flashed_messages(612 category_filter=['message'], with_categories=True)613 assert list(messages) == [('message', u'Hello World')]614 return ''615616 @app.route('/test_filters/')617 def test_filters():618 messages = flask.get_flashed_messages(619 category_filter=['message', 'warning'], with_categories=True)620 assert list(messages) == [621 ('message', u'Hello World'),622 ('warning', flask.Markup(u'<em>Testing</em>'))623 ]624 return ''625626 @app.route('/test_filters_without_returning_categories/')627 def test_filters2():628 messages = flask.get_flashed_messages(629 category_filter=['message', 'warning'])630 assert len(messages) == 2631 assert messages[0] == u'Hello World'632 assert messages[1] == flask.Markup(u'<em>Testing</em>')633 return ''634635 # Create new test client on each test to clean flashed messages.636637 client = app.test_client()638 client.get('/')639 client.get('/test_with_categories/')640641 client = app.test_client()642 client.get('/')643 client.get('/test_filter/')644645 client = app.test_client()646 client.get('/')647 client.get('/test_filters/')648649 client = app.test_client()650 client.get('/')651 client.get('/test_filters_without_returning_categories/')652653654def test_request_processing(app, client):655 evts = []656657 @app.before_request658 def before_request():659 evts.append('before')660661 @app.after_request662 def after_request(response):663 response.data += b'|after'664 evts.append('after')665 return response666667 @app.route('/')668 def index():669 assert 'before' in evts670 assert 'after' not in evts671 return 'request'672673 assert 'after' not in evts674 rv = client.get('/').data675 assert 'after' in evts676 assert rv == b'request|after'677678679def test_request_preprocessing_early_return(app, client):680 evts = []681682 @app.before_request683 def before_request1():684 evts.append(1)685686 @app.before_request687 def before_request2():688 evts.append(2)689 return "hello"690691 @app.before_request692 def before_request3():693 evts.append(3)694 return "bye"695696 @app.route('/')697 def index():698 evts.append('index')699 return "damnit"700701 rv = client.get('/').data.strip()702 assert rv == b'hello'703 assert evts == [1, 2]704705706def test_after_request_processing(app, client):707 @app.route('/')708 def index():709 @flask.after_this_request710 def foo(response):711 response.headers['X-Foo'] = 'a header'712 return response713714 return 'Test'715716 resp = client.get('/')717 assert resp.status_code == 200718 assert resp.headers['X-Foo'] == 'a header'719720721def test_teardown_request_handler(app, client):722 called = []723724 @app.teardown_request725 def teardown_request(exc):726 called.append(True)727 return "Ignored"728729 @app.route('/')730 def root():731 return "Response"732733 rv = client.get('/')734 assert rv.status_code == 200735 assert b'Response' in rv.data736 assert len(called) == 1737738739def test_teardown_request_handler_debug_mode(app, client):740 called = []741742 @app.teardown_request743 def teardown_request(exc):744 called.append(True)745 return "Ignored"746747 @app.route('/')748 def root():749 return "Response"750751 rv = client.get('/')752 assert rv.status_code == 200753 assert b'Response' in rv.data754 assert len(called) == 1755756757def test_teardown_request_handler_error(app, client):758 called = []759 app.config['LOGGER_HANDLER_POLICY'] = 'never'760 app.testing = False761762 @app.teardown_request763 def teardown_request1(exc):764 assert type(exc) == ZeroDivisionError765 called.append(True)766 # This raises a new error and blows away sys.exc_info(), so we can767 # test that all teardown_requests get passed the same original768 # exception.769 try:770 raise TypeError()771 except:772 pass773774 @app.teardown_request775 def teardown_request2(exc):776 assert type(exc) == ZeroDivisionError777 called.append(True)778 # This raises a new error and blows away sys.exc_info(), so we can779 # test that all teardown_requests get passed the same original780 # exception.781 try:782 raise TypeError()783 except:784 pass785786 @app.route('/')787 def fails():788 1 // 0789790 rv = client.get('/')791 assert rv.status_code == 500792 assert b'Internal Server Error' in rv.data793 assert len(called) == 2794795796def test_before_after_request_order(app, client):797 called = []798799 @app.before_request800 def before1():801 called.append(1)802803 @app.before_request804 def before2():805 called.append(2)806807 @app.after_request808 def after1(response):809 called.append(4)810 return response811812 @app.after_request813 def after2(response):814 called.append(3)815 return response816817 @app.teardown_request818 def finish1(exc):819 called.append(6)820821 @app.teardown_request822 def finish2(exc):823 called.append(5)824825 @app.route('/')826 def index():827 return '42'828829 rv = client.get('/')830 assert rv.data == b'42'831 assert called == [1, 2, 3, 4, 5, 6]832833834def test_error_handling(app, client):835 app.config['LOGGER_HANDLER_POLICY'] = 'never'836 app.testing = False837838 @app.errorhandler(404)839 def not_found(e):840 return 'not found', 404841842 @app.errorhandler(500)843 def internal_server_error(e):844 return 'internal server error', 500845846 @app.errorhandler(Forbidden)847 def forbidden(e):848 return 'forbidden', 403849850 @app.route('/')851 def index():852 flask.abort(404)853854 @app.route('/error')855 def error():856 1 // 0857858 @app.route('/forbidden')859 def error2():860 flask.abort(403)861862 rv = client.get('/')863 assert rv.status_code == 404864 assert rv.data == b'not found'865 rv = client.get('/error')866 assert rv.status_code == 500867 assert b'internal server error' == rv.data868 rv = client.get('/forbidden')869 assert rv.status_code == 403870 assert b'forbidden' == rv.data871872873def test_error_handler_unknown_code(app):874 with pytest.raises(KeyError) as exc_info:875 app.register_error_handler(999, lambda e: ('999', 999))876877 assert 'Use a subclass' in exc_info.value.args[0]878879880def test_error_handling_processing(app, client):881 app.config['LOGGER_HANDLER_POLICY'] = 'never'882 app.testing = False883884 @app.errorhandler(500)885 def internal_server_error(e):886 return 'internal server error', 500887888 @app.route('/')889 def broken_func():890 1 // 0891892 @app.after_request893 def after_request(resp):894 resp.mimetype = 'text/x-special'895 return resp896897 resp = client.get('/')898 assert resp.mimetype == 'text/x-special'899 assert resp.data == b'internal server error'900901902def test_baseexception_error_handling(app, client):903 app.config['LOGGER_HANDLER_POLICY'] = 'never'904 app.testing = False905906 @app.route('/')907 def broken_func():908 raise KeyboardInterrupt()909910 with pytest.raises(KeyboardInterrupt):911 client.get('/')912913 ctx = flask._request_ctx_stack.top914 assert ctx.preserved915 assert type(ctx._preserved_exc) is KeyboardInterrupt916917918def test_before_request_and_routing_errors(app, client):919 @app.before_request920 def attach_something():921 flask.g.something = 'value'922923 @app.errorhandler(404)924 def return_something(error):925 return flask.g.something, 404926927 rv = client.get('/')928 assert rv.status_code == 404929 assert rv.data == b'value'930931932def test_user_error_handling(app, client):933 class MyException(Exception):934 pass935936 @app.errorhandler(MyException)937 def handle_my_exception(e):938 assert isinstance(e, MyException)939 return '42'940941 @app.route('/')942 def index():943 raise MyException()944945 assert client.get('/').data == b'42'946947948def test_http_error_subclass_handling(app, client):949 class ForbiddenSubclass(Forbidden):950 pass951952 @app.errorhandler(ForbiddenSubclass)953 def handle_forbidden_subclass(e):954 assert isinstance(e, ForbiddenSubclass)955 return 'banana'956957 @app.errorhandler(403)958 def handle_forbidden_subclass(e):959 assert not isinstance(e, ForbiddenSubclass)960 assert isinstance(e, Forbidden)961 return 'apple'962963 @app.route('/1')964 def index1():965 raise ForbiddenSubclass()966967 @app.route('/2')968 def index2():969 flask.abort(403)970971 @app.route('/3')972 def index3():973 raise Forbidden()974975 assert client.get('/1').data == b'banana'976 assert client.get('/2').data == b'apple'977 assert client.get('/3').data == b'apple'978979980def test_trapping_of_bad_request_key_errors(app, client):981 @app.route('/fail')982 def fail():983 flask.request.form['missing_key']984985 rv = client.get('/fail')986 assert rv.status_code == 400987 assert b'missing_key' not in rv.data988989 app.config['TRAP_BAD_REQUEST_ERRORS'] = True990991 with pytest.raises(KeyError) as e:992 client.get("/fail")993994 assert e.errisinstance(BadRequest)995 assert 'missing_key' in e.value.description996997998def test_trapping_of_all_http_exceptions(app, client):999 app.config['TRAP_HTTP_EXCEPTIONS'] = True10001001 @app.route('/fail')1002 def fail():1003 flask.abort(404)10041005 with pytest.raises(NotFound):1006 client.get('/fail')100710081009def test_enctype_debug_helper(app, client):1010 from flask.debughelpers import DebugFilesKeyError1011 app.debug = True10121013 @app.route('/fail', methods=['POST'])1014 def index():1015 return flask.request.files['foo'].filename10161017 # with statement is important because we leave an exception on the1018 # stack otherwise and we want to ensure that this is not the case1019 # to not negatively affect other tests.1020 with client:1021 with pytest.raises(DebugFilesKeyError) as e:1022 client.post('/fail', data={'foo': 'index.txt'})1023 assert 'no file contents were transmitted' in str(e.value)1024 assert 'This was submitted: "index.txt"' in str(e.value)102510261027def test_response_types(app, client):1028 @app.route('/text')1029 def from_text():1030 return u'Hällo Wörld'10311032 @app.route('/bytes')1033 def from_bytes():1034 return u'Hällo Wörld'.encode('utf-8')10351036 @app.route('/full_tuple')1037 def from_full_tuple():1038 return 'Meh', 400, {1039 'X-Foo': 'Testing',1040 'Content-Type': 'text/plain; charset=utf-8'1041 }10421043 @app.route('/text_headers')1044 def from_text_headers():1045 return 'Hello', {1046 'X-Foo': 'Test',1047 'Content-Type': 'text/plain; charset=utf-8'1048 }10491050 @app.route('/text_status')1051 def from_text_status():1052 return 'Hi, status!', 40010531054 @app.route('/response_headers')1055 def from_response_headers():1056 return flask.Response('Hello world', 404, {'X-Foo': 'Baz'}), {1057 "X-Foo": "Bar",1058 "X-Bar": "Foo"1059 }10601061 @app.route('/response_status')1062 def from_response_status():1063 return app.response_class('Hello world', 400), 50010641065 @app.route('/wsgi')1066 def from_wsgi():1067 return NotFound()10681069 assert client.get('/text').data == u'Hällo Wörld'.encode('utf-8')1070 assert client.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')10711072 rv = client.get('/full_tuple')1073 assert rv.data == b'Meh'1074 assert rv.headers['X-Foo'] == 'Testing'1075 assert rv.status_code == 4001076 assert rv.mimetype == 'text/plain'10771078 rv = client.get('/text_headers')1079 assert rv.data == b'Hello'1080 assert rv.headers['X-Foo'] == 'Test'1081 assert rv.status_code == 2001082 assert rv.mimetype == 'text/plain'10831084 rv = client.get('/text_status')1085 assert rv.data == b'Hi, status!'1086 assert rv.status_code == 4001087 assert rv.mimetype == 'text/html'10881089 rv = client.get('/response_headers')1090 assert rv.data == b'Hello world'1091 assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar']1092 assert rv.headers['X-Bar'] == 'Foo'1093 assert rv.status_code == 40410941095 rv = client.get('/response_status')1096 assert rv.data == b'Hello world'1097 assert rv.status_code == 50010981099 rv = client.get('/wsgi')1100 assert b'Not Found' in rv.data1101 assert rv.status_code == 404110211031104def test_response_type_errors():1105 app = flask.Flask(__name__)1106 app.testing = True11071108 @app.route('/none')1109 def from_none():1110 pass11111112 @app.route('/small_tuple')1113 def from_small_tuple():1114 return 'Hello',11151116 @app.route('/large_tuple')1117 def from_large_tuple():1118 return 'Hello', 234, {'X-Foo': 'Bar'}, '???'11191120 @app.route('/bad_type')1121 def from_bad_type():1122 return True11231124 @app.route('/bad_wsgi')1125 def from_bad_wsgi():1126 return lambda: None11271128 c = app.test_client()11291130 with pytest.raises(TypeError) as e:1131 c.get('/none')1132 assert 'returned None' in str(e)11331134 with pytest.raises(TypeError) as e:1135 c.get('/small_tuple')1136 assert 'tuple must have the form' in str(e)11371138 pytest.raises(TypeError, c.get, '/large_tuple')11391140 with pytest.raises(TypeError) as e:1141 c.get('/bad_type')1142 assert 'it was a bool' in str(e)11431144 pytest.raises(TypeError, c.get, '/bad_wsgi')114511461147def test_make_response(app, req_ctx):1148 rv = flask.make_response()1149 assert rv.status_code == 2001150 assert rv.data == b''1151 assert rv.mimetype == 'text/html'11521153 rv = flask.make_response('Awesome')1154 assert rv.status_code == 2001155 assert rv.data == b'Awesome'1156 assert rv.mimetype == 'text/html'11571158 rv = flask.make_response('W00t', 404)1159 assert rv.status_code == 4041160 assert rv.data == b'W00t'1161 assert rv.mimetype == 'text/html'116211631164def test_make_response_with_response_instance(app, req_ctx):1165 rv = flask.make_response(1166 flask.jsonify({'msg': 'W00t'}), 400)1167 assert rv.status_code == 4001168 assert rv.data == b'{"msg":"W00t"}\n'1169 assert rv.mimetype == 'application/json'11701171 rv = flask.make_response(1172 flask.Response(''), 400)1173 assert rv.status_code == 4001174 assert rv.data == b''1175 assert rv.mimetype == 'text/html'11761177 rv = flask.make_response(1178 flask.Response('', headers={'Content-Type': 'text/html'}),1179 400, [('X-Foo', 'bar')])1180 assert rv.status_code == 4001181 assert rv.headers['Content-Type'] == 'text/html'1182 assert rv.headers['X-Foo'] == 'bar'118311841185def test_jsonify_no_prettyprint(app, req_ctx):1186 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1187 compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1188 uncompressed_msg = {1189 "msg": {1190 "submsg": "W00t"1191 },1192 "msg2": "foobar"1193 }11941195 rv = flask.make_response(1196 flask.jsonify(uncompressed_msg), 200)1197 assert rv.data == compressed_msg119811991200def test_jsonify_prettyprint(app, req_ctx):1201 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1202 compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1203 pretty_response = \1204 b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'12051206 rv = flask.make_response(1207 flask.jsonify(compressed_msg), 200)1208 assert rv.data == pretty_response120912101211def test_jsonify_mimetype(app, req_ctx):1212 app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'})1213 msg = {1214 "msg": {"submsg": "W00t"},1215 }1216 rv = flask.make_response(1217 flask.jsonify(msg), 200)1218 assert rv.mimetype == 'application/vnd.api+json'121912201221def test_jsonify_args_and_kwargs_check(app, req_ctx):1222 with pytest.raises(TypeError) as e:1223 flask.jsonify('fake args', kwargs='fake')1224 assert 'behavior undefined' in str(e.value)122512261227def test_url_generation(app, req_ctx):1228 @app.route('/hello/<name>', methods=['POST'])1229 def hello():1230 pass12311232 assert flask.url_for('hello', name='test x') == '/hello/test%20x'1233 assert flask.url_for('hello', name='test x', _external=True) == \1234 'http://localhost/hello/test%20x'123512361237def test_build_error_handler(app):1238 # Test base case, a URL which results in a BuildError.1239 with app.test_request_context():1240 pytest.raises(BuildError, flask.url_for, 'spam')12411242 # Verify the error is re-raised if not the current exception.1243 try:1244 with app.test_request_context():1245 flask.url_for('spam')1246 except BuildError as err:1247 error = err1248 try:1249 raise RuntimeError('Test case where BuildError is not current.')1250 except RuntimeError:1251 pytest.raises(1252 BuildError, app.handle_url_build_error, error, 'spam', {})12531254 # Test a custom handler.1255 def handler(error, endpoint, values):1256 # Just a test.1257 return '/test_handler/'12581259 app.url_build_error_handlers.append(handler)1260 with app.test_request_context():1261 assert flask.url_for('spam') == '/test_handler/'126212631264def test_build_error_handler_reraise(app):1265 # Test a custom handler which reraises the BuildError1266 def handler_raises_build_error(error, endpoint, values):1267 raise error12681269 app.url_build_error_handlers.append(handler_raises_build_error)12701271 with app.test_request_context():1272 pytest.raises(BuildError, flask.url_for, 'not.existing')127312741275def test_url_for_passes_special_values_to_build_error_handler(app):1276 @app.url_build_error_handlers.append1277 def handler(error, endpoint, values):1278 assert values == {1279 '_external': False,1280 '_anchor': None,1281 '_method': None,1282 '_scheme': None,1283 }1284 return 'handled'12851286 with app.test_request_context():1287 flask.url_for('/')128812891290def test_custom_converters(app, client):1291 from werkzeug.routing import BaseConverter12921293 class ListConverter(BaseConverter):1294 def to_python(self, value):1295 return value.split(',')12961297 def to_url(self, value):1298 base_to_url = super(ListConverter, self).to_url1299 return ','.join(base_to_url(x) for x in value)13001301 app.url_map.converters['list'] = ListConverter13021303 @app.route('/<list:args>')1304 def index(args):1305 return '|'.join(args)13061307 assert client.get('/1,2,3').data == b'1|2|3'130813091310def test_static_files(app, client):1311 rv = client.get('/static/index.html')1312 assert rv.status_code == 2001313 assert rv.data.strip() == b'<h1>Hello World!</h1>'1314 with app.test_request_context():1315 assert flask.url_for('static', filename='index.html') == \1316 '/static/index.html'1317 rv.close()131813191320def test_static_path_deprecated(recwarn):1321 app = flask.Flask(__name__, static_path='/foo')1322 recwarn.pop(DeprecationWarning)13231324 app.testing = True1325 rv = app.test_client().get('/foo/index.html')1326 assert rv.status_code == 2001327 rv.close()13281329 with app.test_request_context():1330 assert flask.url_for('static', filename='index.html') == '/foo/index.html'133113321333def test_static_url_path():1334 app = flask.Flask(__name__, static_url_path='/foo')1335 app.testing = True1336 rv = app.test_client().get('/foo/index.html')1337 assert rv.status_code == 2001338 rv.close()13391340 with app.test_request_context():1341 assert flask.url_for('static', filename='index.html') == '/foo/index.html'134213431344def test_static_route_with_host_matching():1345 app = flask.Flask(__name__, host_matching=True, static_host='example.com')1346 c = app.test_client()1347 rv = c.get('http://example.com/static/index.html')1348 assert rv.status_code == 2001349 rv.close()1350 with app.test_request_context():1351 rv = flask.url_for('static', filename='index.html', _external=True)1352 assert rv == 'http://example.com/static/index.html'1353 # Providing static_host without host_matching=True should error.1354 with pytest.raises(Exception):1355 flask.Flask(__name__, static_host='example.com')1356 # Providing host_matching=True with static_folder but without static_host should error.1357 with pytest.raises(Exception):1358 flask.Flask(__name__, host_matching=True)1359 # Providing host_matching=True without static_host but with static_folder=None should not error.1360 flask.Flask(__name__, host_matching=True, static_folder=None)136113621363def test_request_locals():1364 assert repr(flask.g) == '<LocalProxy unbound>'1365 assert not flask.g136613671368def test_test_app_proper_environ(app, client):1369 app.config.update(1370 SERVER_NAME='localhost.localdomain:5000'1371 )13721373 @app.route('/')1374 def index():1375 return 'Foo'13761377 @app.route('/', subdomain='foo')1378 def subdomain():1379 return 'Foo SubDomain'13801381 rv = client.get('/')1382 assert rv.data == b'Foo'13831384 rv = client.get('/', 'http://localhost.localdomain:5000')1385 assert rv.data == b'Foo'13861387 rv = client.get('/', 'https://localhost.localdomain:5000')1388 assert rv.data == b'Foo'13891390 app.config.update(SERVER_NAME='localhost.localdomain')1391 rv = client.get('/', 'https://localhost.localdomain')1392 assert rv.data == b'Foo'13931394 try:1395 app.config.update(SERVER_NAME='localhost.localdomain:443')1396 rv = client.get('/', 'https://localhost.localdomain')1397 # Werkzeug 0.81398 assert rv.status_code == 4041399 except ValueError as e:1400 # Werkzeug 0.71401 assert str(e) == (1402 "the server name provided "1403 "('localhost.localdomain:443') does not match the "1404 "server name from the WSGI environment ('localhost.localdomain')"1405 )14061407 try:1408 app.config.update(SERVER_NAME='localhost.localdomain')1409 rv = client.get('/', 'http://foo.localhost')1410 # Werkzeug 0.81411 assert rv.status_code == 4041412 except ValueError as e:1413 # Werkzeug 0.71414 assert str(e) == (1415 "the server name provided "1416 "('localhost.localdomain') does not match the "1417 "server name from the WSGI environment ('foo.localhost')"1418 )14191420 rv = client.get('/', 'http://foo.localhost.localdomain')1421 assert rv.data == b'Foo SubDomain'142214231424def test_exception_propagation(app, client):1425 def apprunner(config_key):1426 app.config['LOGGER_HANDLER_POLICY'] = 'never'14271428 @app.route('/')1429 def index():1430 1 // 014311432 if config_key is not None:1433 app.config[config_key] = True1434 with pytest.raises(Exception):1435 client.get('/')1436 else:1437 assert client.get('/').status_code == 50014381439 # we have to run this test in an isolated thread because if the1440 # debug flag is set to true and an exception happens the context is1441 # not torn down. This causes other tests that run after this fail1442 # when they expect no exception on the stack.1443 for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None:1444 t = Thread(target=apprunner, args=(config_key,))1445 t.start()1446 t.join()144714481449@pytest.mark.parametrize('debug', [True, False])1450@pytest.mark.parametrize('use_debugger', [True, False])1451@pytest.mark.parametrize('use_reloader', [True, False])1452@pytest.mark.parametrize('propagate_exceptions', [None, True, False])1453def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1454 use_reloader, propagate_exceptions, app):1455 rv = {}14561457 # Mocks werkzeug.serving.run_simple method1458 def run_simple_mock(*args, **kwargs):1459 rv['passthrough_errors'] = kwargs.get('passthrough_errors')14601461 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1462 app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1463 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)146414651466def test_max_content_length(app, client):1467 app.config['MAX_CONTENT_LENGTH'] = 6414681469 @app.before_request1470 def always_first():1471 flask.request.form['myfile']1472 assert False14731474 @app.route('/accept', methods=['POST'])1475 def accept_file():1476 flask.request.form['myfile']1477 assert False14781479 @app.errorhandler(413)1480 def catcher(error):1481 return '42'14821483 rv = client.post('/accept', data={'myfile': 'foo' * 100})1484 assert rv.data == b'42'148514861487def test_url_processors(app, client):14881489 @app.url_defaults1490 def add_language_code(endpoint, values):1491 if flask.g.lang_code is not None and \1492 app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1493 values.setdefault('lang_code', flask.g.lang_code)14941495 @app.url_value_preprocessor1496 def pull_lang_code(endpoint, values):1497 flask.g.lang_code = values.pop('lang_code', None)14981499 @app.route('/<lang_code>/')1500 def index():1501 return flask.url_for('about')15021503 @app.route('/<lang_code>/about')1504 def about():1505 return flask.url_for('something_else')15061507 @app.route('/foo')1508 def something_else():1509 return flask.url_for('about', lang_code='en')15101511 assert client.get('/de/').data == b'/de/about'1512 assert client.get('/de/about').data == b'/foo'1513 assert client.get('/foo').data == b'/en/about'151415151516def test_inject_blueprint_url_defaults(app):1517 bp = flask.Blueprint('foo.bar.baz', __name__,1518 template_folder='template')15191520 @bp.url_defaults1521 def bp_defaults(endpoint, values):1522 values['page'] = 'login'15231524 @bp.route('/<page>')1525 def view(page):1526 pass15271528 app.register_blueprint(bp)15291530 values = dict()1531 app.inject_url_defaults('foo.bar.baz.view', values)1532 expected = dict(page='login')1533 assert values == expected15341535 with app.test_request_context('/somepage'):1536 url = flask.url_for('foo.bar.baz.view')1537 expected = '/login'1538 assert url == expected153915401541def test_nonascii_pathinfo(app, client):1542 @app.route(u'/киртест')1543 def index():1544 return 'Hello World!'15451546 rv = client.get(u'/киртест')1547 assert rv.data == b'Hello World!'154815491550def test_debug_mode_complains_after_first_request(app, client):1551 app.debug = True15521553 @app.route('/')1554 def index():1555 return 'Awesome'15561557 assert not app.got_first_request1558 assert client.get('/').data == b'Awesome'1559 with pytest.raises(AssertionError) as e:1560 @app.route('/foo')1561 def broken():1562 return 'Meh'1563 assert 'A setup function was called' in str(e)15641565 app.debug = False15661567 @app.route('/foo')1568 def working():1569 return 'Meh'15701571 assert client.get('/foo').data == b'Meh'1572 assert app.got_first_request157315741575def test_before_first_request_functions(app, client):1576 got = []15771578 @app.before_first_request1579 def foo():1580 got.append(42)15811582 client.get('/')1583 assert got == [42]1584 client.get('/')1585 assert got == [42]1586 assert app.got_first_request158715881589def test_before_first_request_functions_concurrent(app, client):1590 got = []15911592 @app.before_first_request1593 def foo():1594 time.sleep(0.2)1595 got.append(42)15961597 def get_and_assert():1598 client.get("/")1599 assert got == [42]16001601 t = Thread(target=get_and_assert)1602 t.start()1603 get_and_assert()1604 t.join()1605 assert app.got_first_request160616071608def test_routing_redirect_debugging(app, client):1609 app.debug = True16101611 @app.route('/foo/', methods=['GET', 'POST'])1612 def foo():1613 return 'success'16141615 with client:1616 with pytest.raises(AssertionError) as e:1617 client.post('/foo', data={})1618 assert 'http://localhost/foo/' in str(e)1619 assert ('Make sure to directly send '1620 'your POST-request to this URL') in str(e)16211622 rv = client.get('/foo', data={}, follow_redirects=True)1623 assert rv.data == b'success'16241625 app.debug = False1626 with client:1627 rv = client.post('/foo', data={}, follow_redirects=True)1628 assert rv.data == b'success'162916301631def test_route_decorator_custom_endpoint(app, client):1632 app.debug = True16331634 @app.route('/foo/')1635 def foo():1636 return flask.request.endpoint16371638 @app.route('/bar/', endpoint='bar')1639 def for_bar():1640 return flask.request.endpoint16411642 @app.route('/bar/123', endpoint='123')1643 def for_bar_foo():1644 return flask.request.endpoint16451646 with app.test_request_context():1647 assert flask.url_for('foo') == '/foo/'1648 assert flask.url_for('bar') == '/bar/'1649 assert flask.url_for('123') == '/bar/123'16501651 assert client.get('/foo/').data == b'foo'1652 assert client.get('/bar/').data == b'bar'1653 assert client.get('/bar/123').data == b'123'165416551656def test_preserve_only_once(app, client):1657 app.debug = True16581659 @app.route('/fail')1660 def fail_func():1661 1 // 016621663 for x in range(3):1664 with pytest.raises(ZeroDivisionError):1665 client.get('/fail')16661667 assert flask._request_ctx_stack.top is not None1668 assert flask._app_ctx_stack.top is not None1669 # implicit appctx disappears too1670 flask._request_ctx_stack.top.pop()1671 assert flask._request_ctx_stack.top is None1672 assert flask._app_ctx_stack.top is None167316741675def test_preserve_remembers_exception(app, client):1676 app.debug = True1677 errors = []16781679 @app.route('/fail')1680 def fail_func():1681 1 // 016821683 @app.route('/success')1684 def success_func():1685 return 'Okay'16861687 @app.teardown_request1688 def teardown_handler(exc):1689 errors.append(exc)16901691 # After this failure we did not yet call the teardown handler1692 with pytest.raises(ZeroDivisionError):1693 client.get('/fail')1694 assert errors == []16951696 # But this request triggers it, and it's an error1697 client.get('/success')1698 assert len(errors) == 21699 assert isinstance(errors[0], ZeroDivisionError)17001701 # At this point another request does nothing.1702 client.get('/success')1703 assert len(errors) == 31704 assert errors[1] is None170517061707def test_get_method_on_g(app_ctx):1708 assert flask.g.get('x') is None1709 assert flask.g.get('x', 11) == 111710 flask.g.x = 421711 assert flask.g.get('x') == 421712 assert flask.g.x == 42171317141715def test_g_iteration_protocol(app_ctx):1716 flask.g.foo = 231717 flask.g.bar = 421718 assert 'foo' in flask.g1719 assert 'foos' not in flask.g1720 assert sorted(flask.g) == ['bar', 'foo']172117221723def test_subdomain_basic_support(app, client):1724 app.config['SERVER_NAME'] = 'localhost.localdomain'17251726 @app.route('/')1727 def normal_index():1728 return 'normal index'17291730 @app.route('/', subdomain='test')1731 def test_index():1732 return 'test index'17331734 rv = client.get('/', 'http://localhost.localdomain/')1735 assert rv.data == b'normal index'17361737 rv = client.get('/', 'http://test.localhost.localdomain/')1738 assert rv.data == b'test index'173917401741def test_subdomain_matching(app, client):1742 app.config['SERVER_NAME'] = 'localhost.localdomain'17431744 @app.route('/', subdomain='<user>')1745 def index(user):1746 return 'index for %s' % user17471748 rv = client.get('/', 'http://mitsuhiko.localhost.localdomain/')1749 assert rv.data == b'index for mitsuhiko'175017511752def test_subdomain_matching_with_ports(app, client):1753 app.config['SERVER_NAME'] = 'localhost.localdomain:3000'17541755 @app.route('/', subdomain='<user>')1756 def index(user):1757 return 'index for %s' % user17581759 rv = client.get('/', 'http://mitsuhiko.localhost.localdomain:3000/')1760 assert rv.data == b'index for mitsuhiko'176117621763def test_multi_route_rules(app, client):1764 @app.route('/')1765 @app.route('/<test>/')1766 def index(test='a'):1767 return test17681769 rv = client.open('/')1770 assert rv.data == b'a'1771 rv = client.open('/b/')1772 assert rv.data == b'b'177317741775def test_multi_route_class_views(app, client):1776 class View(object):1777 def __init__(self, app):1778 app.add_url_rule('/', 'index', self.index)1779 app.add_url_rule('/<test>/', 'index', self.index)17801781 def index(self, test='a'):1782 return test17831784 _ = View(app)1785 rv = client.open('/')1786 assert rv.data == b'a'1787 rv = client.open('/b/')1788 assert rv.data == b'b'178917901791def test_run_defaults(monkeypatch, app):1792 rv = {}17931794 # Mocks werkzeug.serving.run_simple method1795 def run_simple_mock(*args, **kwargs):1796 rv['result'] = 'running...'17971798 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1799 app.run()1800 assert rv['result'] == 'running...'180118021803def test_run_server_port(monkeypatch, app):1804 rv = {}18051806 # Mocks werkzeug.serving.run_simple method1807 def run_simple_mock(hostname, port, application, *args, **kwargs):1808 rv['result'] = 'running on %s:%s ...' % (hostname, port)18091810 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1811 hostname, port = 'localhost', 80001812 app.run(hostname, port, debug=True)1813 assert rv['result'] == 'running on %s:%s ...' % (hostname, port)181418151816@pytest.mark.parametrize('host,port,expect_host,expect_port', (1817 (None, None, 'pocoo.org', 8080),1818 ('localhost', None, 'localhost', 8080),1819 (None, 80, 'pocoo.org', 80),1820 ('localhost', 80, 'localhost', 80),1821))1822def test_run_from_config(monkeypatch, host, port, expect_host, expect_port, app):1823 def run_simple_mock(hostname, port, *args, **kwargs):1824 assert hostname == expect_host1825 assert port == expect_port18261827 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1828 app.config['SERVER_NAME'] = 'pocoo.org:8080'1829 app.run(host, port)