Skip to content
Myr

test_helpers.py

This file

Path

tests/test_helpers.py

739 lines · 26.4 KiB · Python

Last changed by

Revert "Adds simplejson as a testing target." (#1865)David Lordbefore adoption024fbe5

History of this file

Take it

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

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

lines 1–7why, one step back
1# -*- coding: utf-8 -*-
2"""3 tests.helpers4 ~~~~~~~~~~~~~~~~~~~~~~~56 Various helpers.7

Merge pull request #1303 from Parkayun/masterMarkus Unterwaditzerbefore adoption5b98266

line 8why, one step back
8 :copyright: (c) 2015 by Armin Ronacher.

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

lines 9–14why, one step back
9 :license: BSD, see LICENSE for more details.
10"""1112import pytest1314import os

Merge branch 'date-support-in-jsonify'Markus Unterwaditzerbefore adoption495704e

line 15why, one step back
15import datetime

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

lines 16–17why, one step back
16import flask
17from logging import StreamHandler

Raise BadRequest if static file name is invalidDavid Houbefore adoption9f1be8e

line 18why, one step back
18from werkzeug.exceptions import BadRequest

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

line 19why, one step back
19from werkzeug.http import parse_cache_control_header, parse_options_header

Merge branch 'date-support-in-jsonify'Markus Unterwaditzerbefore adoption495704e

line 20why, one step back
20from werkzeug.http import http_date

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

lines 21–33why, one step back
21from flask._compat import StringIO, text_type
222324def has_encoding(name):25 try:26 import codecs27 codecs.lookup(name)28 return True29 except LookupError:30 return False313233class TestJSON(object):

Merge branch 'date-support-in-jsonify'Markus Unterwaditzerbefore adoption495704e

line 34why, one step back
34

Merge pull request #1360 from keyanp/issue1317Markus Unterwaditzerbefore adoption5164be0

lines 35–58why, one step back
35 def test_post_empty_json_adds_exception_to_response_content_in_debug(self):
36 app = flask.Flask(__name__)37 app.config['DEBUG'] = True38 @app.route('/json', methods=['POST'])39 def post_json():40 flask.request.get_json()41 return None42 c = app.test_client()43 rv = c.post('/json', data=None, content_type='application/json')44 assert rv.status_code == 40045 assert b'Failed to decode JSON object' in rv.data4647 def test_post_empty_json_wont_add_exception_to_response_if_no_debug(self):48 app = flask.Flask(__name__)49 app.config['DEBUG'] = False50 @app.route('/json', methods=['POST'])51 def post_json():52 flask.request.get_json()53 return None54 c = app.test_client()55 rv = c.post('/json', data=None, content_type='application/json')56 assert rv.status_code == 40057 assert b'Failed to decode JSON object' not in rv.data58

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

lines 59–88why, one step back
59 def test_json_bad_requests(self):
60 app = flask.Flask(__name__)61 @app.route('/json', methods=['POST'])62 def return_json():63 return flask.jsonify(foo=text_type(flask.request.get_json()))64 c = app.test_client()65 rv = c.post('/json', data='malformed', content_type='application/json')66 assert rv.status_code == 4006768 def test_json_custom_mimetypes(self):69 app = flask.Flask(__name__)70 @app.route('/json', methods=['POST'])71 def return_json():72 return flask.request.get_json()73 c = app.test_client()74 rv = c.post('/json', data='"foo"', content_type='application/x+json')75 assert rv.data == b'foo'7677 def test_json_body_encoding(self):78 app = flask.Flask(__name__)79 app.testing = True80 @app.route('/')81 def index():82 return flask.request.get_json()8384 c = app.test_client()85 resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),86 content_type='application/json; charset=iso-8859-15')87 assert resp.data == u'Hällo Wörld'.encode('utf-8')88

Merge pull request #1671 from jeffwidman/support-json-top-level-arraysDavid Lordbefore adoption431db28

line 89why, one step back
89 def test_json_as_unicode(self):

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

line 90why, one step back
90 app = flask.Flask(__name__)

Merge pull request #1671 from jeffwidman/support-json-top-level-arraysDavid Lordbefore adoption431db28

