test_helpers.py
This file
Path
tests/test_helpers.py
909 lines · 31.6 KiB · Python
Last changed by
Merge pull request #2695 from pallets/backport-2691-json-encodingDavid Lordbefore adoptionb178e89
History of this fileTake it
The walk stopped after 200 commits: lines older than f63cd72 point at it.
Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
lines 1–14why, one step back1# -*- coding: utf-8 -*-2"""3 tests.helpers4 ~~~~~~~~~~~~~~~~~~~~~~~56 Various helpers.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314import osAdd tests for flask.json.dump() and test that jsonify correctly converts uuids.Nathan Landbefore adoptionf16e477
line 15why, one step back15import uuidMerge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
line 16why, one step back16import datetimemake use of range requests if available in werkzeug (#2031)Joël Charlesbefore adoption7186a5a
line 17why, one step back17Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
lines 18–19why, one step back18import flask19from logging import StreamHandlermake use of range requests if available in werkzeug (#2031)Joël Charlesbefore adoption7186a5a
line 20why, one step back20from werkzeug.datastructures import RangeMerge pull request #1730 from geusebi/masterMarkus Unterwaditzerbefore adoption9f9e1fd
line 21why, one step back21from werkzeug.exceptions import BadRequest, NotFoundMerge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
lines 22–23why, one step back22from werkzeug.http import parse_cache_control_header, parse_options_header23from werkzeug.http import http_dateMerge pull request #2695 from pallets/backport-2691-json-encodingDavid Lordbefore adoptionb178e89
lines 24–25why, one step back2425from flask import jsonclean up new json testsDavid Lordbefore adoptionf193f59
line 26why, one step back26from flask._compat import StringIO, text_typeMerge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
lines 27–38why, one step back272829def has_encoding(name):30 try:31 import codecs32 codecs.lookup(name)33 return True34 except LookupError:35 return False363738class TestJSON(object):Merge pull request #2695 from pallets/backport-2691-json-encodingDavid Lordbefore adoptionb178e89
lines 39–52why, one step back39 @pytest.mark.parametrize('value', (40 1, 't', True, False, None,41 [], [1, 2, 3],42 {}, {'foo': u'🐍'},43 ))44 @pytest.mark.parametrize('encoding', (45 'utf-8', 'utf-8-sig',46 'utf-16-le', 'utf-16-be', 'utf-16',47 'utf-32-le', 'utf-32-be', 'utf-32',48 ))49 def test_detect_encoding(self, value, encoding):50 data = json.dumps(value).encode(encoding)51 assert json.detect_encoding(data) == encoding52 assert json.loads(data) == valueMerge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
line 53why, one step back53Ignore cache on request.get_json(cache=False) call (#2089)Jiri Kuncarbefore adoption36425d5
lines 54–61why, one step back54 def test_ignore_cached_json(self):55 app = flask.Flask(__name__)56 with app.test_request_context('/', method='POST', data='malformed',57 content_type='application/json'):58 assert flask.request.get_json(silent=True, cache=True) is None59 with pytest.raises(BadRequest):60 flask.request.get_json(silent=False, cache=False)61Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
lines 62–116why, one step back62 def test_post_empty_json_adds_exception_to_response_content_in_debug(self):63 app = flask.Flask(__name__)64 app.config['DEBUG'] = True65 @app.route('/json', methods=['POST'])66 def post_json():67 flask.request.get_json()68 return None69 c = app.test_client()70 rv = c.post('/json', data=None, content_type='application/json')71 assert rv.status_code == 40072 assert b'Failed to decode JSON object' in rv.data7374 def test_post_empty_json_wont_add_exception_to_response_if_no_debug(self):75 app = flask.Flask(__name__)76 app.config['DEBUG'] = False77 @app.route('/json', methods=['POST'])78 def post_json():79 flask.request.get_json()80 return None81 c = app.test_client()82 rv = c.post('/json', data=None, content_type='application/json')83 assert rv.status_code == 40084 assert b'Failed to decode JSON object' not in rv.data8586 def test_json_bad_requests(self):87 app = flask.Flask(__name__)88 @app.route('/json', methods=['POST'])89 def return_json():90 return flask.jsonify(foo=text_type(flask.request.get_json()))91 c = app.test_client()92 rv = c.post('/json', data='malformed', content_type='application/json')93 assert rv.status_code == 4009495 def test_json_custom_mimetypes(self):96 app = flask.Flask(__name__)97 @app.route('/json', methods=['POST'])98 def return_json():99 return flask.request.get_json()100 c = app.test_client()101 rv = c.post('/json', data='"foo"', content_type='application/x+json')102 assert rv.data == b'foo'103104 def test_json_as_unicode(self):105 app = flask.Flask(__name__)106107 app.config['JSON_AS_ASCII'] = True108 with app.app_context():109 rv = flask.json.dumps(u'\N{SNOWMAN}')110 assert rv == '"\\u2603"'111112 app.config['JSON_AS_ASCII'] = False113 with app.app_context():114 rv = flask.json.dumps(u'\N{SNOWMAN}')115 assert rv == u'"\u2603"'116Add tests for flask.json.dump() and test that jsonify correctly converts uuids.Nathan Landbefore adoptionf16e477
lines 117–118why, one step back117 def test_json_dump_to_file(self):118 app = flask.Flask(__name__)clean up new json testsDavid Lordbefore adoptionf193f59
lines 119–120why, one step back119 test_data = {'name': 'Flask'}120 out = StringIO()Add tests for flask.json.dump() and test that jsonify correctly converts uuids.Nathan Landbefore adoptionf16e477
lines 121–122why, one step back121122 with app.app_context():clean up new json testsDavid Lordbefore adoptionf193f59
lines 123–125why, one step back123 flask.json.dump(test_data, out)124 out.seek(0)125 rv = flask.json.load(out)Add tests for flask.json.dump() and test that jsonify correctly converts uuids.Nathan Landbefore adoptionf16e477
lines 126–127why, one step back126 assert rv == test_data127Parameterizing test (#2073)Alex Kahanbefore adoption2647fc7
lines 128–129why, one step back128 @pytest.mark.parametrize('test_value', [0, -1, 1, 23, 3.14, 's', "longer string", True, False, None])129 def test_jsonify_basic_types(self, test_value):Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
lines 130–133why, one step back130 """Test jsonify with basic types."""131 app = flask.Flask(__name__)132 c = app.test_client()133Parameterizing test (#2073)Alex Kahanbefore adoption2647fc7
lines 134–139why, one step back134 url = '/jsonify_basic_types'135 app.add_url_rule(url, url, lambda x=test_value: flask.jsonify(x))136 rv = c.get(url)137 assert rv.mimetype == 'application/json'138 assert flask.json.loads(rv.data) == test_value139Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
lines 140–194why, one step back140 def test_jsonify_dicts(self):141 """Test jsonify with dicts and kwargs unpacking."""142 d = dict(143 a=0, b=23, c=3.14, d='t', e='Hi', f=True, g=False,144 h=['test list', 10, False],145 i={'test':'dict'}146 )147 app = flask.Flask(__name__)148 @app.route('/kw')149 def return_kwargs():150 return flask.jsonify(**d)151 @app.route('/dict')152 def return_dict():153 return flask.jsonify(d)154 c = app.test_client()155 for url in '/kw', '/dict':156 rv = c.get(url)157 assert rv.mimetype == 'application/json'158 assert flask.json.loads(rv.data) == d159160 def test_jsonify_arrays(self):161 """Test jsonify of lists and args unpacking."""162 l = [163 0, 42, 3.14, 't', 'hello', True, False,164 ['test list', 2, False],165 {'test':'dict'}166 ]167 app = flask.Flask(__name__)168 @app.route('/args_unpack')169 def return_args_unpack():170 return flask.jsonify(*l)171 @app.route('/array')172 def return_array():173 return flask.jsonify(l)174 c = app.test_client()175 for url in '/args_unpack', '/array':176 rv = c.get(url)177 assert rv.mimetype == 'application/json'178 assert flask.json.loads(rv.data) == l179180 def test_jsonify_date_types(self):181 """Test jsonify with datetime.date and datetime.datetime types."""182 test_dates = (183 datetime.datetime(1973, 3, 11, 6, 30, 45),184 datetime.date(1975, 1, 5)185 )186 app = flask.Flask(__name__)187 c = app.test_client()188189 for i, d in enumerate(test_dates):190 url = '/datetest{0}'.format(i)191 app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val))192 rv = c.get(url)193 assert rv.mimetype == 'application/json'194 assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple())Add tests for flask.json.dump() and test that jsonify correctly converts uuids.Nathan Landbefore adoptionf16e477
lines 195–197why, one step back195196 def test_jsonify_uuid_types(self):197 """Test jsonify with uuid.UUID types"""clean up new json testsDavid Lordbefore adoptionf193f59
line 198why, one step back198Parameterizing test (#2073)Alex Kahanbefore adoption2647fc7
line 199why, one step back199 test_uuid = uuid.UUID(bytes=b'\xDE\xAD\xBE\xEF' * 4)Add tests for flask.json.dump() and test that jsonify correctly converts uuids.Nathan Landbefore adoptionf16e477
lines 200–201why, one step back200 app = flask.Flask(__name__)201 url = '/uuid_test'clean up new json testsDavid Lordbefore adoptionf193f59
lines 202–204why, one step back202 app.add_url_rule(url, url, lambda: flask.jsonify(x=test_uuid))203204 c = app.test_client()Add tests for flask.json.dump() and test that jsonify correctly converts uuids.Nathan Landbefore adoptionf16e477
line 205why, one step back205 rv = c.get(url)clean up new json testsDavid Lordbefore adoptionf193f59
lines 206–210why, one step back206207 rv_x = flask.json.loads(rv.data)['x']208 assert rv_x == str(test_uuid)209 rv_uuid = uuid.UUID(rv_x)210 assert rv_uuid == test_uuidMerge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
lines 211–376why, one step back211212 def test_json_attr(self):213 app = flask.Flask(__name__)214 @app.route('/add', methods=['POST'])215 def add():216 json = flask.request.get_json()217 return text_type(json['a'] + json['b'])218 c = app.test_client()219 rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),220 content_type='application/json')221 assert rv.data == b'3'222223 def test_template_escaping(self):224 app = flask.Flask(__name__)225 render = flask.render_template_string226 with app.test_request_context():227 rv = flask.json.htmlsafe_dumps('</script>')228 assert rv == u'"\\u003c/script\\u003e"'229 assert type(rv) == text_type230 rv = render('{{ "</script>"|tojson }}')231 assert rv == '"\\u003c/script\\u003e"'232 rv = render('{{ "<\0/script>"|tojson }}')233 assert rv == '"\\u003c\\u0000/script\\u003e"'234 rv = render('{{ "<!--<script>"|tojson }}')235 assert rv == '"\\u003c!--\\u003cscript\\u003e"'236 rv = render('{{ "&"|tojson }}')237 assert rv == '"\\u0026"'238 rv = render('{{ "\'"|tojson }}')239 assert rv == '"\\u0027"'240 rv = render("<a ng-data='{{ data|tojson }}'></a>",241 data={'x': ["foo", "bar", "baz'"]})242 assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'243244 def test_json_customization(self):245 class X(object):246 def __init__(self, val):247 self.val = val248 class MyEncoder(flask.json.JSONEncoder):249 def default(self, o):250 if isinstance(o, X):251 return '<%d>' % o.val252 return flask.json.JSONEncoder.default(self, o)253 class MyDecoder(flask.json.JSONDecoder):254 def __init__(self, *args, **kwargs):255 kwargs.setdefault('object_hook', self.object_hook)256 flask.json.JSONDecoder.__init__(self, *args, **kwargs)257 def object_hook(self, obj):258 if len(obj) == 1 and '_foo' in obj:259 return X(obj['_foo'])260 return obj261 app = flask.Flask(__name__)262 app.testing = True263 app.json_encoder = MyEncoder264 app.json_decoder = MyDecoder265 @app.route('/', methods=['POST'])266 def index():267 return flask.json.dumps(flask.request.get_json()['x'])268 c = app.test_client()269 rv = c.post('/', data=flask.json.dumps({270 'x': {'_foo': 42}271 }), content_type='application/json')272 assert rv.data == b'"<42>"'273274 def test_modified_url_encoding(self):275 class ModifiedRequest(flask.Request):276 url_charset = 'euc-kr'277 app = flask.Flask(__name__)278 app.testing = True279 app.request_class = ModifiedRequest280 app.url_map.charset = 'euc-kr'281282 @app.route('/')283 def index():284 return flask.request.args['foo']285286 rv = app.test_client().get(u'/?foo=정상처리'.encode('euc-kr'))287 assert rv.status_code == 200288 assert rv.data == u'정상처리'.encode('utf-8')289290 if not has_encoding('euc-kr'):291 test_modified_url_encoding = None292293 def test_json_key_sorting(self):294 app = flask.Flask(__name__)295 app.testing = True296 assert app.config['JSON_SORT_KEYS'] == True297 d = dict.fromkeys(range(20), 'foo')298299 @app.route('/')300 def index():301 return flask.jsonify(values=d)302303 c = app.test_client()304 rv = c.get('/')305 lines = [x.strip() for x in rv.data.strip().decode('utf-8').splitlines()]306 sorted_by_str = [307 '{',308 '"values": {',309 '"0": "foo",',310 '"1": "foo",',311 '"10": "foo",',312 '"11": "foo",',313 '"12": "foo",',314 '"13": "foo",',315 '"14": "foo",',316 '"15": "foo",',317 '"16": "foo",',318 '"17": "foo",',319 '"18": "foo",',320 '"19": "foo",',321 '"2": "foo",',322 '"3": "foo",',323 '"4": "foo",',324 '"5": "foo",',325 '"6": "foo",',326 '"7": "foo",',327 '"8": "foo",',328 '"9": "foo"',329 '}',330 '}'331 ]332 sorted_by_int = [333 '{',334 '"values": {',335 '"0": "foo",',336 '"1": "foo",',337 '"2": "foo",',338 '"3": "foo",',339 '"4": "foo",',340 '"5": "foo",',341 '"6": "foo",',342 '"7": "foo",',343 '"8": "foo",',344 '"9": "foo",',345 '"10": "foo",',346 '"11": "foo",',347 '"12": "foo",',348 '"13": "foo",',349 '"14": "foo",',350 '"15": "foo",',351 '"16": "foo",',352 '"17": "foo",',353 '"18": "foo",',354 '"19": "foo"',355 '}',356 '}'357 ]358359 try:360 assert lines == sorted_by_int361 except AssertionError:362 assert lines == sorted_by_str363364class TestSendfile(object):365366 def test_send_file_regular(self):367 app = flask.Flask(__name__)368 with app.test_request_context():369 rv = flask.send_file('static/index.html')370 assert rv.direct_passthrough371 assert rv.mimetype == 'text/html'372 with app.open_resource('static/index.html') as f:373 rv.direct_passthrough = False374 assert rv.data == f.read()375 rv.close()376Merge pull request #1878 from untitaker/recwarnMarkus Unterwaditzerbefore adoption3d72099
line 377why, one step back377 def test_send_file_xsendfile(self, catch_deprecation_warnings):Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
lines 378–386why, one step back378 app = flask.Flask(__name__)379 app.use_x_sendfile = True380 with app.test_request_context():381 rv = flask.send_file('static/index.html')382 assert rv.direct_passthrough383 assert 'x-sendfile' in rv.headers384 assert rv.headers['x-sendfile'] == \385 os.path.join(app.root_path, 'static/index.html')386 assert rv.mimetype == 'text/html'Add last_modified arg for send_filePrachi Shirish Khadkebefore adoptionaf515cc
lines 387–390why, one step back387 rv.close()388389 def test_send_file_last_modified(self):390 app = flask.Flask(__name__)pass value directly to last_modifiedDavid Lordbefore adoption7c27140
lines 391–394why, one step back391 last_modified = datetime.datetime(1999, 1, 1)392393 @app.route('/')394 def index():Properly remove f.name usage in send_file (#1988)Markus Unterwaditzerbefore adoption71e10be
lines 395–397why, one step back395 return flask.send_file(StringIO("party like it's"),396 last_modified=last_modified,397 mimetype='text/plain')pass value directly to last_modifiedDavid Lordbefore adoption7c27140
lines 398–401why, one step back398399 c = app.test_client()400 rv = c.get('/')401 assert rv.last_modified == last_modifiedMerge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
line 402why, one step back402Properly remove f.name usage in send_file (#1988)Markus Unterwaditzerbefore adoption71e10be
lines 403–410why, one step back403 def test_send_file_object_without_mimetype(self):404 app = flask.Flask(__name__)405406 with app.test_request_context():407 with pytest.raises(ValueError) as excinfo:408 flask.send_file(StringIO("LOL"))409 assert 'Unable to infer MIME-type' in str(excinfo)410 assert 'no filename is available' in str(excinfo)Fix error in send_file helper (#2003)Romanbefore adoption92ce20e
lines 411–412why, one step back411412 with app.test_request_context():Merge pull request #2019 from pallets/bugfix/sendfile-errorArmin Ronacherbefore adoptiona40489e
line 413why, one step back413 flask.send_file(StringIO("LOL"), attachment_filename='filename')Properly remove f.name usage in send_file (#1988)Markus Unterwaditzerbefore adoption71e10be
line 414why, one step back414Remove deprecation warnings for add_etags & mimetype guessing for send_file()Dan Sullybefore adoption8458cc5
line 415why, one step back415 def test_send_file_object(self):Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
line 416why, one step back416 app = flask.Flask(__name__)Merge pull request #1878 from untitaker/recwarnMarkus Unterwaditzerbefore adoption3d72099
lines 417–419why, one step back417418 with app.test_request_context():419 with open(os.path.join(app.root_path, 'static/index.html'), mode='rb') as f:Properly remove f.name usage in send_file (#1988)Markus Unterwaditzerbefore adoption71e10be
line 420why, one step back420 rv = flask.send_file(f, mimetype='text/html')Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
lines 421–427why, one step back421 rv.direct_passthrough = False422 with app.open_resource('static/index.html') as f:423 assert rv.data == f.read()424 assert rv.mimetype == 'text/html'425 rv.close()426427 app.use_x_sendfile = TrueMerge pull request #1878 from untitaker/recwarnMarkus Unterwaditzerbefore adoption3d72099
lines 428–430why, one step back428429 with app.test_request_context():430 with open(os.path.join(app.root_path, 'static/index.html')) as f:Properly remove f.name usage in send_file (#1988)Markus Unterwaditzerbefore adoption71e10be
line 431why, one step back431 rv = flask.send_file(f, mimetype='text/html')Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
line 432why, one step back432 assert rv.mimetype == 'text/html'Properly remove f.name usage in send_file (#1988)Markus Unterwaditzerbefore adoption71e10be
line 433why, one step back433 assert 'x-sendfile' not in rv.headersMerge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
lines 434–437why, one step back434 rv.close()435436 app.use_x_sendfile = False437 with app.test_request_context():Merge pull request #1878 from untitaker/recwarnMarkus Unterwaditzerbefore adoption3d72099
line 438why, one step back438 f = StringIO('Test')Properly remove f.name usage in send_file (#1988)Markus Unterwaditzerbefore adoption71e10be
line 439why, one step back439 rv = flask.send_file(f, mimetype='application/octet-stream')Merge pull request #1878 from untitaker/recwarnMarkus Unterwaditzerbefore adoption3d72099
lines 440–451why, one step back440 rv.direct_passthrough = False441 assert rv.data == b'Test'442 assert rv.mimetype == 'application/octet-stream'443 rv.close()444445 class PyStringIO(object):446 def __init__(self, *args, **kwargs):447 self._io = StringIO(*args, **kwargs)448 def __getattr__(self, name):449 return getattr(self._io, name)450 f = PyStringIO('Test')451 f.name = 'test.txt'Properly remove f.name usage in send_file (#1988)Markus Unterwaditzerbefore adoption71e10be
line 452why, one step back452 rv = flask.send_file(f, attachment_filename=f.name)Merge pull request #1878 from untitaker/recwarnMarkus Unterwaditzerbefore adoption3d72099
lines 453–464why, one step back453 rv.direct_passthrough = False454 assert rv.data == b'Test'455 assert rv.mimetype == 'text/plain'456 rv.close()457458 f = StringIO('Test')459 rv = flask.send_file(f, mimetype='text/plain')460 rv.direct_passthrough = False461 assert rv.data == b'Test'462 assert rv.mimetype == 'text/plain'463 rv.close()464Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
lines 465–466why, one step back465 app.use_x_sendfile = True466Merge pull request #1878 from untitaker/recwarnMarkus Unterwaditzerbefore adoption3d72099
lines 467–468why, one step back467 with app.test_request_context():468 f = StringIO('Test')Properly remove f.name usage in send_file (#1988)Markus Unterwaditzerbefore adoption71e10be
line 469why, one step back469 rv = flask.send_file(f, mimetype='text/html')Merge pull request #1878 from untitaker/recwarnMarkus Unterwaditzerbefore adoption3d72099
lines 470–471why, one step back470 assert 'x-sendfile' not in rv.headers471 rv.close()make use of range requests if available in werkzeug (#2031)Joël Charlesbefore adoption7186a5a
lines 472–474why, one step back472473 @pytest.mark.skipif(474 not callable(getattr(Range, 'to_content_range_header', None)),Fix ValueError for some invalid Range requestsThiefMasterbefore adoptionc52e1b7
line 475why, one step back475 reason="not implemented within werkzeug"make use of range requests if available in werkzeug (#2031)Joël Charlesbefore adoption7186a5a
lines 476–521why, one step back476 )477 def test_send_file_range_request(self):478 app = flask.Flask(__name__)479480 @app.route('/')481 def index():482 return flask.send_file('static/index.html', conditional=True)483484 c = app.test_client()485486 rv = c.get('/', headers={'Range': 'bytes=4-15'})487 assert rv.status_code == 206488 with app.open_resource('static/index.html') as f:489 assert rv.data == f.read()[4:16]490 rv.close()491492 rv = c.get('/', headers={'Range': 'bytes=4-'})493 assert rv.status_code == 206494 with app.open_resource('static/index.html') as f:495 assert rv.data == f.read()[4:]496 rv.close()497498 rv = c.get('/', headers={'Range': 'bytes=4-1000'})499 assert rv.status_code == 206500 with app.open_resource('static/index.html') as f:501 assert rv.data == f.read()[4:]502 rv.close()503504 rv = c.get('/', headers={'Range': 'bytes=-10'})505 assert rv.status_code == 206506 with app.open_resource('static/index.html') as f:507 assert rv.data == f.read()[-10:]508 rv.close()509510 rv = c.get('/', headers={'Range': 'bytes=1000-'})511 assert rv.status_code == 416512 rv.close()513514 rv = c.get('/', headers={'Range': 'bytes=-'})515 assert rv.status_code == 416516 rv.close()517518 rv = c.get('/', headers={'Range': 'somethingsomething'})519 assert rv.status_code == 416520 rv.close()521get mtime in utcDavid Lordbefore adoption4ff84d5
line 522why, one step back522 last_modified = datetime.datetime.utcfromtimestamp(os.path.getmtime(make use of range requests if available in werkzeug (#2031)Joël Charlesbefore adoption7186a5a
lines 523–533why, one step back523 os.path.join(app.root_path, 'static/index.html'))).replace(524 microsecond=0)525526 rv = c.get('/', headers={'Range': 'bytes=4-15',527 'If-Range': http_date(last_modified)})528 assert rv.status_code == 206529 rv.close()530531 rv = c.get('/', headers={'Range': 'bytes=4-15', 'If-Range': http_date(532 datetime.datetime(1999, 1, 1))})533 assert rv.status_code == 200Fix ValueError for some invalid Range requestsThiefMasterbefore adoptionc52e1b7
lines 534–552why, one step back534 rv.close()535536 @pytest.mark.skipif(537 not callable(getattr(Range, 'to_content_range_header', None)),538 reason="not implemented within werkzeug"539 )540 def test_send_file_range_request_xsendfile_invalid(self):541 # https://github.com/pallets/flask/issues/2526542 app = flask.Flask(__name__)543 app.use_x_sendfile = True544545 @app.route('/')546 def index():547 return flask.send_file('static/index.html', conditional=True)548549 c = app.test_client()550551 rv = c.get('/', headers={'Range': 'bytes=1000-'})552 assert rv.status_code == 416make use of range requests if available in werkzeug (#2031)Joël Charlesbefore adoption7186a5a
line 553why, one step back553 rv.close()Merge pull request #1878 from untitaker/recwarnMarkus Unterwaditzerbefore adoption3d72099
line 554why, one step back554Remove deprecation warnings for add_etags & mimetype guessing for send_file()Dan Sullybefore adoption8458cc5
line 555why, one step back555 def test_attachment(self):Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
line 556why, one step back556 app = flask.Flask(__name__)Merge pull request #1878 from untitaker/recwarnMarkus Unterwaditzerbefore adoption3d72099
lines 557–558why, one step back557 with app.test_request_context():558 with open(os.path.join(app.root_path, 'static/index.html')) as f:Properly remove f.name usage in send_file (#1988)Markus Unterwaditzerbefore adoption71e10be
lines 559–560why, one step back559 rv = flask.send_file(f, as_attachment=True,560 attachment_filename='index.html')Merge pull request #1878 from untitaker/recwarnMarkus Unterwaditzerbefore adoption3d72099
lines 561–562why, one step back561 value, options = \562 parse_options_header(rv.headers['Content-Disposition'])Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
lines 563–636why, one step back563 assert value == 'attachment'564 rv.close()565566 with app.test_request_context():567 assert options['filename'] == 'index.html'568 rv = flask.send_file('static/index.html', as_attachment=True)569 value, options = parse_options_header(rv.headers['Content-Disposition'])570 assert value == 'attachment'571 assert options['filename'] == 'index.html'572 rv.close()573574 with app.test_request_context():575 rv = flask.send_file(StringIO('Test'), as_attachment=True,576 attachment_filename='index.txt',577 add_etags=False)578 assert rv.mimetype == 'text/plain'579 value, options = parse_options_header(rv.headers['Content-Disposition'])580 assert value == 'attachment'581 assert options['filename'] == 'index.txt'582 rv.close()583584 def test_static_file(self):585 app = flask.Flask(__name__)586 # default cache timeout is 12 hours587 with app.test_request_context():588 # Test with static file handler.589 rv = app.send_static_file('index.html')590 cc = parse_cache_control_header(rv.headers['Cache-Control'])591 assert cc.max_age == 12 * 60 * 60592 rv.close()593 # Test again with direct use of send_file utility.594 rv = flask.send_file('static/index.html')595 cc = parse_cache_control_header(rv.headers['Cache-Control'])596 assert cc.max_age == 12 * 60 * 60597 rv.close()598 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600599 with app.test_request_context():600 # Test with static file handler.601 rv = app.send_static_file('index.html')602 cc = parse_cache_control_header(rv.headers['Cache-Control'])603 assert cc.max_age == 3600604 rv.close()605 # Test again with direct use of send_file utility.606 rv = flask.send_file('static/index.html')607 cc = parse_cache_control_header(rv.headers['Cache-Control'])608 assert cc.max_age == 3600609 rv.close()610 class StaticFileApp(flask.Flask):611 def get_send_file_max_age(self, filename):612 return 10613 app = StaticFileApp(__name__)614 with app.test_request_context():615 # Test with static file handler.616 rv = app.send_static_file('index.html')617 cc = parse_cache_control_header(rv.headers['Cache-Control'])618 assert cc.max_age == 10619 rv.close()620 # Test again with direct use of send_file utility.621 rv = flask.send_file('static/index.html')622 cc = parse_cache_control_header(rv.headers['Cache-Control'])623 assert cc.max_age == 10624 rv.close()625626 def test_send_from_directory(self):627 app = flask.Flask(__name__)628 app.testing = True629 app.root_path = os.path.join(os.path.dirname(__file__),630 'test_apps', 'subdomaintestmodule')631 with app.test_request_context():632 rv = flask.send_from_directory('static', 'hello.txt')633 rv.direct_passthrough = False634 assert rv.data.strip() == b'Hello Subdomain'635 rv.close()636Raise BadRequest if static file name is invalidDavid Houbefore adoption9f1be8e
lines 637–644why, one step back637 def test_send_from_directory_bad_request(self):638 app = flask.Flask(__name__)639 app.testing = True640 app.root_path = os.path.join(os.path.dirname(__file__),641 'test_apps', 'subdomaintestmodule')642 with app.test_request_context():643 with pytest.raises(BadRequest):644 flask.send_from_directory('static', 'bad\x00')Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
lines 645–758why, one step back645646class TestLogging(object):647648 def test_logger_cache(self):649 app = flask.Flask(__name__)650 logger1 = app.logger651 assert app.logger is logger1652 assert logger1.name == __name__653 app.logger_name = __name__ + '/test_logger_cache'654 assert app.logger is not logger1655656 def test_debug_log(self, capsys):657 app = flask.Flask(__name__)658 app.debug = True659660 @app.route('/')661 def index():662 app.logger.warning('the standard library is dead')663 app.logger.debug('this is a debug statement')664 return ''665666 @app.route('/exc')667 def exc():668 1 // 0669670 with app.test_client() as c:671 c.get('/')672 out, err = capsys.readouterr()673 assert 'WARNING in test_helpers [' in err674 assert os.path.basename(__file__.rsplit('.', 1)[0] + '.py') in err675 assert 'the standard library is dead' in err676 assert 'this is a debug statement' in err677678 with pytest.raises(ZeroDivisionError):679 c.get('/exc')680681 def test_debug_log_override(self):682 app = flask.Flask(__name__)683 app.debug = True684 app.logger_name = 'flask_tests/test_debug_log_override'685 app.logger.level = 10686 assert app.logger.level == 10687688 def test_exception_logging(self):689 out = StringIO()690 app = flask.Flask(__name__)691 app.config['LOGGER_HANDLER_POLICY'] = 'never'692 app.logger_name = 'flask_tests/test_exception_logging'693 app.logger.addHandler(StreamHandler(out))694695 @app.route('/')696 def index():697 1 // 0698699 rv = app.test_client().get('/')700 assert rv.status_code == 500701 assert b'Internal Server Error' in rv.data702703 err = out.getvalue()704 assert 'Exception on / [GET]' in err705 assert 'Traceback (most recent call last):' in err706 assert '1 // 0' in err707 assert 'ZeroDivisionError:' in err708709 def test_processor_exceptions(self):710 app = flask.Flask(__name__)711 app.config['LOGGER_HANDLER_POLICY'] = 'never'712 @app.before_request713 def before_request():714 if trigger == 'before':715 1 // 0716 @app.after_request717 def after_request(response):718 if trigger == 'after':719 1 // 0720 return response721 @app.route('/')722 def index():723 return 'Foo'724 @app.errorhandler(500)725 def internal_server_error(e):726 return 'Hello Server Error', 500727 for trigger in 'before', 'after':728 rv = app.test_client().get('/')729 assert rv.status_code == 500730 assert rv.data == b'Hello Server Error'731732 def test_url_for_with_anchor(self):733 app = flask.Flask(__name__)734 @app.route('/')735 def index():736 return '42'737 with app.test_request_context():738 assert flask.url_for('index', _anchor='x y') == '/#x%20y'739740 def test_url_for_with_scheme(self):741 app = flask.Flask(__name__)742 @app.route('/')743 def index():744 return '42'745 with app.test_request_context():746 assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'747748 def test_url_for_with_scheme_not_external(self):749 app = flask.Flask(__name__)750 @app.route('/')751 def index():752 return '42'753 with app.test_request_context():754 pytest.raises(ValueError,755 flask.url_for,756 'index',757 _scheme='https')758Merge pull request #1813 from pallets/bugfix/schemeArmin Ronacherbefore adoptionb13e83a
lines 759–768why, one step back759 def test_url_for_with_alternating_schemes(self):760 app = flask.Flask(__name__)761 @app.route('/')762 def index():763 return '42'764 with app.test_request_context():765 assert flask.url_for('index', _external=True) == 'http://localhost/'766 assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'767 assert flask.url_for('index', _external=True) == 'http://localhost/'768Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
lines 769–833why, one step back769 def test_url_with_method(self):770 from flask.views import MethodView771 app = flask.Flask(__name__)772 class MyView(MethodView):773 def get(self, id=None):774 if id is None:775 return 'List'776 return 'Get %d' % id777 def post(self):778 return 'Create'779 myview = MyView.as_view('myview')780 app.add_url_rule('/myview/', methods=['GET'],781 view_func=myview)782 app.add_url_rule('/myview/<int:id>', methods=['GET'],783 view_func=myview)784 app.add_url_rule('/myview/create', methods=['POST'],785 view_func=myview)786787 with app.test_request_context():788 assert flask.url_for('myview', _method='GET') == '/myview/'789 assert flask.url_for('myview', id=42, _method='GET') == '/myview/42'790 assert flask.url_for('myview', _method='POST') == '/myview/create'791792793class TestNoImports(object):794 """Test Flasks are created without import.795796 Avoiding ``__import__`` helps create Flask instances where there are errors797 at import time. Those runtime errors will be apparent to the user soon798 enough, but tools which build Flask instances meta-programmatically benefit799 from a Flask which does not ``__import__``. Instead of importing to800 retrieve file paths or metadata on a module or package, use the pkgutil and801 imp modules in the Python standard library.802 """803804 def test_name_with_import_error(self, modules_tmpdir):805 modules_tmpdir.join('importerror.py').write('raise NotImplementedError()')806 try:807 flask.Flask('importerror')808 except NotImplementedError:809 assert False, 'Flask(import_name) is importing import_name.'810811812class TestStreaming(object):813814 def test_streaming_with_context(self):815 app = flask.Flask(__name__)816 app.testing = True817 @app.route('/')818 def index():819 def generate():820 yield 'Hello '821 yield flask.request.args['name']822 yield '!'823 return flask.Response(flask.stream_with_context(generate()))824 c = app.test_client()825 rv = c.get('/?name=World')826 assert rv.data == b'Hello World!'827828 def test_streaming_with_context_as_decorator(self):829 app = flask.Flask(__name__)830 app.testing = True831 @app.route('/')832 def index():833 @flask.stream_with_contextFixed stream_with_context if decorated function has parametersShipeng Fengbefore adoptioncc536c8
lines 834–835why, one step back834 def generate(hello):835 yield helloMerge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
lines 836–837why, one step back836 yield flask.request.args['name']837 yield '!'Fixed stream_with_context if decorated function has parametersShipeng Fengbefore adoptioncc536c8
line 838why, one step back838 return flask.Response(generate('Hello '))Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
lines 839–868why, one step back839 c = app.test_client()840 rv = c.get('/?name=World')841 assert rv.data == b'Hello World!'842843 def test_streaming_with_context_and_custom_close(self):844 app = flask.Flask(__name__)845 app.testing = True846 called = []847 class Wrapper(object):848 def __init__(self, gen):849 self._gen = gen850 def __iter__(self):851 return self852 def close(self):853 called.append(42)854 def __next__(self):855 return next(self._gen)856 next = __next__857 @app.route('/')858 def index():859 def generate():860 yield 'Hello '861 yield flask.request.args['name']862 yield '!'863 return flask.Response(flask.stream_with_context(864 Wrapper(generate())))865 c = app.test_client()866 rv = c.get('/?name=World')867 assert rv.data == b'Hello World!'868 assert called == [42]Merge pull request #1730 from geusebi/masterMarkus Unterwaditzerbefore adoption9f9e1fd
lines 869–874why, one step back869870871class TestSafeJoin(object):872 def test_safe_join(self):873 # Valid combinations of *args and expected joined paths.874 passing = (safe_join on Windows uses posixpathDavid Lordbefore adoptionf7c35bf
lines 875–880why, one step back875 (('a/b/c',), 'a/b/c'),876 (('/', 'a/', 'b/', 'c/'), '/a/b/c'),877 (('a', 'b', 'c'), 'a/b/c'),878 (('/a', 'b/c'), '/a/b/c'),879 (('a/b', 'X/../c'), 'a/b/c'),880 (('/a/b', 'c/X/..'), '/a/b/c'),Merge pull request #1730 from geusebi/masterMarkus Unterwaditzerbefore adoption9f9e1fd
line 881why, one step back881 # If last path is '' add a slashsafe_join on Windows uses posixpathDavid Lordbefore adoptionf7c35bf
line 882why, one step back882 (('/a/b/c', ''), '/a/b/c/'),Merge pull request #1730 from geusebi/masterMarkus Unterwaditzerbefore adoption9f9e1fd
line 883why, one step back883 # Preserve dot slashsafe_join on Windows uses posixpathDavid Lordbefore adoptionf7c35bf
lines 884–885why, one step back884 (('/a/b/c', './'), '/a/b/c/.'),885 (('a/b/c', 'X/..'), 'a/b/c/.'),Merge pull request #1730 from geusebi/masterMarkus Unterwaditzerbefore adoption9f9e1fd
lines 886–898why, one step back886 # Base directory is always considered safe887 (('../', 'a/b/c'), '../a/b/c'),888 (('/..', ), '/..'),889 )890891 for args, expected in passing:892 assert flask.safe_join(*args) == expected893894 def test_safe_join_exceptions(self):895 # Should raise werkzeug.exceptions.NotFound on unsafe joins.896 failing = (897 # path.isabs and ``..'' checks898 ('/a', 'b', '/c'),safe_join on Windows uses posixpathDavid Lordbefore adoptionf7c35bf
line 899why, one step back899 ('/a', '../b/c'),Merge pull request #1730 from geusebi/masterMarkus Unterwaditzerbefore adoption9f9e1fd
lines 900–901why, one step back900 ('/a', '..', 'b/c'),901 # Boundaries violations after path normalizationsafe_join on Windows uses posixpathDavid Lordbefore adoptionf7c35bf
line 902why, one step back902 ('/a', 'b/../b/../../c'),Merge pull request #1730 from geusebi/masterMarkus Unterwaditzerbefore adoption9f9e1fd
line 903why, one step back903 ('/a', 'b', 'c/../..'),safe_join on Windows uses posixpathDavid Lordbefore adoptionf7c35bf
line 904why, one step back904 ('/a', 'b/../../c'),Merge pull request #1730 from geusebi/masterMarkus Unterwaditzerbefore adoption9f9e1fd
lines 905–909why, one step back905 )906907 for args in failing:908 with pytest.raises(NotFound):909 print(flask.safe_join(*args))