Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

1,660 lines · 44.0 KiB · Python

Last changed by

Don't passthrough_errors unless instructed. (#2006)Markus Unterwaditzerbefore adoptionc4ec695

History of this file

Take it

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

Merge pull request #1418 from alexwlchan/masterKeyan Pishdadianbefore adoptiondac45f6

lines 1–309why, 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):

Merge pull request #1743 from homoSapiensSapiens/use_pytest_raisesMarkus Unterwaditzerbefore adoptiond45445e

lines 310–311why, one step back
310 e = pytest.raises(RuntimeError, f, *args, **kwargs)
311 assert e.value.args and 'session is unavailable' in e.value.args[0]

Merge pull request #1418 from alexwlchan/masterKeyan Pishdadianbefore adoptiondac45f6

lines 312–851why, one step back
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.headers336 match = re.search(r'\bexpires=([^;]+)(?i)', rv.headers['set-cookie'])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.data769770771def test_before_request_and_routing_errors():772 app = flask.Flask(__name__)773774 @app.before_request775 def attach_something():776 flask.g.something = 'value'777778 @app.errorhandler(404)779 def return_something(error):780 return flask.g.something, 404781 rv = app.test_client().get('/')782 assert rv.status_code == 404783 assert rv.data == b'value'784785786def test_user_error_handling():787 class MyException(Exception):788 pass789790 app = flask.Flask(__name__)791792 @app.errorhandler(MyException)793 def handle_my_exception(e):794 assert isinstance(e, MyException)795 return '42'796797 @app.route('/')798 def index():799 raise MyException()800801 c = app.test_client()802 assert c.get('/').data == b'42'803804805def test_http_error_subclass_handling():806 class ForbiddenSubclass(Forbidden):807 pass808809 app = flask.Flask(__name__)810811 @app.errorhandler(ForbiddenSubclass)812 def handle_forbidden_subclass(e):813 assert isinstance(e, ForbiddenSubclass)814 return 'banana'815816 @app.errorhandler(403)817 def handle_forbidden_subclass(e):818 assert not isinstance(e, ForbiddenSubclass)819 assert isinstance(e, Forbidden)820 return 'apple'821822 @app.route('/1')823 def index1():824 raise ForbiddenSubclass()825826 @app.route('/2')827 def index2():828 flask.abort(403)829830 @app.route('/3')831 def index3():832 raise Forbidden()833834 c = app.test_client()835 assert c.get('/1').data == b'banana'836 assert c.get('/2').data == b'apple'837 assert c.get('/3').data == b'apple'838839840def test_trapping_of_bad_request_key_errors():841 app = flask.Flask(__name__)842 app.testing = True843844 @app.route('/fail')845 def fail():846 flask.request.form['missing_key']847 c = app.test_client()848 assert c.get('/fail').status_code == 400849850 app.config['TRAP_BAD_REQUEST_ERRORS'] = True851 c = app.test_client()

Merge pull request #1743 from homoSapiensSapiens/use_pytest_raisesMarkus Unterwaditzerbefore adoptiond45445e

lines 852–854why, one step back
852 with pytest.raises(KeyError) as e:
853 c.get("/fail")854 assert e.errisinstance(BadRequest)

Merge pull request #1418 from alexwlchan/masterKeyan Pishdadianbefore adoptiondac45f6

lines 855–883why, one step back
855
856857def test_trapping_of_all_http_exceptions():858 app = flask.Flask(__name__)859 app.testing = True860 app.config['TRAP_HTTP_EXCEPTIONS'] = True861862 @app.route('/fail')863 def fail():864 flask.abort(404)865866 c = app.test_client()867 with pytest.raises(NotFound):868 c.get('/fail')869870871def test_enctype_debug_helper():872 from flask.debughelpers import DebugFilesKeyError873 app = flask.Flask(__name__)874 app.debug = True875876 @app.route('/fail', methods=['POST'])877 def index():878 return flask.request.files['foo'].filename879880 # with statement is important because we leave an exception on the881 # stack otherwise and we want to ensure that this is not the case882 # to not negatively affect other tests.883 with app.test_client() as c:

Merge pull request #1743 from homoSapiensSapiens/use_pytest_raisesMarkus Unterwaditzerbefore adoptiond45445e

line 884why, one step back
884 with pytest.raises(DebugFilesKeyError) as e:

Merge pull request #1418 from alexwlchan/masterKeyan Pishdadianbefore adoptiondac45f6

line 885why, one step back
885 c.post('/fail', data={'foo': 'index.txt'})

Merge pull request #1743 from homoSapiensSapiens/use_pytest_raisesMarkus Unterwaditzerbefore adoptiond45445e

lines 886–887why, one step back
886 assert 'no file contents were transmitted' in str(e.value)
887 assert 'This was submitted: "index.txt"' in str(e.value)

Merge pull request #1418 from alexwlchan/masterKeyan Pishdadianbefore adoptiondac45f6

lines 888–1021why, one step back
888
889890def test_response_creation():891 app = flask.Flask(__name__)892893 @app.route('/unicode')894 def from_unicode():895 return u'Hällo Wörld'896897 @app.route('/string')898 def from_string():899 return u'Hällo Wörld'.encode('utf-8')900901 @app.route('/args')902 def from_tuple():903 return 'Meh', 400, {904 'X-Foo': 'Testing',905 'Content-Type': 'text/plain; charset=utf-8'906 }907908 @app.route('/two_args')909 def from_two_args_tuple():910 return 'Hello', {911 'X-Foo': 'Test',912 'Content-Type': 'text/plain; charset=utf-8'913 }914915 @app.route('/args_status')916 def from_status_tuple():917 return 'Hi, status!', 400918919 @app.route('/args_header')920 def from_response_instance_status_tuple():921 return flask.Response('Hello world', 404), {922 "X-Foo": "Bar",923 "X-Bar": "Foo"924 }925926 c = app.test_client()927 assert c.get('/unicode').data == u'Hällo Wörld'.encode('utf-8')928 assert c.get('/string').data == u'Hällo Wörld'.encode('utf-8')929 rv = c.get('/args')930 assert rv.data == b'Meh'931 assert rv.headers['X-Foo'] == 'Testing'932 assert rv.status_code == 400933 assert rv.mimetype == 'text/plain'934 rv2 = c.get('/two_args')935 assert rv2.data == b'Hello'936 assert rv2.headers['X-Foo'] == 'Test'937 assert rv2.status_code == 200938 assert rv2.mimetype == 'text/plain'939 rv3 = c.get('/args_status')940 assert rv3.data == b'Hi, status!'941 assert rv3.status_code == 400942 assert rv3.mimetype == 'text/html'943 rv4 = c.get('/args_header')944 assert rv4.data == b'Hello world'945 assert rv4.headers['X-Foo'] == 'Bar'946 assert rv4.headers['X-Bar'] == 'Foo'947 assert rv4.status_code == 404948949950def test_make_response():951 app = flask.Flask(__name__)952 with app.test_request_context():953 rv = flask.make_response()954 assert rv.status_code == 200955 assert rv.data == b''956 assert rv.mimetype == 'text/html'957958 rv = flask.make_response('Awesome')959 assert rv.status_code == 200960 assert rv.data == b'Awesome'961 assert rv.mimetype == 'text/html'962963 rv = flask.make_response('W00t', 404)964 assert rv.status_code == 404965 assert rv.data == b'W00t'966 assert rv.mimetype == 'text/html'967968969def test_make_response_with_response_instance():970 app = flask.Flask(__name__)971 with app.test_request_context():972 rv = flask.make_response(973 flask.jsonify({'msg': 'W00t'}), 400)974 assert rv.status_code == 400975 assert rv.data == b'{\n "msg": "W00t"\n}\n'976 assert rv.mimetype == 'application/json'977978 rv = flask.make_response(979 flask.Response(''), 400)980 assert rv.status_code == 400981 assert rv.data == b''982 assert rv.mimetype == 'text/html'983984 rv = flask.make_response(985 flask.Response('', headers={'Content-Type': 'text/html'}),986 400, [('X-Foo', 'bar')])987 assert rv.status_code == 400988 assert rv.headers['Content-Type'] == 'text/html'989 assert rv.headers['X-Foo'] == 'bar'990991992def test_jsonify_no_prettyprint():993 app = flask.Flask(__name__)994 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})995 with app.test_request_context():996 compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'997 uncompressed_msg = {998 "msg": {999 "submsg": "W00t"1000 },1001 "msg2": "foobar"1002 }10031004 rv = flask.make_response(1005 flask.jsonify(uncompressed_msg), 200)1006 assert rv.data == compressed_msg100710081009def test_jsonify_prettyprint():1010 app = flask.Flask(__name__)1011 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1012 with app.test_request_context():1013 compressed_msg = {"msg":{"submsg":"W00t"},"msg2":"foobar"}1014 pretty_response =\1015 b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'10161017 rv = flask.make_response(1018 flask.jsonify(compressed_msg), 200)1019 assert rv.data == pretty_response10201021