lines 91–124why, one step back
91
92 app.config['JSON_AS_ASCII'] = True93 with app.app_context():94 rv = flask.json.dumps(u'\N{SNOWMAN}')95 assert rv == '"\\u2603"'9697 app.config['JSON_AS_ASCII'] = False98 with app.app_context():99 rv = flask.json.dumps(u'\N{SNOWMAN}')100 assert rv == u'"\u2603"'101102 def test_jsonify_basic_types(self):103 """Test jsonify with basic types."""104 # Should be able to use pytest parametrize on this, but I couldn't105 # figure out the correct syntax106 # https://pytest.org/latest/parametrize.html#pytest-mark-parametrize-parametrizing-test-functions107 test_data = (0, 1, 23, 3.14, 's', "longer string", True, False,)108 app = flask.Flask(__name__)109 c = app.test_client()110 for i, d in enumerate(test_data):111 url = '/jsonify_basic_types{0}'.format(i)112 app.add_url_rule(url, str(i), lambda x=d: flask.jsonify(x))113 rv = c.get(url)114 assert rv.mimetype == 'application/json'115 assert flask.json.loads(rv.data) == d116117 def test_jsonify_dicts(self):118 """Test jsonify with dicts and kwargs unpacking."""119 d = dict(120 a=0, b=23, c=3.14, d='t', e='Hi', f=True, g=False,121 h=['test list', 10, False],122 i={'test':'dict'}123 )124 app = flask.Flask(__name__)

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

lines 125–136why, one step back
125 @app.route('/kw')
126 def return_kwargs():127 return flask.jsonify(**d)128 @app.route('/dict')129 def return_dict():130 return flask.jsonify(d)131 c = app.test_client()132 for url in '/kw', '/dict':133 rv = c.get(url)134 assert rv.mimetype == 'application/json'135 assert flask.json.loads(rv.data) == d136

Merge pull request #1671 from jeffwidman/support-json-top-level-arraysDavid Lordbefore adoption431db28

lines 137–143why, one step back
137 def test_jsonify_arrays(self):
138 """Test jsonify of lists and args unpacking."""139 l = [140 0, 42, 3.14, 't', 'hello', True, False,141 ['test list', 2, False],142 {'test':'dict'}143 ]

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

line 144why, one step back
144 app = flask.Flask(__name__)

Merge pull request #1671 from jeffwidman/support-json-top-level-arraysDavid Lordbefore adoption431db28

lines 145–155why, one step back
145 @app.route('/args_unpack')
146 def return_args_unpack():147 return flask.jsonify(*l)148 @app.route('/array')149 def return_array():150 return flask.jsonify(l)151 c = app.test_client()152 for url in '/args_unpack', '/array':153 rv = c.get(url)154 assert rv.mimetype == 'application/json'155 assert flask.json.loads(rv.data) == l

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

line 156why, one step back
156

Merge pull request #1671 from jeffwidman/support-json-top-level-arraysDavid Lordbefore adoption431db28

lines 157–158why, one step back
157 def test_jsonify_date_types(self):
158 """Test jsonify with datetime.date and datetime.datetime types."""

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

line 159why, one step back
159

Merge pull request #1671 from jeffwidman/support-json-top-level-arraysDavid Lordbefore adoption431db28

lines 160–173why, one step back
160 test_dates = (
161 datetime.datetime(1973, 3, 11, 6, 30, 45),162 datetime.date(1975, 1, 5)163 )164165 app = flask.Flask(__name__)166 c = app.test_client()167168 for i, d in enumerate(test_dates):169 url = '/datetest{0}'.format(i)170 app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val))171 rv = c.get(url)172 assert rv.mimetype == 'application/json'173 assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple())

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

