Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

1,736 lines · 46.4 KiB · Python

Last changed by

Change Flask.__init__ to accept two new keyword arguments, host_matching and static_host. (#1560)jabbefore adoption00d6e33

History of this file

Take it

The walk stopped after 200 commits: lines older than bd66710 point at it.

Changelog for #1763Markus Unterwaditzerbefore adoptionbd66710

lines 1–335why, one step back
1# -*- coding: utf-8 -*-
2"""3 tests.basic4 ~~~~~~~~~~~~~~~~~~~~~56 The basic functionality.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314import re15import uuid16import time17import flask18import pickle19from datetime import datetime20from threading import Thread21from flask._compat import text_type22from werkzeug.exceptions import BadRequest, NotFound, Forbidden23from werkzeug.http import parse_date24from werkzeug.routing import BuildError25import werkzeug.serving262728def test_options_work():29 app = flask.Flask(__name__)3031 @app.route('/', methods=['GET', 'POST'])32 def index():33 return 'Hello World'34 rv = app.test_client().open('/', method='OPTIONS')35 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']36 assert rv.data == b''373839def test_options_on_multiple_rules():40 app = flask.Flask(__name__)4142 @app.route('/', methods=['GET', 'POST'])43 def index():44 return 'Hello World'4546 @app.route('/', methods=['PUT'])47 def index_put():48 return 'Aha!'49 rv = app.test_client().open('/', method='OPTIONS')50 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']515253def test_options_handling_disabled():54 app = flask.Flask(__name__)5556 def index():57 return 'Hello World!'58 index.provide_automatic_options = False59 app.route('/')(index)60 rv = app.test_client().open('/', method='OPTIONS')61 assert rv.status_code == 4056263 app = flask.Flask(__name__)6465 def index2():66 return 'Hello World!'67 index2.provide_automatic_options = True68 app.route('/', methods=['OPTIONS'])(index2)69 rv = app.test_client().open('/', method='OPTIONS')70 assert sorted(rv.allow) == ['OPTIONS']717273def test_request_dispatching():74 app = flask.Flask(__name__)7576 @app.route('/')77 def index():78 return flask.request.method7980 @app.route('/more', methods=['GET', 'POST'])81 def more():82 return flask.request.method8384 c = app.test_client()85 assert c.get('/').data == b'GET'86 rv = c.post('/')87 assert rv.status_code == 40588 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']89 rv = c.head('/')90 assert rv.status_code == 20091 assert not rv.data # head truncates92 assert c.post('/more').data == b'POST'93 assert c.get('/more').data == b'GET'94 rv = c.delete('/more')95 assert rv.status_code == 40596 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']979899def test_disallow_string_for_allowed_methods():100 app = flask.Flask(__name__)101 with pytest.raises(TypeError):102 @app.route('/', methods='GET POST')103 def index():104 return "Hey"105106107def test_url_mapping():108 app = flask.Flask(__name__)109110 random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"111112 def index():113 return flask.request.method114115 def more():116 return flask.request.method117118 def options():119 return random_uuid4120121122 app.add_url_rule('/', 'index', index)123 app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])124125 # Issue 1288: Test that automatic options are not added when non-uppercase 'options' in methods126 app.add_url_rule('/options', 'options', options, methods=['options'])127128 c = app.test_client()129 assert c.get('/').data == b'GET'130 rv = c.post('/')131 assert rv.status_code == 405132 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']133 rv = c.head('/')134 assert rv.status_code == 200135 assert not rv.data # head truncates136 assert c.post('/more').data == b'POST'137 assert c.get('/more').data == b'GET'138 rv = c.delete('/more')139 assert rv.status_code == 405140 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']141 rv = c.open('/options', method='OPTIONS')142 assert rv.status_code == 200143 assert random_uuid4 in rv.data.decode("utf-8")144145146def test_werkzeug_routing():147 from werkzeug.routing import Submount, Rule148 app = flask.Flask(__name__)149 app.url_map.add(Submount('/foo', [150 Rule('/bar', endpoint='bar'),151 Rule('/', endpoint='index')152 ]))153154 def bar():155 return 'bar'156157 def index():158 return 'index'159 app.view_functions['bar'] = bar160 app.view_functions['index'] = index161162 c = app.test_client()163 assert c.get('/foo/').data == b'index'164 assert c.get('/foo/bar').data == b'bar'165166167def test_endpoint_decorator():168 from werkzeug.routing import Submount, Rule169 app = flask.Flask(__name__)170 app.url_map.add(Submount('/foo', [171 Rule('/bar', endpoint='bar'),172 Rule('/', endpoint='index')173 ]))174175 @app.endpoint('bar')176 def bar():177 return 'bar'178179 @app.endpoint('index')180 def index():181 return 'index'182183 c = app.test_client()184 assert c.get('/foo/').data == b'index'185 assert c.get('/foo/bar').data == b'bar'186187188def test_session():189 app = flask.Flask(__name__)190 app.secret_key = 'testkey'191192 @app.route('/set', methods=['POST'])193 def set():194 flask.session['value'] = flask.request.form['value']195 return 'value set'196197 @app.route('/get')198 def get():199 return flask.session['value']200201 c = app.test_client()202 assert c.post('/set', data={'value': '42'}).data == b'value set'203 assert c.get('/get').data == b'42'204205206def test_session_using_server_name():207 app = flask.Flask(__name__)208 app.config.update(209 SECRET_KEY='foo',210 SERVER_NAME='example.com'211 )212213 @app.route('/')214 def index():215 flask.session['testing'] = 42216 return 'Hello World'217 rv = app.test_client().get('/', 'http://example.com/')218 assert 'domain=.example.com' in rv.headers['set-cookie'].lower()219 assert 'httponly' in rv.headers['set-cookie'].lower()220221222def test_session_using_server_name_and_port():223 app = flask.Flask(__name__)224 app.config.update(225 SECRET_KEY='foo',226 SERVER_NAME='example.com:8080'227 )228229 @app.route('/')230 def index():231 flask.session['testing'] = 42232 return 'Hello World'233 rv = app.test_client().get('/', 'http://example.com:8080/')234 assert 'domain=.example.com' in rv.headers['set-cookie'].lower()235 assert 'httponly' in rv.headers['set-cookie'].lower()236237238def test_session_using_server_name_port_and_path():239 app = flask.Flask(__name__)240 app.config.update(241 SECRET_KEY='foo',242 SERVER_NAME='example.com:8080',243 APPLICATION_ROOT='/foo'244 )245246 @app.route('/')247 def index():248 flask.session['testing'] = 42249 return 'Hello World'250 rv = app.test_client().get('/', 'http://example.com:8080/foo')251 assert 'domain=example.com' in rv.headers['set-cookie'].lower()252 assert 'path=/foo' in rv.headers['set-cookie'].lower()253 assert 'httponly' in rv.headers['set-cookie'].lower()254255256def test_session_using_application_root():257 class PrefixPathMiddleware(object):258259 def __init__(self, app, prefix):260 self.app = app261 self.prefix = prefix262263 def __call__(self, environ, start_response):264 environ['SCRIPT_NAME'] = self.prefix265 return self.app(environ, start_response)266267 app = flask.Flask(__name__)268 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar')269 app.config.update(270 SECRET_KEY='foo',271 APPLICATION_ROOT='/bar'272 )273274 @app.route('/')275 def index():276 flask.session['testing'] = 42277 return 'Hello World'278 rv = app.test_client().get('/', 'http://example.com:8080/')279 assert 'path=/bar' in rv.headers['set-cookie'].lower()280281282def test_session_using_session_settings():283 app = flask.Flask(__name__)284 app.config.update(285 SECRET_KEY='foo',286 SERVER_NAME='www.example.com:8080',287 APPLICATION_ROOT='/test',288 SESSION_COOKIE_DOMAIN='.example.com',289 SESSION_COOKIE_HTTPONLY=False,290 SESSION_COOKIE_SECURE=True,291 SESSION_COOKIE_PATH='/'292 )293294 @app.route('/')295 def index():296 flask.session['testing'] = 42297 return 'Hello World'298 rv = app.test_client().get('/', 'http://www.example.com:8080/test/')299 cookie = rv.headers['set-cookie'].lower()300 assert 'domain=.example.com' in cookie301 assert 'path=/' in cookie302 assert 'secure' in cookie303 assert 'httponly' not in cookie304305306def test_missing_session():307 app = flask.Flask(__name__)308309 def expect_exception(f, *args, **kwargs):310 e = pytest.raises(RuntimeError, f, *args, **kwargs)311 assert e.value.args and 'session is unavailable' in e.value.args[0]312 with app.test_request_context():313 assert flask.session.get('missing_key') is None314 expect_exception(flask.session.__setitem__, 'foo', 42)315 expect_exception(flask.session.pop, 'foo')316317318def test_session_expiration():319 permanent = True320 app = flask.Flask(__name__)321 app.secret_key = 'testkey'322323 @app.route('/')324 def index():325 flask.session['test'] = 42326 flask.session.permanent = permanent327 return ''328329 @app.route('/test')330 def test():331 return text_type(flask.session.permanent)332333 client = app.test_client()334 rv = client.get('/')335 assert 'set-cookie' in rv.headers

Merge pull request #2148 from drewja/masterDavid Lordbefore adoption22c613b

line 336why, one step back
336 match = re.search(r'(?i)\bexpires=([^;]+)', rv.headers['set-cookie'])

Changelog for #1763Markus Unterwaditzerbefore adoptionbd66710

lines 337–770why, one step back
337 expires = parse_date(match.group())
338 expected = datetime.utcnow() + app.permanent_session_lifetime339 assert expires.year == expected.year340 assert expires.month == expected.month341 assert expires.day == expected.day342343 rv = client.get('/test')344 assert rv.data == b'True'345346 permanent = False347 rv = app.test_client().get('/')348 assert 'set-cookie' in rv.headers349 match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])350 assert match is None351352353def test_session_stored_last():354 app = flask.Flask(__name__)355 app.secret_key = 'development-key'356 app.testing = True357358 @app.after_request359 def modify_session(response):360 flask.session['foo'] = 42361 return response362363 @app.route('/')364 def dump_session_contents():365 return repr(flask.session.get('foo'))366367 c = app.test_client()368 assert c.get('/').data == b'None'369 assert c.get('/').data == b'42'370371372def test_session_special_types():373 app = flask.Flask(__name__)374 app.secret_key = 'development-key'375 app.testing = True376 now = datetime.utcnow().replace(microsecond=0)377 the_uuid = uuid.uuid4()378379 @app.after_request380 def modify_session(response):381 flask.session['m'] = flask.Markup('Hello!')382 flask.session['u'] = the_uuid383 flask.session['dt'] = now384 flask.session['b'] = b'\xff'385 flask.session['t'] = (1, 2, 3)386 return response387388 @app.route('/')389 def dump_session_contents():390 return pickle.dumps(dict(flask.session))391392 c = app.test_client()393 c.get('/')394 rv = pickle.loads(c.get('/').data)395 assert rv['m'] == flask.Markup('Hello!')396 assert type(rv['m']) == flask.Markup397 assert rv['dt'] == now398 assert rv['u'] == the_uuid399 assert rv['b'] == b'\xff'400 assert type(rv['b']) == bytes401 assert rv['t'] == (1, 2, 3)402403404def test_session_cookie_setting():405 app = flask.Flask(__name__)406 app.testing = True407 app.secret_key = 'dev key'408 is_permanent = True409410 @app.route('/bump')411 def bump():412 rv = flask.session['foo'] = flask.session.get('foo', 0) + 1413 flask.session.permanent = is_permanent414 return str(rv)415416 @app.route('/read')417 def read():418 return str(flask.session.get('foo', 0))419420 def run_test(expect_header):421 with app.test_client() as c:422 assert c.get('/bump').data == b'1'423 assert c.get('/bump').data == b'2'424 assert c.get('/bump').data == b'3'425426 rv = c.get('/read')427 set_cookie = rv.headers.get('set-cookie')428 assert (set_cookie is not None) == expect_header429 assert rv.data == b'3'430431 is_permanent = True432 app.config['SESSION_REFRESH_EACH_REQUEST'] = True433 run_test(expect_header=True)434435 is_permanent = True436 app.config['SESSION_REFRESH_EACH_REQUEST'] = False437 run_test(expect_header=False)438439 is_permanent = False440 app.config['SESSION_REFRESH_EACH_REQUEST'] = True441 run_test(expect_header=False)442443 is_permanent = False444 app.config['SESSION_REFRESH_EACH_REQUEST'] = False445 run_test(expect_header=False)446447448def test_flashes():449 app = flask.Flask(__name__)450 app.secret_key = 'testkey'451452 with app.test_request_context():453 assert not flask.session.modified454 flask.flash('Zap')455 flask.session.modified = False456 flask.flash('Zip')457 assert flask.session.modified458 assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']459460461def test_extended_flashing():462 # Be sure app.testing=True below, else tests can fail silently.463 #464 # Specifically, if app.testing is not set to True, the AssertionErrors465 # in the view functions will cause a 500 response to the test client466 # instead of propagating exceptions.467468 app = flask.Flask(__name__)469 app.secret_key = 'testkey'470 app.testing = True471472 @app.route('/')473 def index():474 flask.flash(u'Hello World')475 flask.flash(u'Hello World', 'error')476 flask.flash(flask.Markup(u'<em>Testing</em>'), 'warning')477 return ''478479 @app.route('/test/')480 def test():481 messages = flask.get_flashed_messages()482 assert list(messages) == [483 u'Hello World',484 u'Hello World',485 flask.Markup(u'<em>Testing</em>')486 ]487 return ''488489 @app.route('/test_with_categories/')490 def test_with_categories():491 messages = flask.get_flashed_messages(with_categories=True)492 assert len(messages) == 3493 assert list(messages) == [494 ('message', u'Hello World'),495 ('error', u'Hello World'),496 ('warning', flask.Markup(u'<em>Testing</em>'))497 ]498 return ''499500 @app.route('/test_filter/')501 def test_filter():502 messages = flask.get_flashed_messages(503 category_filter=['message'], with_categories=True)504 assert list(messages) == [('message', u'Hello World')]505 return ''506507 @app.route('/test_filters/')508 def test_filters():509 messages = flask.get_flashed_messages(510 category_filter=['message', 'warning'], with_categories=True)511 assert list(messages) == [512 ('message', u'Hello World'),513 ('warning', flask.Markup(u'<em>Testing</em>'))514 ]515 return ''516517 @app.route('/test_filters_without_returning_categories/')518 def test_filters2():519 messages = flask.get_flashed_messages(520 category_filter=['message', 'warning'])521 assert len(messages) == 2522 assert messages[0] == u'Hello World'523 assert messages[1] == flask.Markup(u'<em>Testing</em>')524 return ''525526 # Create new test client on each test to clean flashed messages.527528 c = app.test_client()529 c.get('/')530 c.get('/test/')531532 c = app.test_client()533 c.get('/')534 c.get('/test_with_categories/')535536 c = app.test_client()537 c.get('/')538 c.get('/test_filter/')539540 c = app.test_client()541 c.get('/')542 c.get('/test_filters/')543544 c = app.test_client()545 c.get('/')546 c.get('/test_filters_without_returning_categories/')547548549def test_request_processing():550 app = flask.Flask(__name__)551 evts = []552553 @app.before_request554 def before_request():555 evts.append('before')556557 @app.after_request558 def after_request(response):559 response.data += b'|after'560 evts.append('after')561 return response562563 @app.route('/')564 def index():565 assert 'before' in evts566 assert 'after' not in evts567 return 'request'568 assert 'after' not in evts569 rv = app.test_client().get('/').data570 assert 'after' in evts571 assert rv == b'request|after'572573574def test_request_preprocessing_early_return():575 app = flask.Flask(__name__)576 evts = []577578 @app.before_request579 def before_request1():580 evts.append(1)581582 @app.before_request583 def before_request2():584 evts.append(2)585 return "hello"586587 @app.before_request588 def before_request3():589 evts.append(3)590 return "bye"591592 @app.route('/')593 def index():594 evts.append('index')595 return "damnit"596597 rv = app.test_client().get('/').data.strip()598 assert rv == b'hello'599 assert evts == [1, 2]600601602def test_after_request_processing():603 app = flask.Flask(__name__)604 app.testing = True605606 @app.route('/')607 def index():608 @flask.after_this_request609 def foo(response):610 response.headers['X-Foo'] = 'a header'611 return response612 return 'Test'613 c = app.test_client()614 resp = c.get('/')615 assert resp.status_code == 200616 assert resp.headers['X-Foo'] == 'a header'617618619def test_teardown_request_handler():620 called = []621 app = flask.Flask(__name__)622623 @app.teardown_request624 def teardown_request(exc):625 called.append(True)626 return "Ignored"627628 @app.route('/')629 def root():630 return "Response"631 rv = app.test_client().get('/')632 assert rv.status_code == 200633 assert b'Response' in rv.data634 assert len(called) == 1635636637def test_teardown_request_handler_debug_mode():638 called = []639 app = flask.Flask(__name__)640 app.testing = True641642 @app.teardown_request643 def teardown_request(exc):644 called.append(True)645 return "Ignored"646647 @app.route('/')648 def root():649 return "Response"650 rv = app.test_client().get('/')651 assert rv.status_code == 200652 assert b'Response' in rv.data653 assert len(called) == 1654655656def test_teardown_request_handler_error():657 called = []658 app = flask.Flask(__name__)659 app.config['LOGGER_HANDLER_POLICY'] = 'never'660661 @app.teardown_request662 def teardown_request1(exc):663 assert type(exc) == ZeroDivisionError664 called.append(True)665 # This raises a new error and blows away sys.exc_info(), so we can666 # test that all teardown_requests get passed the same original667 # exception.668 try:669 raise TypeError()670 except:671 pass672673 @app.teardown_request674 def teardown_request2(exc):675 assert type(exc) == ZeroDivisionError676 called.append(True)677 # This raises a new error and blows away sys.exc_info(), so we can678 # test that all teardown_requests get passed the same original679 # exception.680 try:681 raise TypeError()682 except:683 pass684685 @app.route('/')686 def fails():687 1 // 0688 rv = app.test_client().get('/')689 assert rv.status_code == 500690 assert b'Internal Server Error' in rv.data691 assert len(called) == 2692693694def test_before_after_request_order():695 called = []696 app = flask.Flask(__name__)697698 @app.before_request699 def before1():700 called.append(1)701702 @app.before_request703 def before2():704 called.append(2)705706 @app.after_request707 def after1(response):708 called.append(4)709 return response710711 @app.after_request712 def after2(response):713 called.append(3)714 return response715716 @app.teardown_request717 def finish1(exc):718 called.append(6)719720 @app.teardown_request721 def finish2(exc):722 called.append(5)723724 @app.route('/')725 def index():726 return '42'727 rv = app.test_client().get('/')728 assert rv.data == b'42'729 assert called == [1, 2, 3, 4, 5, 6]730731732def test_error_handling():733 app = flask.Flask(__name__)734 app.config['LOGGER_HANDLER_POLICY'] = 'never'735736 @app.errorhandler(404)737 def not_found(e):738 return 'not found', 404739740 @app.errorhandler(500)741 def internal_server_error(e):742 return 'internal server error', 500743744 @app.errorhandler(Forbidden)745 def forbidden(e):746 return 'forbidden', 403747748 @app.route('/')749 def index():750 flask.abort(404)751752 @app.route('/error')753 def error():754 1 // 0755756 @app.route('/forbidden')757 def error2():758 flask.abort(403)759 c = app.test_client()760 rv = c.get('/')761 assert rv.status_code == 404762 assert rv.data == b'not found'763 rv = c.get('/error')764 assert rv.status_code == 500765 assert b'internal server error' == rv.data766 rv = c.get('/forbidden')767 assert rv.status_code == 403768 assert b'forbidden' == rv.data769770

Merge pull request #2013 from pallets/bugfix/error-handler-error-handlerArmin Ronacherbefore adoption9e41eca

lines 771–793why, one step back
771def test_error_handling_processing():
772 app = flask.Flask(__name__)773 app.config['LOGGER_HANDLER_POLICY'] = 'never'774775 @app.errorhandler(500)776 def internal_server_error(e):777 return 'internal server error', 500778779 @app.route('/')780 def broken_func():781 1 // 0782783 @app.after_request784 def after_request(resp):785 resp.mimetype = 'text/x-special'786 return resp787788 with app.test_client() as c:789 resp = c.get('/')790 assert resp.mimetype == 'text/x-special'791 assert resp.data == b'internal server error'792793

Merge branch '0.12-maintenance'Markus Unterwaditzerbefore adoptionde555c8

lines 794–810why, one step back
794def test_baseexception_error_handling():
795 app = flask.Flask(__name__)796 app.config['LOGGER_HANDLER_POLICY'] = 'never'797798 @app.route('/')799 def broken_func():800 raise KeyboardInterrupt()801802 with app.test_client() as c:803 with pytest.raises(KeyboardInterrupt):804 c.get('/')805806 ctx = flask._request_ctx_stack.top807 assert ctx.preserved808 assert type(ctx._preserved_exc) is KeyboardInterrupt809810

Changelog for #1763Markus Unterwaditzerbefore adoptionbd66710

lines 811–1014why, one step back
811def test_before_request_and_routing_errors():
812 app = flask.Flask(__name__)813814 @app.before_request815 def attach_something():816 flask.g.something = 'value'817818 @app.errorhandler(404)819 def return_something(error):820 return flask.g.something, 404821 rv = app.test_client().get('/')822 assert rv.status_code == 404823 assert rv.data == b'value'824825826def test_user_error_handling():827 class MyException(Exception):828 pass829830 app = flask.Flask(__name__)831832 @app.errorhandler(MyException)833 def handle_my_exception(e):834 assert isinstance(e, MyException)835 return '42'836837 @app.route('/')838 def index():839 raise MyException()840841 c = app.test_client()842 assert c.get('/').data == b'42'843844845def test_http_error_subclass_handling():846 class ForbiddenSubclass(Forbidden):847 pass848849 app = flask.Flask(__name__)850851 @app.errorhandler(ForbiddenSubclass)852 def handle_forbidden_subclass(e):853 assert isinstance(e, ForbiddenSubclass)854 return 'banana'855856 @app.errorhandler(403)857 def handle_forbidden_subclass(e):858 assert not isinstance(e, ForbiddenSubclass)859 assert isinstance(e, Forbidden)860 return 'apple'861862 @app.route('/1')863 def index1():864 raise ForbiddenSubclass()865866 @app.route('/2')867 def index2():868 flask.abort(403)869870 @app.route('/3')871 def index3():872 raise Forbidden()873874 c = app.test_client()875 assert c.get('/1').data == b'banana'876 assert c.get('/2').data == b'apple'877 assert c.get('/3').data == b'apple'878879880def test_trapping_of_bad_request_key_errors():881 app = flask.Flask(__name__)882 app.testing = True883884 @app.route('/fail')885 def fail():886 flask.request.form['missing_key']887 c = app.test_client()888 assert c.get('/fail').status_code == 400889890 app.config['TRAP_BAD_REQUEST_ERRORS'] = True891 c = app.test_client()892 with pytest.raises(KeyError) as e:893 c.get("/fail")894 assert e.errisinstance(BadRequest)895896897def test_trapping_of_all_http_exceptions():898 app = flask.Flask(__name__)899 app.testing = True900 app.config['TRAP_HTTP_EXCEPTIONS'] = True901902 @app.route('/fail')903 def fail():904 flask.abort(404)905906 c = app.test_client()907 with pytest.raises(NotFound):908 c.get('/fail')909910911def test_enctype_debug_helper():912 from flask.debughelpers import DebugFilesKeyError913 app = flask.Flask(__name__)914 app.debug = True915916 @app.route('/fail', methods=['POST'])917 def index():918 return flask.request.files['foo'].filename919920 # with statement is important because we leave an exception on the921 # stack otherwise and we want to ensure that this is not the case922 # to not negatively affect other tests.923 with app.test_client() as c:924 with pytest.raises(DebugFilesKeyError) as e:925 c.post('/fail', data={'foo': 'index.txt'})926 assert 'no file contents were transmitted' in str(e.value)927 assert 'This was submitted: "index.txt"' in str(e.value)928929930def test_response_creation():931 app = flask.Flask(__name__)932933 @app.route('/unicode')934 def from_unicode():935 return u'Hällo Wörld'936937 @app.route('/string')938 def from_string():939 return u'Hällo Wörld'.encode('utf-8')940941 @app.route('/args')942 def from_tuple():943 return 'Meh', 400, {944 'X-Foo': 'Testing',945 'Content-Type': 'text/plain; charset=utf-8'946 }947948 @app.route('/two_args')949 def from_two_args_tuple():950 return 'Hello', {951 'X-Foo': 'Test',952 'Content-Type': 'text/plain; charset=utf-8'953 }954955 @app.route('/args_status')956 def from_status_tuple():957 return 'Hi, status!', 400958959 @app.route('/args_header')960 def from_response_instance_status_tuple():961 return flask.Response('Hello world', 404), {962 "X-Foo": "Bar",963 "X-Bar": "Foo"964 }965966 c = app.test_client()967 assert c.get('/unicode').data == u'Hällo Wörld'.encode('utf-8')968 assert c.get('/string').data == u'Hällo Wörld'.encode('utf-8')969 rv = c.get('/args')970 assert rv.data == b'Meh'971 assert rv.headers['X-Foo'] == 'Testing'972 assert rv.status_code == 400973 assert rv.mimetype == 'text/plain'974 rv2 = c.get('/two_args')975 assert rv2.data == b'Hello'976 assert rv2.headers['X-Foo'] == 'Test'977 assert rv2.status_code == 200978 assert rv2.mimetype == 'text/plain'979 rv3 = c.get('/args_status')980 assert rv3.data == b'Hi, status!'981 assert rv3.status_code == 400982 assert rv3.mimetype == 'text/html'983 rv4 = c.get('/args_header')984 assert rv4.data == b'Hello world'985 assert rv4.headers['X-Foo'] == 'Bar'986 assert rv4.headers['X-Bar'] == 'Foo'987 assert rv4.status_code == 404988989990def test_make_response():991 app = flask.Flask(__name__)992 with app.test_request_context():993 rv = flask.make_response()994 assert rv.status_code == 200995 assert rv.data == b''996 assert rv.mimetype == 'text/html'997998 rv = flask.make_response('Awesome')999 assert rv.status_code == 2001000 assert rv.data == b'Awesome'1001 assert rv.mimetype == 'text/html'10021003 rv = flask.make_response('W00t', 404)1004 assert rv.status_code == 4041005 assert rv.data == b'W00t'1006 assert rv.mimetype == 'text/html'100710081009def test_make_response_with_response_instance():1010 app = flask.Flask(__name__)1011 with app.test_request_context():1012 rv = flask.make_response(1013 flask.jsonify({'msg': 'W00t'}), 400)1014 assert rv.status_code == 400

Don't rely on X-Requested-With for pretty print json response (#2193)Hsiaoming Yangbefore adoptiona7f1a21

line 1015why, one step back
1015 assert rv.data == b'{"msg":"W00t"}\n'

Changelog for #1763Markus Unterwaditzerbefore adoptionbd66710

lines 1016–1061why, one step back
1016 assert rv.mimetype == 'application/json'
10171018 rv = flask.make_response(1019 flask.Response(''), 400)1020 assert rv.status_code == 4001021 assert rv.data == b''1022 assert rv.mimetype == 'text/html'10231024 rv = flask.make_response(1025 flask.Response('', headers={'Content-Type': 'text/html'}),1026 400, [('X-Foo', 'bar')])1027 assert rv.status_code == 4001028 assert rv.headers['Content-Type'] == 'text/html'1029 assert rv.headers['X-Foo'] == 'bar'103010311032def test_jsonify_no_prettyprint():1033 app = flask.Flask(__name__)1034 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1035 with app.test_request_context():1036 compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1037 uncompressed_msg = {1038 "msg": {1039 "submsg": "W00t"1040 },1041 "msg2": "foobar"1042 }10431044 rv = flask.make_response(1045 flask.jsonify(uncompressed_msg), 200)1046 assert rv.data == compressed_msg104710481049def test_jsonify_prettyprint():1050 app = flask.Flask(__name__)1051 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1052 with app.test_request_context():1053 compressed_msg = {"msg":{"submsg":"W00t"},"msg2":"foobar"}1054 pretty_response =\1055 b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'10561057 rv = flask.make_response(1058 flask.jsonify(compressed_msg), 200)1059 assert rv.data == pretty_response10601061

Add JSONIFY_MIMETYPE configuration variable (#1728)Steven Loriabefore adoption2bf477c

lines 1062–1073why, one step back
1062def test_jsonify_mimetype():
1063 app = flask.Flask(__name__)1064 app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'})1065 with app.test_request_context():1066 msg = {1067 "msg": {"submsg": "W00t"},1068 }1069 rv = flask.make_response(1070 flask.jsonify(msg), 200)1071 assert rv.mimetype == 'application/vnd.api+json'10721073

Add negative test for json.jsonify (#1876)dawran6before adoptione048aa4

lines 1074–1081why, one step back
1074def test_jsonify_args_and_kwargs_check():
1075 app = flask.Flask(__name__)1076 with app.test_request_context():1077 with pytest.raises(TypeError) as e:1078 flask.jsonify('fake args', kwargs='fake')1079 assert 'behavior undefined' in str(e.value)10801081

Changelog for #1763Markus Unterwaditzerbefore adoptionbd66710

lines 1082–1166why, one step back
1082def test_url_generation():
1083 app = flask.Flask(__name__)10841085 @app.route('/hello/<name>', methods=['POST'])1086 def hello():1087 pass1088 with app.test_request_context():1089 assert flask.url_for('hello', name='test x') == '/hello/test%20x'1090 assert flask.url_for('hello', name='test x', _external=True) == \1091 'http://localhost/hello/test%20x'109210931094def test_build_error_handler():1095 app = flask.Flask(__name__)10961097 # Test base case, a URL which results in a BuildError.1098 with app.test_request_context():1099 pytest.raises(BuildError, flask.url_for, 'spam')11001101 # Verify the error is re-raised if not the current exception.1102 try:1103 with app.test_request_context():1104 flask.url_for('spam')1105 except BuildError as err:1106 error = err1107 try:1108 raise RuntimeError('Test case where BuildError is not current.')1109 except RuntimeError:1110 pytest.raises(1111 BuildError, app.handle_url_build_error, error, 'spam', {})11121113 # Test a custom handler.1114 def handler(error, endpoint, values):1115 # Just a test.1116 return '/test_handler/'1117 app.url_build_error_handlers.append(handler)1118 with app.test_request_context():1119 assert flask.url_for('spam') == '/test_handler/'112011211122def test_build_error_handler_reraise():1123 app = flask.Flask(__name__)11241125 # Test a custom handler which reraises the BuildError1126 def handler_raises_build_error(error, endpoint, values):1127 raise error1128 app.url_build_error_handlers.append(handler_raises_build_error)11291130 with app.test_request_context():1131 pytest.raises(BuildError, flask.url_for, 'not.existing')113211331134def test_custom_converters():1135 from werkzeug.routing import BaseConverter11361137 class ListConverter(BaseConverter):11381139 def to_python(self, value):1140 return value.split(',')11411142 def to_url(self, value):1143 base_to_url = super(ListConverter, self).to_url1144 return ','.join(base_to_url(x) for x in value)1145 app = flask.Flask(__name__)1146 app.url_map.converters['list'] = ListConverter11471148 @app.route('/<list:args>')1149 def index(args):1150 return '|'.join(args)1151 c = app.test_client()1152 assert c.get('/1,2,3').data == b'1|2|3'115311541155def test_static_files():1156 app = flask.Flask(__name__)1157 app.testing = True1158 rv = app.test_client().get('/static/index.html')1159 assert rv.status_code == 2001160 assert rv.data.strip() == b'<h1>Hello World!</h1>'1161 with app.test_request_context():1162 assert flask.url_for('static', filename='index.html') == \1163 '/static/index.html'1164 rv.close()11651166

Merge pull request #1878 from untitaker/recwarnMarkus Unterwaditzerbefore adoption3d72099

lines 1167–1170why, one step back
1167def test_static_path_deprecated(recwarn):
1168 app = flask.Flask(__name__, static_path='/foo')1169 recwarn.pop(DeprecationWarning)1170

Coverage for test_static_path_deprecated and test_static_url_path (#1860)jphilipsen05before adoption047efac

lines 1171–1173why, one step back
1171 app.testing = True
1172 rv = app.test_client().get('/foo/index.html')1173 assert rv.status_code == 200

Merge pull request #1878 from untitaker/recwarnMarkus Unterwaditzerbefore adoption3d72099

lines 1174–1175why, one step back
1174 rv.close()
1175

Coverage for test_static_path_deprecated and test_static_url_path (#1860)jphilipsen05before adoption047efac

lines 1176–1184why, one step back
1176 with app.test_request_context():
1177 assert flask.url_for('static', filename='index.html') == '/foo/index.html'117811791180def test_static_url_path():1181 app = flask.Flask(__name__, static_url_path='/foo')1182 app.testing = True1183 rv = app.test_client().get('/foo/index.html')1184 assert rv.status_code == 200

Merge pull request #1878 from untitaker/recwarnMarkus Unterwaditzerbefore adoption3d72099

lines 1185–1186why, one step back
1185 rv.close()
1186

Coverage for test_static_path_deprecated and test_static_url_path (#1860)jphilipsen05before adoption047efac

lines 1187–1190why, one step back
1187 with app.test_request_context():
1188 assert flask.url_for('static', filename='index.html') == '/foo/index.html'11891190

Change Flask.__init__ to accept two new keyword arguments, host_matching and static_host. (#1560)jabbefore adoption00d6e33

lines 1191–1209why, one step back
1191def test_static_route_with_host_matching():
1192 app = flask.Flask(__name__, host_matching=True, static_host='example.com')1193 c = app.test_client()1194 rv = c.get('http://example.com/static/index.html')1195 assert rv.status_code == 2001196 rv.close()1197 with app.test_request_context():1198 rv = flask.url_for('static', filename='index.html', _external=True)1199 assert rv == 'http://example.com/static/index.html'1200 # Providing static_host without host_matching=True should error.1201 with pytest.raises(Exception):1202 flask.Flask(__name__, static_host='example.com')1203 # Providing host_matching=True with static_folder but without static_host should error.1204 with pytest.raises(Exception):1205 flask.Flask(__name__, host_matching=True)1206 # Providing host_matching=True without static_host but with static_folder=None should not error.1207 flask.Flask(__name__, host_matching=True, static_folder=None)12081209

Changelog for #1763Markus Unterwaditzerbefore adoptionbd66710

lines 1210–1719why, one step back
1210def test_none_response():
1211 app = flask.Flask(__name__)1212 app.testing = True12131214 @app.route('/')1215 def test():1216 return None1217 try:1218 app.test_client().get('/')1219 except ValueError as e:1220 assert str(e) == 'View function did not return a response'1221 pass1222 else:1223 assert "Expected ValueError"122412251226def test_request_locals():1227 assert repr(flask.g) == '<LocalProxy unbound>'1228 assert not flask.g122912301231def test_test_app_proper_environ():1232 app = flask.Flask(__name__)1233 app.config.update(1234 SERVER_NAME='localhost.localdomain:5000'1235 )12361237 @app.route('/')1238 def index():1239 return 'Foo'12401241 @app.route('/', subdomain='foo')1242 def subdomain():1243 return 'Foo SubDomain'12441245 rv = app.test_client().get('/')1246 assert rv.data == b'Foo'12471248 rv = app.test_client().get('/', 'http://localhost.localdomain:5000')1249 assert rv.data == b'Foo'12501251 rv = app.test_client().get('/', 'https://localhost.localdomain:5000')1252 assert rv.data == b'Foo'12531254 app.config.update(SERVER_NAME='localhost.localdomain')1255 rv = app.test_client().get('/', 'https://localhost.localdomain')1256 assert rv.data == b'Foo'12571258 try:1259 app.config.update(SERVER_NAME='localhost.localdomain:443')1260 rv = app.test_client().get('/', 'https://localhost.localdomain')1261 # Werkzeug 0.81262 assert rv.status_code == 4041263 except ValueError as e:1264 # Werkzeug 0.71265 assert str(e) == (1266 "the server name provided "1267 "('localhost.localdomain:443') does not match the "1268 "server name from the WSGI environment ('localhost.localdomain')"1269 )12701271 try:1272 app.config.update(SERVER_NAME='localhost.localdomain')1273 rv = app.test_client().get('/', 'http://foo.localhost')1274 # Werkzeug 0.81275 assert rv.status_code == 4041276 except ValueError as e:1277 # Werkzeug 0.71278 assert str(e) == (1279 "the server name provided "1280 "('localhost.localdomain') does not match the "1281 "server name from the WSGI environment ('foo.localhost')"1282 )12831284 rv = app.test_client().get('/', 'http://foo.localhost.localdomain')1285 assert rv.data == b'Foo SubDomain'128612871288def test_exception_propagation():1289 def apprunner(config_key):1290 app = flask.Flask(__name__)1291 app.config['LOGGER_HANDLER_POLICY'] = 'never'12921293 @app.route('/')1294 def index():1295 1 // 01296 c = app.test_client()1297 if config_key is not None:1298 app.config[config_key] = True1299 with pytest.raises(Exception):1300 c.get('/')1301 else:1302 assert c.get('/').status_code == 50013031304 # we have to run this test in an isolated thread because if the1305 # debug flag is set to true and an exception happens the context is1306 # not torn down. This causes other tests that run after this fail1307 # when they expect no exception on the stack.1308 for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None:1309 t = Thread(target=apprunner, args=(config_key,))1310 t.start()1311 t.join()131213131314@pytest.mark.parametrize('debug', [True, False])1315@pytest.mark.parametrize('use_debugger', [True, False])1316@pytest.mark.parametrize('use_reloader', [True, False])1317@pytest.mark.parametrize('propagate_exceptions', [None, True, False])1318def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1319 use_reloader, propagate_exceptions):1320 rv = {}13211322 # Mocks werkzeug.serving.run_simple method1323 def run_simple_mock(*args, **kwargs):1324 rv['passthrough_errors'] = kwargs.get('passthrough_errors')13251326 app = flask.Flask(__name__)1327 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1328 app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1329 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)133013311332def test_max_content_length():1333 app = flask.Flask(__name__)1334 app.config['MAX_CONTENT_LENGTH'] = 6413351336 @app.before_request1337 def always_first():1338 flask.request.form['myfile']1339 assert False13401341 @app.route('/accept', methods=['POST'])1342 def accept_file():1343 flask.request.form['myfile']1344 assert False13451346 @app.errorhandler(413)1347 def catcher(error):1348 return '42'13491350 c = app.test_client()1351 rv = c.post('/accept', data={'myfile': 'foo' * 100})1352 assert rv.data == b'42'135313541355def test_url_processors():1356 app = flask.Flask(__name__)13571358 @app.url_defaults1359 def add_language_code(endpoint, values):1360 if flask.g.lang_code is not None and \1361 app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1362 values.setdefault('lang_code', flask.g.lang_code)13631364 @app.url_value_preprocessor1365 def pull_lang_code(endpoint, values):1366 flask.g.lang_code = values.pop('lang_code', None)13671368 @app.route('/<lang_code>/')1369 def index():1370 return flask.url_for('about')13711372 @app.route('/<lang_code>/about')1373 def about():1374 return flask.url_for('something_else')13751376 @app.route('/foo')1377 def something_else():1378 return flask.url_for('about', lang_code='en')13791380 c = app.test_client()13811382 assert c.get('/de/').data == b'/de/about'1383 assert c.get('/de/about').data == b'/foo'1384 assert c.get('/foo').data == b'/en/about'138513861387def test_inject_blueprint_url_defaults():1388 app = flask.Flask(__name__)1389 bp = flask.Blueprint('foo.bar.baz', __name__,1390 template_folder='template')13911392 @bp.url_defaults1393 def bp_defaults(endpoint, values):1394 values['page'] = 'login'13951396 @bp.route('/<page>')1397 def view(page):1398 pass13991400 app.register_blueprint(bp)14011402 values = dict()1403 app.inject_url_defaults('foo.bar.baz.view', values)1404 expected = dict(page='login')1405 assert values == expected14061407 with app.test_request_context('/somepage'):1408 url = flask.url_for('foo.bar.baz.view')1409 expected = '/login'1410 assert url == expected141114121413def test_nonascii_pathinfo():1414 app = flask.Flask(__name__)1415 app.testing = True14161417 @app.route(u'/киртест')1418 def index():1419 return 'Hello World!'14201421 c = app.test_client()1422 rv = c.get(u'/киртест')1423 assert rv.data == b'Hello World!'142414251426def test_debug_mode_complains_after_first_request():1427 app = flask.Flask(__name__)1428 app.debug = True14291430 @app.route('/')1431 def index():1432 return 'Awesome'1433 assert not app.got_first_request1434 assert app.test_client().get('/').data == b'Awesome'1435 with pytest.raises(AssertionError) as e:1436 @app.route('/foo')1437 def broken():1438 return 'Meh'1439 assert 'A setup function was called' in str(e)14401441 app.debug = False14421443 @app.route('/foo')1444 def working():1445 return 'Meh'1446 assert app.test_client().get('/foo').data == b'Meh'1447 assert app.got_first_request144814491450def test_before_first_request_functions():1451 got = []1452 app = flask.Flask(__name__)14531454 @app.before_first_request1455 def foo():1456 got.append(42)1457 c = app.test_client()1458 c.get('/')1459 assert got == [42]1460 c.get('/')1461 assert got == [42]1462 assert app.got_first_request146314641465def test_before_first_request_functions_concurrent():1466 got = []1467 app = flask.Flask(__name__)14681469 @app.before_first_request1470 def foo():1471 time.sleep(0.2)1472 got.append(42)14731474 c = app.test_client()14751476 def get_and_assert():1477 c.get("/")1478 assert got == [42]14791480 t = Thread(target=get_and_assert)1481 t.start()1482 get_and_assert()1483 t.join()1484 assert app.got_first_request148514861487def test_routing_redirect_debugging():1488 app = flask.Flask(__name__)1489 app.debug = True14901491 @app.route('/foo/', methods=['GET', 'POST'])1492 def foo():1493 return 'success'1494 with app.test_client() as c:1495 with pytest.raises(AssertionError) as e:1496 c.post('/foo', data={})1497 assert 'http://localhost/foo/' in str(e)1498 assert ('Make sure to directly send '1499 'your POST-request to this URL') in str(e)15001501 rv = c.get('/foo', data={}, follow_redirects=True)1502 assert rv.data == b'success'15031504 app.debug = False1505 with app.test_client() as c:1506 rv = c.post('/foo', data={}, follow_redirects=True)1507 assert rv.data == b'success'150815091510def test_route_decorator_custom_endpoint():1511 app = flask.Flask(__name__)1512 app.debug = True15131514 @app.route('/foo/')1515 def foo():1516 return flask.request.endpoint15171518 @app.route('/bar/', endpoint='bar')1519 def for_bar():1520 return flask.request.endpoint15211522 @app.route('/bar/123', endpoint='123')1523 def for_bar_foo():1524 return flask.request.endpoint15251526 with app.test_request_context():1527 assert flask.url_for('foo') == '/foo/'1528 assert flask.url_for('bar') == '/bar/'1529 assert flask.url_for('123') == '/bar/123'15301531 c = app.test_client()1532 assert c.get('/foo/').data == b'foo'1533 assert c.get('/bar/').data == b'bar'1534 assert c.get('/bar/123').data == b'123'153515361537def test_preserve_only_once():1538 app = flask.Flask(__name__)1539 app.debug = True15401541 @app.route('/fail')1542 def fail_func():1543 1 // 015441545 c = app.test_client()1546 for x in range(3):1547 with pytest.raises(ZeroDivisionError):1548 c.get('/fail')15491550 assert flask._request_ctx_stack.top is not None1551 assert flask._app_ctx_stack.top is not None1552 # implicit appctx disappears too1553 flask._request_ctx_stack.top.pop()1554 assert flask._request_ctx_stack.top is None1555 assert flask._app_ctx_stack.top is None155615571558def test_preserve_remembers_exception():1559 app = flask.Flask(__name__)1560 app.debug = True1561 errors = []15621563 @app.route('/fail')1564 def fail_func():1565 1 // 015661567 @app.route('/success')1568 def success_func():1569 return 'Okay'15701571 @app.teardown_request1572 def teardown_handler(exc):1573 errors.append(exc)15741575 c = app.test_client()15761577 # After this failure we did not yet call the teardown handler1578 with pytest.raises(ZeroDivisionError):1579 c.get('/fail')1580 assert errors == []15811582 # But this request triggers it, and it's an error1583 c.get('/success')1584 assert len(errors) == 21585 assert isinstance(errors[0], ZeroDivisionError)15861587 # At this point another request does nothing.1588 c.get('/success')1589 assert len(errors) == 31590 assert errors[1] is None159115921593def test_get_method_on_g():1594 app = flask.Flask(__name__)1595 app.testing = True15961597 with app.app_context():1598 assert flask.g.get('x') is None1599 assert flask.g.get('x', 11) == 111600 flask.g.x = 421601 assert flask.g.get('x') == 421602 assert flask.g.x == 42160316041605def test_g_iteration_protocol():1606 app = flask.Flask(__name__)1607 app.testing = True16081609 with app.app_context():1610 flask.g.foo = 231611 flask.g.bar = 421612 assert 'foo' in flask.g1613 assert 'foos' not in flask.g1614 assert sorted(flask.g) == ['bar', 'foo']161516161617def test_subdomain_basic_support():1618 app = flask.Flask(__name__)1619 app.config['SERVER_NAME'] = 'localhost'16201621 @app.route('/')1622 def normal_index():1623 return 'normal index'16241625 @app.route('/', subdomain='test')1626 def test_index():1627 return 'test index'16281629 c = app.test_client()1630 rv = c.get('/', 'http://localhost/')1631 assert rv.data == b'normal index'16321633 rv = c.get('/', 'http://test.localhost/')1634 assert rv.data == b'test index'163516361637def test_subdomain_matching():1638 app = flask.Flask(__name__)1639 app.config['SERVER_NAME'] = 'localhost'16401641 @app.route('/', subdomain='<user>')1642 def index(user):1643 return 'index for %s' % user16441645 c = app.test_client()1646 rv = c.get('/', 'http://mitsuhiko.localhost/')1647 assert rv.data == b'index for mitsuhiko'164816491650def test_subdomain_matching_with_ports():1651 app = flask.Flask(__name__)1652 app.config['SERVER_NAME'] = 'localhost:3000'16531654 @app.route('/', subdomain='<user>')1655 def index(user):1656 return 'index for %s' % user16571658 c = app.test_client()1659 rv = c.get('/', 'http://mitsuhiko.localhost:3000/')1660 assert rv.data == b'index for mitsuhiko'166116621663def test_multi_route_rules():1664 app = flask.Flask(__name__)16651666 @app.route('/')1667 @app.route('/<test>/')1668 def index(test='a'):1669 return test16701671 rv = app.test_client().open('/')1672 assert rv.data == b'a'1673 rv = app.test_client().open('/b/')1674 assert rv.data == b'b'167516761677def test_multi_route_class_views():1678 class View(object):16791680 def __init__(self, app):1681 app.add_url_rule('/', 'index', self.index)1682 app.add_url_rule('/<test>/', 'index', self.index)16831684 def index(self, test='a'):1685 return test16861687 app = flask.Flask(__name__)1688 _ = View(app)1689 rv = app.test_client().open('/')1690 assert rv.data == b'a'1691 rv = app.test_client().open('/b/')1692 assert rv.data == b'b'169316941695def test_run_defaults(monkeypatch):1696 rv = {}16971698 # Mocks werkzeug.serving.run_simple method1699 def run_simple_mock(*args, **kwargs):1700 rv['result'] = 'running...'17011702 app = flask.Flask(__name__)1703 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1704 app.run()1705 assert rv['result'] == 'running...'170617071708def test_run_server_port(monkeypatch):1709 rv = {}17101711 # Mocks werkzeug.serving.run_simple method1712 def run_simple_mock(hostname, port, application, *args, **kwargs):1713 rv['result'] = 'running on %s:%s ...' % (hostname, port)17141715 app = flask.Flask(__name__)1716 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1717 hostname, port = 'localhost', 80001718 app.run(hostname, port, debug=True)1719 assert rv['result'] == 'running on %s:%s ...' % (hostname, port)

add test and changelog for SERVER_NAME app.run defaultDavid Lordbefore adoption42fbbb4

lines 1720–1736why, one step back
1720
17211722@pytest.mark.parametrize('host,port,expect_host,expect_port', (1723 (None, None, 'pocoo.org', 8080),1724 ('localhost', None, 'localhost', 8080),1725 (None, 80, 'pocoo.org', 80),1726 ('localhost', 80, 'localhost', 80),1727))1728def test_run_from_config(monkeypatch, host, port, expect_host, expect_port):1729 def run_simple_mock(hostname, port, *args, **kwargs):1730 assert hostname == expect_host1731 assert port == expect_port17321733 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1734 app = flask.Flask(__name__)1735 app.config['SERVER_NAME'] = 'pocoo.org:8080'1736 app.run(host, port)