Add JSONIFY_MIMETYPE configuration variable (#1728)Steven Loriabefore adoption2bf477c

lines 1022–1033why, one step back
1022def test_jsonify_mimetype():
1023 app = flask.Flask(__name__)1024 app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'})1025 with app.test_request_context():1026 msg = {1027 "msg": {"submsg": "W00t"},1028 }1029 rv = flask.make_response(1030 flask.jsonify(msg), 200)1031 assert rv.mimetype == 'application/vnd.api+json'10321033

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

lines 1034–1041why, one step back
1034def test_jsonify_args_and_kwargs_check():
1035 app = flask.Flask(__name__)1036 with app.test_request_context():1037 with pytest.raises(TypeError) as e:1038 flask.jsonify('fake args', kwargs='fake')1039 assert 'behavior undefined' in str(e.value)10401041

Merge pull request #1418 from alexwlchan/masterKeyan Pishdadianbefore adoptiondac45f6

lines 1042–1081why, one step back
1042def test_url_generation():
1043 app = flask.Flask(__name__)10441045 @app.route('/hello/<name>', methods=['POST'])1046 def hello():1047 pass1048 with app.test_request_context():1049 assert flask.url_for('hello', name='test x') == '/hello/test%20x'1050 assert flask.url_for('hello', name='test x', _external=True) == \1051 'http://localhost/hello/test%20x'105210531054def test_build_error_handler():1055 app = flask.Flask(__name__)10561057 # Test base case, a URL which results in a BuildError.1058 with app.test_request_context():1059 pytest.raises(BuildError, flask.url_for, 'spam')10601061 # Verify the error is re-raised if not the current exception.1062 try:1063 with app.test_request_context():1064 flask.url_for('spam')1065 except BuildError as err:1066 error = err1067 try:1068 raise RuntimeError('Test case where BuildError is not current.')1069 except RuntimeError:1070 pytest.raises(1071 BuildError, app.handle_url_build_error, error, 'spam', {})10721073 # Test a custom handler.1074 def handler(error, endpoint, values):1075 # Just a test.1076 return '/test_handler/'1077 app.url_build_error_handlers.append(handler)1078 with app.test_request_context():1079 assert flask.url_for('spam') == '/test_handler/'10801081

Merge branch '0.10-maintenance'Markus Unterwaditzerbefore adoption81ae94a

lines 1082–1093why, one step back
1082def test_build_error_handler_reraise():
1083 app = flask.Flask(__name__)10841085 # Test a custom handler which reraises the BuildError1086 def handler_raises_build_error(error, endpoint, values):1087 raise error1088 app.url_build_error_handlers.append(handler_raises_build_error)10891090 with app.test_request_context():1091 pytest.raises(BuildError, flask.url_for, 'not.existing')10921093

Merge pull request #1418 from alexwlchan/masterKeyan Pishdadianbefore adoptiondac45f6

lines 1094–1126why, one step back
1094def test_custom_converters():
1095 from werkzeug.routing import BaseConverter10961097 class ListConverter(BaseConverter):10981099 def to_python(self, value):1100 return value.split(',')11011102 def to_url(self, value):1103 base_to_url = super(ListConverter, self).to_url1104 return ','.join(base_to_url(x) for x in value)1105 app = flask.Flask(__name__)1106 app.url_map.converters['list'] = ListConverter11071108 @app.route('/<list:args>')1109 def index(args):1110 return '|'.join(args)1111 c = app.test_client()1112 assert c.get('/1,2,3').data == b'1|2|3'111311141115def test_static_files():1116 app = flask.Flask(__name__)1117 app.testing = True1118 rv = app.test_client().get('/static/index.html')1119 assert rv.status_code == 2001120 assert rv.data.strip() == b'<h1>Hello World!</h1>'1121 with app.test_request_context():1122 assert flask.url_for('static', filename='index.html') == \1123 '/static/index.html'1124 rv.close()11251126

Merge pull request #1878 from untitaker/recwarnMarkus Unterwaditzerbefore adoption3d72099

lines 1127–1130why, one step back
1127def test_static_path_deprecated(recwarn):
1128 app = flask.Flask(__name__, static_path='/foo')1129 recwarn.pop(DeprecationWarning)1130

Coverage for test_static_path_deprecated and test_static_url_path (#1860)jphilipsen05before adoption047efac

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

Merge pull request #1878 from untitaker/recwarnMarkus Unterwaditzerbefore adoption3d72099

lines 1134–1135why, one step back
1134 rv.close()
1135

Coverage for test_static_path_deprecated and test_static_url_path (#1860)jphilipsen05before adoption047efac

lines 1136–1144why, one step back
1136 with app.test_request_context():
1137 assert flask.url_for('static', filename='index.html') == '/foo/index.html'113811391140def test_static_url_path():1141 app = flask.Flask(__name__, static_url_path='/foo')1142 app.testing = True1143 rv = app.test_client().get('/foo/index.html')1144 assert rv.status_code == 200

Merge pull request #1878 from untitaker/recwarnMarkus Unterwaditzerbefore adoption3d72099

lines 1145–1146why, one step back
1145 rv.close()
1146

Coverage for test_static_path_deprecated and test_static_url_path (#1860)jphilipsen05before adoption047efac

lines 1147–1150why, one step back
1147 with app.test_request_context():
1148 assert flask.url_for('static', filename='index.html') == '/foo/index.html'11491150

Merge pull request #1418 from alexwlchan/masterKeyan Pishdadianbefore adoptiondac45f6

lines 1151–1239why, one step back
1151def test_none_response():
1152 app = flask.Flask(__name__)1153 app.testing = True11541155 @app.route('/')1156 def test():1157 return None1158 try:1159 app.test_client().get('/')1160 except ValueError as e:1161 assert str(e) == 'View function did not return a response'1162 pass1163 else:1164 assert "Expected ValueError"116511661167def test_request_locals():1168 assert repr(flask.g) == '<LocalProxy unbound>'1169 assert not flask.g117011711172def test_test_app_proper_environ():1173 app = flask.Flask(__name__)1174 app.config.update(1175 SERVER_NAME='localhost.localdomain:5000'1176 )11771178 @app.route('/')1179 def index():1180 return 'Foo'11811182 @app.route('/', subdomain='foo')1183 def subdomain():1184 return 'Foo SubDomain'11851186 rv = app.test_client().get('/')1187 assert rv.data == b'Foo'11881189 rv = app.test_client().get('/', 'http://localhost.localdomain:5000')1190 assert rv.data == b'Foo'11911192 rv = app.test_client().get('/', 'https://localhost.localdomain:5000')1193 assert rv.data == b'Foo'11941195 app.config.update(SERVER_NAME='localhost.localdomain')1196 rv = app.test_client().get('/', 'https://localhost.localdomain')1197 assert rv.data == b'Foo'11981199 try:1200 app.config.update(SERVER_NAME='localhost.localdomain:443')1201 rv = app.test_client().get('/', 'https://localhost.localdomain')1202 # Werkzeug 0.81203 assert rv.status_code == 4041204 except ValueError as e:1205 # Werkzeug 0.71206 assert str(e) == (1207 "the server name provided "1208 "('localhost.localdomain:443') does not match the "1209 "server name from the WSGI environment ('localhost.localdomain')"1210 )12111212 try:1213 app.config.update(SERVER_NAME='localhost.localdomain')1214 rv = app.test_client().get('/', 'http://foo.localhost')1215 # Werkzeug 0.81216 assert rv.status_code == 4041217 except ValueError as e:1218 # Werkzeug 0.71219 assert str(e) == (1220 "the server name provided "1221 "('localhost.localdomain') does not match the "1222 "server name from the WSGI environment ('foo.localhost')"1223 )12241225 rv = app.test_client().get('/', 'http://foo.localhost.localdomain')1226 assert rv.data == b'Foo SubDomain'122712281229def test_exception_propagation():1230 def apprunner(config_key):1231 app = flask.Flask(__name__)1232 app.config['LOGGER_HANDLER_POLICY'] = 'never'12331234 @app.route('/')1235 def index():1236 1 // 01237 c = app.test_client()1238 if config_key is not None:1239 app.config[config_key] = True

Merge pull request #1743 from homoSapiensSapiens/use_pytest_raisesMarkus Unterwaditzerbefore adoptiond45445e

line 1240why, one step back
1240 with pytest.raises(Exception):

Merge pull request #1418 from alexwlchan/masterKeyan Pishdadianbefore adoptiondac45f6

lines 1241–1254why, one step back
1241 c.get('/')
1242 else:1243 assert c.get('/').status_code == 50012441245 # we have to run this test in an isolated thread because if the1246 # debug flag is set to true and an exception happens the context is1247 # not torn down. This causes other tests that run after this fail1248 # when they expect no exception on the stack.1249 for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None:1250 t = Thread(target=apprunner, args=(config_key,))1251 t.start()1252 t.join()12531254

Merge pull request #1679 from miguelgrinberg/passthrough-errorsDavid Lordbefore adoption7b1ebfb

lines 1255–1272why, one step back
1255@pytest.mark.parametrize('debug', [True, False])
1256@pytest.mark.parametrize('use_debugger', [True, False])1257@pytest.mark.parametrize('use_reloader', [True, False])1258@pytest.mark.parametrize('propagate_exceptions', [None, True, False])1259def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1260 use_reloader, propagate_exceptions):1261 rv = {}12621263 # Mocks werkzeug.serving.run_simple method1264 def run_simple_mock(*args, **kwargs):1265 rv['passthrough_errors'] = kwargs.get('passthrough_errors')12661267 app = flask.Flask(__name__)1268 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1269 app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1270 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)12711272

Merge pull request #1418 from alexwlchan/masterKeyan Pishdadianbefore adoptiondac45f6

lines 1273–1375why, one step back
1273def test_max_content_length():
1274 app = flask.Flask(__name__)1275 app.config['MAX_CONTENT_LENGTH'] = 6412761277 @app.before_request1278 def always_first():1279 flask.request.form['myfile']1280 assert False12811282 @app.route('/accept', methods=['POST'])1283 def accept_file():1284 flask.request.form['myfile']1285 assert False12861287 @app.errorhandler(413)1288 def catcher(error):1289 return '42'12901291 c = app.test_client()1292 rv = c.post('/accept', data={'myfile': 'foo' * 100})1293 assert rv.data == b'42'129412951296def test_url_processors():1297 app = flask.Flask(__name__)12981299 @app.url_defaults1300 def add_language_code(endpoint, values):1301 if flask.g.lang_code is not None and \1302 app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1303 values.setdefault('lang_code', flask.g.lang_code)13041305 @app.url_value_preprocessor1306 def pull_lang_code(endpoint, values):1307 flask.g.lang_code = values.pop('lang_code', None)13081309 @app.route('/<lang_code>/')1310 def index():1311 return flask.url_for('about')13121313 @app.route('/<lang_code>/about')1314 def about():1315 return flask.url_for('something_else')13161317 @app.route('/foo')1318 def something_else():1319 return flask.url_for('about', lang_code='en')13201321 c = app.test_client()13221323 assert c.get('/de/').data == b'/de/about'1324 assert c.get('/de/about').data == b'/foo'1325 assert c.get('/foo').data == b'/en/about'132613271328def test_inject_blueprint_url_defaults():1329 app = flask.Flask(__name__)1330 bp = flask.Blueprint('foo.bar.baz', __name__,1331 template_folder='template')13321333 @bp.url_defaults1334 def bp_defaults(endpoint, values):1335 values['page'] = 'login'13361337 @bp.route('/<page>')1338 def view(page):1339 pass13401341 app.register_blueprint(bp)13421343 values = dict()1344 app.inject_url_defaults('foo.bar.baz.view', values)1345 expected = dict(page='login')1346 assert values == expected13471348 with app.test_request_context('/somepage'):1349 url = flask.url_for('foo.bar.baz.view')1350 expected = '/login'1351 assert url == expected135213531354def test_nonascii_pathinfo():1355 app = flask.Flask(__name__)1356 app.testing = True13571358 @app.route(u'/киртест')1359 def index():1360 return 'Hello World!'13611362 c = app.test_client()1363 rv = c.get(u'/киртест')1364 assert rv.data == b'Hello World!'136513661367def test_debug_mode_complains_after_first_request():1368 app = flask.Flask(__name__)1369 app.debug = True13701371 @app.route('/')1372 def index():1373 return 'Awesome'1374 assert not app.got_first_request1375 assert app.test_client().get('/').data == b'Awesome'

Merge pull request #1743 from homoSapiensSapiens/use_pytest_raisesMarkus Unterwaditzerbefore adoptiond45445e

line 1376why, one step back
1376 with pytest.raises(AssertionError) as e:

Merge pull request #1418 from alexwlchan/masterKeyan Pishdadianbefore adoptiondac45f6

lines 1377–1379why, one step back
1377 @app.route('/foo')
1378 def broken():1379 return 'Meh'

Merge pull request #1743 from homoSapiensSapiens/use_pytest_raisesMarkus Unterwaditzerbefore adoptiond45445e

line 1380why, one step back
1380 assert 'A setup function was called' in str(e)

Merge pull request #1418 from alexwlchan/masterKeyan Pishdadianbefore adoptiondac45f6

lines 1381–1435why, one step back
1381
1382 app.debug = False13831384 @app.route('/foo')1385 def working():1386 return 'Meh'1387 assert app.test_client().get('/foo').data == b'Meh'1388 assert app.got_first_request138913901391def test_before_first_request_functions():1392 got = []1393 app = flask.Flask(__name__)13941395 @app.before_first_request1396 def foo():1397 got.append(42)1398 c = app.test_client()1399 c.get('/')1400 assert got == [42]1401 c.get('/')1402 assert got == [42]1403 assert app.got_first_request140414051406def test_before_first_request_functions_concurrent():1407 got = []1408 app = flask.Flask(__name__)14091410 @app.before_first_request1411 def foo():1412 time.sleep(0.2)1413 got.append(42)14141415 c = app.test_client()14161417 def get_and_assert():1418 c.get("/")1419 assert got == [42]14201421 t = Thread(target=get_and_assert)1422 t.start()1423 get_and_assert()1424 t.join()1425 assert app.got_first_request142614271428def test_routing_redirect_debugging():1429 app = flask.Flask(__name__)1430 app.debug = True14311432 @app.route('/foo/', methods=['GET', 'POST'])1433 def foo():1434 return 'success'1435 with app.test_client() as c:

Merge pull request #1743 from homoSapiensSapiens/use_pytest_raisesMarkus Unterwaditzerbefore adoptiond45445e

line 1436why, one step back
1436 with pytest.raises(AssertionError) as e:

Merge pull request #1418 from alexwlchan/masterKeyan Pishdadianbefore adoptiondac45f6

line 1437why, one step back
1437 c.post('/foo', data={})

Merge pull request #1743 from homoSapiensSapiens/use_pytest_raisesMarkus Unterwaditzerbefore adoptiond45445e

lines 1438–1440why, one step back
1438 assert 'http://localhost/foo/' in str(e)
1439 assert ('Make sure to directly send '1440 'your POST-request to this URL') in str(e)

Merge pull request #1418 from alexwlchan/masterKeyan Pishdadianbefore adoptiondac45f6

lines 1441–1660why, one step back
1441
1442 rv = c.get('/foo', data={}, follow_redirects=True)1443 assert rv.data == b'success'14441445 app.debug = False1446 with app.test_client() as c:1447 rv = c.post('/foo', data={}, follow_redirects=True)1448 assert rv.data == b'success'144914501451def test_route_decorator_custom_endpoint():1452 app = flask.Flask(__name__)1453 app.debug = True14541455 @app.route('/foo/')1456 def foo():1457 return flask.request.endpoint14581459 @app.route('/bar/', endpoint='bar')1460 def for_bar():1461 return flask.request.endpoint14621463 @app.route('/bar/123', endpoint='123')1464 def for_bar_foo():1465 return flask.request.endpoint14661467 with app.test_request_context():1468 assert flask.url_for('foo') == '/foo/'1469 assert flask.url_for('bar') == '/bar/'1470 assert flask.url_for('123') == '/bar/123'14711472 c = app.test_client()1473 assert c.get('/foo/').data == b'foo'1474 assert c.get('/bar/').data == b'bar'1475 assert c.get('/bar/123').data == b'123'147614771478def test_preserve_only_once():1479 app = flask.Flask(__name__)1480 app.debug = True14811482 @app.route('/fail')1483 def fail_func():1484 1 // 014851486 c = app.test_client()1487 for x in range(3):1488 with pytest.raises(ZeroDivisionError):1489 c.get('/fail')14901491 assert flask._request_ctx_stack.top is not None1492 assert flask._app_ctx_stack.top is not None1493 # implicit appctx disappears too1494 flask._request_ctx_stack.top.pop()1495 assert flask._request_ctx_stack.top is None1496 assert flask._app_ctx_stack.top is None149714981499def test_preserve_remembers_exception():1500 app = flask.Flask(__name__)1501 app.debug = True1502 errors = []15031504 @app.route('/fail')1505 def fail_func():1506 1 // 015071508 @app.route('/success')1509 def success_func():1510 return 'Okay'15111512 @app.teardown_request1513 def teardown_handler(exc):1514 errors.append(exc)15151516 c = app.test_client()15171518 # After this failure we did not yet call the teardown handler1519 with pytest.raises(ZeroDivisionError):1520 c.get('/fail')1521 assert errors == []15221523 # But this request triggers it, and it's an error1524 c.get('/success')1525 assert len(errors) == 21526 assert isinstance(errors[0], ZeroDivisionError)15271528 # At this point another request does nothing.1529 c.get('/success')1530 assert len(errors) == 31531 assert errors[1] is None153215331534def test_get_method_on_g():1535 app = flask.Flask(__name__)1536 app.testing = True15371538 with app.app_context():1539 assert flask.g.get('x') is None1540 assert flask.g.get('x', 11) == 111541 flask.g.x = 421542 assert flask.g.get('x') == 421543 assert flask.g.x == 42154415451546def test_g_iteration_protocol():1547 app = flask.Flask(__name__)1548 app.testing = True15491550 with app.app_context():1551 flask.g.foo = 231552 flask.g.bar = 421553 assert 'foo' in flask.g1554 assert 'foos' not in flask.g1555 assert sorted(flask.g) == ['bar', 'foo']155615571558def test_subdomain_basic_support():1559 app = flask.Flask(__name__)1560 app.config['SERVER_NAME'] = 'localhost'15611562 @app.route('/')1563 def normal_index():1564 return 'normal index'15651566 @app.route('/', subdomain='test')1567 def test_index():1568 return 'test index'15691570 c = app.test_client()1571 rv = c.get('/', 'http://localhost/')1572 assert rv.data == b'normal index'15731574 rv = c.get('/', 'http://test.localhost/')1575 assert rv.data == b'test index'157615771578def test_subdomain_matching():1579 app = flask.Flask(__name__)1580 app.config['SERVER_NAME'] = 'localhost'15811582 @app.route('/', subdomain='<user>')1583 def index(user):1584 return 'index for %s' % user15851586 c = app.test_client()1587 rv = c.get('/', 'http://mitsuhiko.localhost/')1588 assert rv.data == b'index for mitsuhiko'158915901591def test_subdomain_matching_with_ports():1592 app = flask.Flask(__name__)1593 app.config['SERVER_NAME'] = 'localhost:3000'15941595 @app.route('/', subdomain='<user>')1596 def index(user):1597 return 'index for %s' % user15981599 c = app.test_client()1600 rv = c.get('/', 'http://mitsuhiko.localhost:3000/')1601 assert rv.data == b'index for mitsuhiko'160216031604def test_multi_route_rules():1605 app = flask.Flask(__name__)16061607 @app.route('/')1608 @app.route('/<test>/')1609 def index(test='a'):1610 return test16111612 rv = app.test_client().open('/')1613 assert rv.data == b'a'1614 rv = app.test_client().open('/b/')1615 assert rv.data == b'b'161616171618def test_multi_route_class_views():1619 class View(object):16201621 def __init__(self, app):1622 app.add_url_rule('/', 'index', self.index)1623 app.add_url_rule('/<test>/', 'index', self.index)16241625 def index(self, test='a'):1626 return test16271628 app = flask.Flask(__name__)1629 _ = View(app)1630 rv = app.test_client().open('/')1631 assert rv.data == b'a'1632 rv = app.test_client().open('/b/')1633 assert rv.data == b'b'163416351636def test_run_defaults(monkeypatch):1637 rv = {}16381639 # Mocks werkzeug.serving.run_simple method1640 def run_simple_mock(*args, **kwargs):1641 rv['result'] = 'running...'16421643 app = flask.Flask(__name__)1644 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1645 app.run()1646 assert rv['result'] == 'running...'164716481649def test_run_server_port(monkeypatch):1650 rv = {}16511652 # Mocks werkzeug.serving.run_simple method1653 def run_simple_mock(hostname, port, application, *args, **kwargs):1654 rv['result'] = 'running on %s:%s ...' % (hostname, port)16551656 app = flask.Flask(__name__)1657 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1658 hostname, port = 'localhost', 80001659 app.run(hostname, port, debug=True)1660 assert rv['result'] == 'running on %s:%s ...' % (hostname, port)