lines 174–507why, one step back
174
175 def test_json_attr(self):176 app = flask.Flask(__name__)177 @app.route('/add', methods=['POST'])178 def add():179 json = flask.request.get_json()180 return text_type(json['a'] + json['b'])181 c = app.test_client()182 rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),183 content_type='application/json')184 assert rv.data == b'3'185186 def test_template_escaping(self):187 app = flask.Flask(__name__)188 render = flask.render_template_string189 with app.test_request_context():190 rv = flask.json.htmlsafe_dumps('</script>')191 assert rv == u'"\\u003c/script\\u003e"'192 assert type(rv) == text_type193 rv = render('{{ "</script>"|tojson }}')194 assert rv == '"\\u003c/script\\u003e"'195 rv = render('{{ "<\0/script>"|tojson }}')196 assert rv == '"\\u003c\\u0000/script\\u003e"'197 rv = render('{{ "<!--<script>"|tojson }}')198 assert rv == '"\\u003c!--\\u003cscript\\u003e"'199 rv = render('{{ "&"|tojson }}')200 assert rv == '"\\u0026"'201 rv = render('{{ "\'"|tojson }}')202 assert rv == '"\\u0027"'203 rv = render("<a ng-data='{{ data|tojson }}'></a>",204 data={'x': ["foo", "bar", "baz'"]})205 assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'206207 def test_json_customization(self):208 class X(object):209 def __init__(self, val):210 self.val = val211 class MyEncoder(flask.json.JSONEncoder):212 def default(self, o):213 if isinstance(o, X):214 return '<%d>' % o.val215 return flask.json.JSONEncoder.default(self, o)216 class MyDecoder(flask.json.JSONDecoder):217 def __init__(self, *args, **kwargs):218 kwargs.setdefault('object_hook', self.object_hook)219 flask.json.JSONDecoder.__init__(self, *args, **kwargs)220 def object_hook(self, obj):221 if len(obj) == 1 and '_foo' in obj:222 return X(obj['_foo'])223 return obj224 app = flask.Flask(__name__)225 app.testing = True226 app.json_encoder = MyEncoder227 app.json_decoder = MyDecoder228 @app.route('/', methods=['POST'])229 def index():230 return flask.json.dumps(flask.request.get_json()['x'])231 c = app.test_client()232 rv = c.post('/', data=flask.json.dumps({233 'x': {'_foo': 42}234 }), content_type='application/json')235 assert rv.data == b'"<42>"'236237 def test_modified_url_encoding(self):238 class ModifiedRequest(flask.Request):239 url_charset = 'euc-kr'240 app = flask.Flask(__name__)241 app.testing = True242 app.request_class = ModifiedRequest243 app.url_map.charset = 'euc-kr'244245 @app.route('/')246 def index():247 return flask.request.args['foo']248249 rv = app.test_client().get(u'/?foo=정상처리'.encode('euc-kr'))250 assert rv.status_code == 200251 assert rv.data == u'정상처리'.encode('utf-8')252253 if not has_encoding('euc-kr'):254 test_modified_url_encoding = None255256 def test_json_key_sorting(self):257 app = flask.Flask(__name__)258 app.testing = True259 assert app.config['JSON_SORT_KEYS'] == True260 d = dict.fromkeys(range(20), 'foo')261262 @app.route('/')263 def index():264 return flask.jsonify(values=d)265266 c = app.test_client()267 rv = c.get('/')268 lines = [x.strip() for x in rv.data.strip().decode('utf-8').splitlines()]269 sorted_by_str = [270 '{',271 '"values": {',272 '"0": "foo",',273 '"1": "foo",',274 '"10": "foo",',275 '"11": "foo",',276 '"12": "foo",',277 '"13": "foo",',278 '"14": "foo",',279 '"15": "foo",',280 '"16": "foo",',281 '"17": "foo",',282 '"18": "foo",',283 '"19": "foo",',284 '"2": "foo",',285 '"3": "foo",',286 '"4": "foo",',287 '"5": "foo",',288 '"6": "foo",',289 '"7": "foo",',290 '"8": "foo",',291 '"9": "foo"',292 '}',293 '}'294 ]295 sorted_by_int = [296 '{',297 '"values": {',298 '"0": "foo",',299 '"1": "foo",',300 '"2": "foo",',301 '"3": "foo",',302 '"4": "foo",',303 '"5": "foo",',304 '"6": "foo",',305 '"7": "foo",',306 '"8": "foo",',307 '"9": "foo",',308 '"10": "foo",',309 '"11": "foo",',310 '"12": "foo",',311 '"13": "foo",',312 '"14": "foo",',313 '"15": "foo",',314 '"16": "foo",',315 '"17": "foo",',316 '"18": "foo",',317 '"19": "foo"',318 '}',319 '}'320 ]321322 try:323 assert lines == sorted_by_int324 except AssertionError:325 assert lines == sorted_by_str326327class TestSendfile(object):328329 def test_send_file_regular(self):330 app = flask.Flask(__name__)331 with app.test_request_context():332 rv = flask.send_file('static/index.html')333 assert rv.direct_passthrough334 assert rv.mimetype == 'text/html'335 with app.open_resource('static/index.html') as f:336 rv.direct_passthrough = False337 assert rv.data == f.read()338 rv.close()339340 def test_send_file_xsendfile(self):341 app = flask.Flask(__name__)342 app.use_x_sendfile = True343 with app.test_request_context():344 rv = flask.send_file('static/index.html')345 assert rv.direct_passthrough346 assert 'x-sendfile' in rv.headers347 assert rv.headers['x-sendfile'] == \348 os.path.join(app.root_path, 'static/index.html')349 assert rv.mimetype == 'text/html'350 rv.close()351352 def test_send_file_object(self, catch_deprecation_warnings):353 app = flask.Flask(__name__)354 with catch_deprecation_warnings() as captured:355 with app.test_request_context():356 f = open(os.path.join(app.root_path, 'static/index.html'), mode='rb')357 rv = flask.send_file(f)358 rv.direct_passthrough = False359 with app.open_resource('static/index.html') as f:360 assert rv.data == f.read()361 assert rv.mimetype == 'text/html'362 rv.close()363 # mimetypes + etag364 assert len(captured) == 2365366 app.use_x_sendfile = True367 with catch_deprecation_warnings() as captured:368 with app.test_request_context():369 f = open(os.path.join(app.root_path, 'static/index.html'))370 rv = flask.send_file(f)371 assert rv.mimetype == 'text/html'372 assert 'x-sendfile' in rv.headers373 assert rv.headers['x-sendfile'] == \374 os.path.join(app.root_path, 'static/index.html')375 rv.close()376 # mimetypes + etag377 assert len(captured) == 2378379 app.use_x_sendfile = False380 with app.test_request_context():381 with catch_deprecation_warnings() as captured:382 f = StringIO('Test')383 rv = flask.send_file(f)384 rv.direct_passthrough = False385 assert rv.data == b'Test'386 assert rv.mimetype == 'application/octet-stream'387 rv.close()388 # etags389 assert len(captured) == 1390 with catch_deprecation_warnings() as captured:391 class PyStringIO(object):392 def __init__(self, *args, **kwargs):393 self._io = StringIO(*args, **kwargs)394 def __getattr__(self, name):395 return getattr(self._io, name)396 f = PyStringIO('Test')397 f.name = 'test.txt'398 rv = flask.send_file(f)399 rv.direct_passthrough = False400 assert rv.data == b'Test'401 assert rv.mimetype == 'text/plain'402 rv.close()403 # attachment_filename and etags404 assert len(captured) == 3405 with catch_deprecation_warnings() as captured:406 f = StringIO('Test')407 rv = flask.send_file(f, mimetype='text/plain')408 rv.direct_passthrough = False409 assert rv.data == b'Test'410 assert rv.mimetype == 'text/plain'411 rv.close()412 # etags413 assert len(captured) == 1414415 app.use_x_sendfile = True416 with catch_deprecation_warnings() as captured:417 with app.test_request_context():418 f = StringIO('Test')419 rv = flask.send_file(f)420 assert 'x-sendfile' not in rv.headers421 rv.close()422 # etags423 assert len(captured) == 1424425 def test_attachment(self, catch_deprecation_warnings):426 app = flask.Flask(__name__)427 with catch_deprecation_warnings() as captured:428 with app.test_request_context():429 f = open(os.path.join(app.root_path, 'static/index.html'))430 rv = flask.send_file(f, as_attachment=True)431 value, options = parse_options_header(rv.headers['Content-Disposition'])432 assert value == 'attachment'433 rv.close()434 # mimetypes + etag435 assert len(captured) == 2436437 with app.test_request_context():438 assert options['filename'] == 'index.html'439 rv = flask.send_file('static/index.html', as_attachment=True)440 value, options = parse_options_header(rv.headers['Content-Disposition'])441 assert value == 'attachment'442 assert options['filename'] == 'index.html'443 rv.close()444445 with app.test_request_context():446 rv = flask.send_file(StringIO('Test'), as_attachment=True,447 attachment_filename='index.txt',448 add_etags=False)449 assert rv.mimetype == 'text/plain'450 value, options = parse_options_header(rv.headers['Content-Disposition'])451 assert value == 'attachment'452 assert options['filename'] == 'index.txt'453 rv.close()454455 def test_static_file(self):456 app = flask.Flask(__name__)457 # default cache timeout is 12 hours458 with app.test_request_context():459 # Test with static file handler.460 rv = app.send_static_file('index.html')461 cc = parse_cache_control_header(rv.headers['Cache-Control'])462 assert cc.max_age == 12 * 60 * 60463 rv.close()464 # Test again with direct use of send_file utility.465 rv = flask.send_file('static/index.html')466 cc = parse_cache_control_header(rv.headers['Cache-Control'])467 assert cc.max_age == 12 * 60 * 60468 rv.close()469 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600470 with app.test_request_context():471 # Test with static file handler.472 rv = app.send_static_file('index.html')473 cc = parse_cache_control_header(rv.headers['Cache-Control'])474 assert cc.max_age == 3600475 rv.close()476 # Test again with direct use of send_file utility.477 rv = flask.send_file('static/index.html')478 cc = parse_cache_control_header(rv.headers['Cache-Control'])479 assert cc.max_age == 3600480 rv.close()481 class StaticFileApp(flask.Flask):482 def get_send_file_max_age(self, filename):483 return 10484 app = StaticFileApp(__name__)485 with app.test_request_context():486 # Test with static file handler.487 rv = app.send_static_file('index.html')488 cc = parse_cache_control_header(rv.headers['Cache-Control'])489 assert cc.max_age == 10490 rv.close()491 # Test again with direct use of send_file utility.492 rv = flask.send_file('static/index.html')493 cc = parse_cache_control_header(rv.headers['Cache-Control'])494 assert cc.max_age == 10495 rv.close()496497 def test_send_from_directory(self):498 app = flask.Flask(__name__)499 app.testing = True500 app.root_path = os.path.join(os.path.dirname(__file__),501 'test_apps', 'subdomaintestmodule')502 with app.test_request_context():503 rv = flask.send_from_directory('static', 'hello.txt')504 rv.direct_passthrough = False505 assert rv.data.strip() == b'Hello Subdomain'506 rv.close()507

Raise BadRequest if static file name is invalidDavid Houbefore adoption9f1be8e

lines 508–515why, one step back
508 def test_send_from_directory_bad_request(self):
509 app = flask.Flask(__name__)510 app.testing = True511 app.root_path = os.path.join(os.path.dirname(__file__),512 'test_apps', 'subdomaintestmodule')513 with app.test_request_context():514 with pytest.raises(BadRequest):515 flask.send_from_directory('static', 'bad\x00')

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

lines 516–629why, one step back
516
517class TestLogging(object):518519 def test_logger_cache(self):520 app = flask.Flask(__name__)521 logger1 = app.logger522 assert app.logger is logger1523 assert logger1.name == __name__524 app.logger_name = __name__ + '/test_logger_cache'525 assert app.logger is not logger1526527 def test_debug_log(self, capsys):528 app = flask.Flask(__name__)529 app.debug = True530531 @app.route('/')532 def index():533 app.logger.warning('the standard library is dead')534 app.logger.debug('this is a debug statement')535 return ''536537 @app.route('/exc')538 def exc():539 1 // 0540541 with app.test_client() as c:542 c.get('/')543 out, err = capsys.readouterr()544 assert 'WARNING in test_helpers [' in err545 assert os.path.basename(__file__.rsplit('.', 1)[0] + '.py') in err546 assert 'the standard library is dead' in err547 assert 'this is a debug statement' in err548549 with pytest.raises(ZeroDivisionError):550 c.get('/exc')551552 def test_debug_log_override(self):553 app = flask.Flask(__name__)554 app.debug = True555 app.logger_name = 'flask_tests/test_debug_log_override'556 app.logger.level = 10557 assert app.logger.level == 10558559 def test_exception_logging(self):560 out = StringIO()561 app = flask.Flask(__name__)562 app.config['LOGGER_HANDLER_POLICY'] = 'never'563 app.logger_name = 'flask_tests/test_exception_logging'564 app.logger.addHandler(StreamHandler(out))565566 @app.route('/')567 def index():568 1 // 0569570 rv = app.test_client().get('/')571 assert rv.status_code == 500572 assert b'Internal Server Error' in rv.data573574 err = out.getvalue()575 assert 'Exception on / [GET]' in err576 assert 'Traceback (most recent call last):' in err577 assert '1 // 0' in err578 assert 'ZeroDivisionError:' in err579580 def test_processor_exceptions(self):581 app = flask.Flask(__name__)582 app.config['LOGGER_HANDLER_POLICY'] = 'never'583 @app.before_request584 def before_request():585 if trigger == 'before':586 1 // 0587 @app.after_request588 def after_request(response):589 if trigger == 'after':590 1 // 0591 return response592 @app.route('/')593 def index():594 return 'Foo'595 @app.errorhandler(500)596 def internal_server_error(e):597 return 'Hello Server Error', 500598 for trigger in 'before', 'after':599 rv = app.test_client().get('/')600 assert rv.status_code == 500601 assert rv.data == b'Hello Server Error'602603 def test_url_for_with_anchor(self):604 app = flask.Flask(__name__)605 @app.route('/')606 def index():607 return '42'608 with app.test_request_context():609 assert flask.url_for('index', _anchor='x y') == '/#x%20y'610611 def test_url_for_with_scheme(self):612 app = flask.Flask(__name__)613 @app.route('/')614 def index():615 return '42'616 with app.test_request_context():617 assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'618619 def test_url_for_with_scheme_not_external(self):620 app = flask.Flask(__name__)621 @app.route('/')622 def index():623 return '42'624 with app.test_request_context():625 pytest.raises(ValueError,626 flask.url_for,627 'index',628 _scheme='https')629

Merge pull request #1813 from pallets/bugfix/schemeArmin Ronacherbefore adoptionb13e83a

lines 630–639why, one step back
630 def test_url_for_with_alternating_schemes(self):
631 app = flask.Flask(__name__)632 @app.route('/')633 def index():634 return '42'635 with app.test_request_context():636 assert flask.url_for('index', _external=True) == 'http://localhost/'637 assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'638 assert flask.url_for('index', _external=True) == 'http://localhost/'639

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

lines 640–704why, one step back
640 def test_url_with_method(self):
641 from flask.views import MethodView642 app = flask.Flask(__name__)643 class MyView(MethodView):644 def get(self, id=None):645 if id is None:646 return 'List'647 return 'Get %d' % id648 def post(self):649 return 'Create'650 myview = MyView.as_view('myview')651 app.add_url_rule('/myview/', methods=['GET'],652 view_func=myview)653 app.add_url_rule('/myview/<int:id>', methods=['GET'],654 view_func=myview)655 app.add_url_rule('/myview/create', methods=['POST'],656 view_func=myview)657658 with app.test_request_context():659 assert flask.url_for('myview', _method='GET') == '/myview/'660 assert flask.url_for('myview', id=42, _method='GET') == '/myview/42'661 assert flask.url_for('myview', _method='POST') == '/myview/create'662663664class TestNoImports(object):665 """Test Flasks are created without import.666667 Avoiding ``__import__`` helps create Flask instances where there are errors668 at import time. Those runtime errors will be apparent to the user soon669 enough, but tools which build Flask instances meta-programmatically benefit670 from a Flask which does not ``__import__``. Instead of importing to671 retrieve file paths or metadata on a module or package, use the pkgutil and672 imp modules in the Python standard library.673 """674675 def test_name_with_import_error(self, modules_tmpdir):676 modules_tmpdir.join('importerror.py').write('raise NotImplementedError()')677 try:678 flask.Flask('importerror')679 except NotImplementedError:680 assert False, 'Flask(import_name) is importing import_name.'681682683class TestStreaming(object):684685 def test_streaming_with_context(self):686 app = flask.Flask(__name__)687 app.testing = True688 @app.route('/')689 def index():690 def generate():691 yield 'Hello '692 yield flask.request.args['name']693 yield '!'694 return flask.Response(flask.stream_with_context(generate()))695 c = app.test_client()696 rv = c.get('/?name=World')697 assert rv.data == b'Hello World!'698699 def test_streaming_with_context_as_decorator(self):700 app = flask.Flask(__name__)701 app.testing = True702 @app.route('/')703 def index():704 @flask.stream_with_context

Fixed stream_with_context if decorated function has parametersShipeng Fengbefore adoptioncc536c8

lines 705–706why, one step back
705 def generate(hello):
706 yield hello

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

lines 707–708why, one step back
707 yield flask.request.args['name']
708 yield '!'

Fixed stream_with_context if decorated function has parametersShipeng Fengbefore adoptioncc536c8

line 709why, one step back
709 return flask.Response(generate('Hello '))

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

lines 710–739why, one step back
710 c = app.test_client()
711 rv = c.get('/?name=World')712 assert rv.data == b'Hello World!'713714 def test_streaming_with_context_and_custom_close(self):715 app = flask.Flask(__name__)716 app.testing = True717 called = []718 class Wrapper(object):719 def __init__(self, gen):720 self._gen = gen721 def __iter__(self):722 return self723 def close(self):724 called.append(42)725 def __next__(self):726 return next(self._gen)727 next = __next__728 @app.route('/')729 def index():730 def generate():731 yield 'Hello '732 yield flask.request.args['name']733 yield '!'734 return flask.Response(flask.stream_with_context(735 Wrapper(generate())))736 c = app.test_client()737 rv = c.get('/?name=World')738 assert rv.data == b'Hello World!'739 assert called == [42]