test_helpers.py
This file
Path
tests/test_helpers.py
1,039 lines · 33.4 KiB · Python
Last changed by
Merge pull request #3181 from EtiennePelletier/Flask-3125David Lordbefore adoption5a49b96
History of this fileTake it
1# -*- coding: utf-8 -*-2"""3 tests.helpers4 ~~~~~~~~~~~~~~~~~~~~~~~56 Various helpers.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112import datetime13import io14import os15import uuid1617import pytest18from werkzeug.datastructures import Range19from werkzeug.exceptions import BadRequest, NotFound20from werkzeug.http import http_date, parse_cache_control_header, parse_options_header2122import flask23from flask import json24from flask._compat import StringIO, text_type25from flask.helpers import get_debug_flag, get_env262728def has_encoding(name):29 try:30 import codecs3132 codecs.lookup(name)33 return True34 except LookupError:35 return False363738class FakePath(object):39 """Fake object to represent a ``PathLike object``.4041 This represents a ``pathlib.Path`` object in python 3.42 See: https://www.python.org/dev/peps/pep-0519/43 """4445 def __init__(self, path):46 self.path = path4748 def __fspath__(self):49 return self.path505152class FixedOffset(datetime.tzinfo):53 """Fixed offset in hours east from UTC.5455 This is a slight adaptation of the ``FixedOffset`` example found in56 https://docs.python.org/2.7/library/datetime.html.57 """5859 def __init__(self, hours, name):60 self.__offset = datetime.timedelta(hours=hours)61 self.__name = name6263 def utcoffset(self, dt):64 return self.__offset6566 def tzname(self, dt):67 return self.__name6869 def dst(self, dt):70 return datetime.timedelta()717273class TestJSON(object):74 @pytest.mark.parametrize(75 "value", (1, "t", True, False, None, [], [1, 2, 3], {}, {"foo": u"🐍"})76 )77 @pytest.mark.parametrize(78 "encoding",79 (80 "utf-8",81 "utf-8-sig",82 "utf-16-le",83 "utf-16-be",84 "utf-16",85 "utf-32-le",86 "utf-32-be",87 "utf-32",88 ),89 )90 def test_detect_encoding(self, value, encoding):91 data = json.dumps(value).encode(encoding)92 assert json.detect_encoding(data) == encoding93 assert json.loads(data) == value9495 @pytest.mark.parametrize("debug", (True, False))96 def test_bad_request_debug_message(self, app, client, debug):97 app.config["DEBUG"] = debug98 app.config["TRAP_BAD_REQUEST_ERRORS"] = False99100 @app.route("/json", methods=["POST"])101 def post_json():102 flask.request.get_json()103 return None104105 rv = client.post("/json", data=None, content_type="application/json")106 assert rv.status_code == 400107 contains = b"Failed to decode JSON object" in rv.data108 assert contains == debug109110 def test_json_bad_requests(self, app, client):111 @app.route("/json", methods=["POST"])112 def return_json():113 return flask.jsonify(foo=text_type(flask.request.get_json()))114115 rv = client.post("/json", data="malformed", content_type="application/json")116 assert rv.status_code == 400117118 def test_json_custom_mimetypes(self, app, client):119 @app.route("/json", methods=["POST"])120 def return_json():121 return flask.request.get_json()122123 rv = client.post("/json", data='"foo"', content_type="application/x+json")124 assert rv.data == b"foo"125126 @pytest.mark.parametrize(127 "test_value,expected", [(True, '"\\u2603"'), (False, u'"\u2603"')]128 )129 def test_json_as_unicode(self, test_value, expected, app, app_ctx):130131 app.config["JSON_AS_ASCII"] = test_value132 rv = flask.json.dumps(u"\N{SNOWMAN}")133 assert rv == expected134135 def test_json_dump_to_file(self, app, app_ctx):136 test_data = {"name": "Flask"}137 out = StringIO()138139 flask.json.dump(test_data, out)140 out.seek(0)141 rv = flask.json.load(out)142 assert rv == test_data143144 @pytest.mark.parametrize(145 "test_value", [0, -1, 1, 23, 3.14, "s", "longer string", True, False, None]146 )147 def test_jsonify_basic_types(self, test_value, app, client):148 """Test jsonify with basic types."""149150 url = "/jsonify_basic_types"151 app.add_url_rule(url, url, lambda x=test_value: flask.jsonify(x))152 rv = client.get(url)153 assert rv.mimetype == "application/json"154 assert flask.json.loads(rv.data) == test_value155156 def test_jsonify_dicts(self, app, client):157 """Test jsonify with dicts and kwargs unpacking."""158 d = {159 "a": 0,160 "b": 23,161 "c": 3.14,162 "d": "t",163 "e": "Hi",164 "f": True,165 "g": False,166 "h": ["test list", 10, False],167 "i": {"test": "dict"},168 }169170 @app.route("/kw")171 def return_kwargs():172 return flask.jsonify(**d)173174 @app.route("/dict")175 def return_dict():176 return flask.jsonify(d)177178 for url in "/kw", "/dict":179 rv = client.get(url)180 assert rv.mimetype == "application/json"181 assert flask.json.loads(rv.data) == d182183 def test_jsonify_arrays(self, app, client):184 """Test jsonify of lists and args unpacking."""185 l = [186 0,187 42,188 3.14,189 "t",190 "hello",191 True,192 False,193 ["test list", 2, False],194 {"test": "dict"},195 ]196197 @app.route("/args_unpack")198 def return_args_unpack():199 return flask.jsonify(*l)200201 @app.route("/array")202 def return_array():203 return flask.jsonify(l)204205 for url in "/args_unpack", "/array":206 rv = client.get(url)207 assert rv.mimetype == "application/json"208 assert flask.json.loads(rv.data) == l209210 def test_jsonify_date_types(self, app, client):211 """Test jsonify with datetime.date and datetime.datetime types."""212 test_dates = (213 datetime.datetime(1973, 3, 11, 6, 30, 45),214 datetime.date(1975, 1, 5),215 )216217 for i, d in enumerate(test_dates):218 url = "/datetest{0}".format(i)219 app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val))220 rv = client.get(url)221 assert rv.mimetype == "application/json"222 assert flask.json.loads(rv.data)["x"] == http_date(d.timetuple())223224 @pytest.mark.parametrize("tz", (("UTC", 0), ("PST", -8), ("KST", 9)))225 def test_jsonify_aware_datetimes(self, tz):226 """Test if aware datetime.datetime objects are converted into GMT."""227 tzinfo = FixedOffset(hours=tz[1], name=tz[0])228 dt = datetime.datetime(2017, 1, 1, 12, 34, 56, tzinfo=tzinfo)229 gmt = FixedOffset(hours=0, name="GMT")230 expected = dt.astimezone(gmt).strftime('"%a, %d %b %Y %H:%M:%S %Z"')231 assert flask.json.JSONEncoder().encode(dt) == expected232233 def test_jsonify_uuid_types(self, app, client):234 """Test jsonify with uuid.UUID types"""235236 test_uuid = uuid.UUID(bytes=b"\xDE\xAD\xBE\xEF" * 4)237 url = "/uuid_test"238 app.add_url_rule(url, url, lambda: flask.jsonify(x=test_uuid))239240 rv = client.get(url)241242 rv_x = flask.json.loads(rv.data)["x"]243 assert rv_x == str(test_uuid)244 rv_uuid = uuid.UUID(rv_x)245 assert rv_uuid == test_uuid246247 def test_json_attr(self, app, client):248 @app.route("/add", methods=["POST"])249 def add():250 json = flask.request.get_json()251 return text_type(json["a"] + json["b"])252253 rv = client.post(254 "/add",255 data=flask.json.dumps({"a": 1, "b": 2}),256 content_type="application/json",257 )258 assert rv.data == b"3"259260 def test_template_escaping(self, app, req_ctx):261 render = flask.render_template_string262 rv = flask.json.htmlsafe_dumps("</script>")263 assert rv == u'"\\u003c/script\\u003e"'264 assert type(rv) == text_type265 rv = render('{{ "</script>"|tojson }}')266 assert rv == '"\\u003c/script\\u003e"'267 rv = render('{{ "<\0/script>"|tojson }}')268 assert rv == '"\\u003c\\u0000/script\\u003e"'269 rv = render('{{ "<!--<script>"|tojson }}')270 assert rv == '"\\u003c!--\\u003cscript\\u003e"'271 rv = render('{{ "&"|tojson }}')272 assert rv == '"\\u0026"'273 rv = render('{{ "\'"|tojson }}')274 assert rv == '"\\u0027"'275 rv = render(276 "<a ng-data='{{ data|tojson }}'></a>", data={"x": ["foo", "bar", "baz'"]}277 )278 assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'279280 def test_json_customization(self, app, client):281 class X(object):282 def __init__(self, val):283 self.val = val284285 class MyEncoder(flask.json.JSONEncoder):286 def default(self, o):287 if isinstance(o, X):288 return "<%d>" % o.val289 return flask.json.JSONEncoder.default(self, o)290291 class MyDecoder(flask.json.JSONDecoder):292 def __init__(self, *args, **kwargs):293 kwargs.setdefault("object_hook", self.object_hook)294 flask.json.JSONDecoder.__init__(self, *args, **kwargs)295296 def object_hook(self, obj):297 if len(obj) == 1 and "_foo" in obj:298 return X(obj["_foo"])299 return obj300301 app.json_encoder = MyEncoder302 app.json_decoder = MyDecoder303304 @app.route("/", methods=["POST"])305 def index():306 return flask.json.dumps(flask.request.get_json()["x"])307308 rv = client.post(309 "/",310 data=flask.json.dumps({"x": {"_foo": 42}}),311 content_type="application/json",312 )313 assert rv.data == b'"<42>"'314315 def test_blueprint_json_customization(self, app, client):316 class X(object):317 def __init__(self, val):318 self.val = val319320 class MyEncoder(flask.json.JSONEncoder):321 def default(self, o):322 if isinstance(o, X):323 return "<%d>" % o.val324325 return flask.json.JSONEncoder.default(self, o)326327 class MyDecoder(flask.json.JSONDecoder):328 def __init__(self, *args, **kwargs):329 kwargs.setdefault("object_hook", self.object_hook)330 flask.json.JSONDecoder.__init__(self, *args, **kwargs)331332 def object_hook(self, obj):333 if len(obj) == 1 and "_foo" in obj:334 return X(obj["_foo"])335336 return obj337338 bp = flask.Blueprint("bp", __name__)339 bp.json_encoder = MyEncoder340 bp.json_decoder = MyDecoder341342 @bp.route("/bp", methods=["POST"])343 def index():344 return flask.json.dumps(flask.request.get_json()["x"])345346 app.register_blueprint(bp)347348 rv = client.post(349 "/bp",350 data=flask.json.dumps({"x": {"_foo": 42}}),351 content_type="application/json",352 )353 assert rv.data == b'"<42>"'354355 def test_modified_url_encoding(self, app, client):356 class ModifiedRequest(flask.Request):357 url_charset = "euc-kr"358359 app.request_class = ModifiedRequest360 app.url_map.charset = "euc-kr"361362 @app.route("/")363 def index():364 return flask.request.args["foo"]365366 rv = client.get(u"/?foo=정상처리".encode("euc-kr"))367 assert rv.status_code == 200368 assert rv.data == u"정상처리".encode("utf-8")369370 if not has_encoding("euc-kr"):371 test_modified_url_encoding = None372373 def test_json_key_sorting(self, app, client):374 app.debug = True375376 assert app.config["JSON_SORT_KEYS"] == True377 d = dict.fromkeys(range(20), "foo")378379 @app.route("/")380 def index():381 return flask.jsonify(values=d)382383 rv = client.get("/")384 lines = [x.strip() for x in rv.data.strip().decode("utf-8").splitlines()]385 sorted_by_str = [386 "{",387 '"values": {',388 '"0": "foo",',389 '"1": "foo",',390 '"10": "foo",',391 '"11": "foo",',392 '"12": "foo",',393 '"13": "foo",',394 '"14": "foo",',395 '"15": "foo",',396 '"16": "foo",',397 '"17": "foo",',398 '"18": "foo",',399 '"19": "foo",',400 '"2": "foo",',401 '"3": "foo",',402 '"4": "foo",',403 '"5": "foo",',404 '"6": "foo",',405 '"7": "foo",',406 '"8": "foo",',407 '"9": "foo"',408 "}",409 "}",410 ]411 sorted_by_int = [412 "{",413 '"values": {',414 '"0": "foo",',415 '"1": "foo",',416 '"2": "foo",',417 '"3": "foo",',418 '"4": "foo",',419 '"5": "foo",',420 '"6": "foo",',421 '"7": "foo",',422 '"8": "foo",',423 '"9": "foo",',424 '"10": "foo",',425 '"11": "foo",',426 '"12": "foo",',427 '"13": "foo",',428 '"14": "foo",',429 '"15": "foo",',430 '"16": "foo",',431 '"17": "foo",',432 '"18": "foo",',433 '"19": "foo"',434 "}",435 "}",436 ]437438 try:439 assert lines == sorted_by_int440 except AssertionError:441 assert lines == sorted_by_str442443444class TestSendfile(object):445 def test_send_file_regular(self, app, req_ctx):446 rv = flask.send_file("static/index.html")447 assert rv.direct_passthrough448 assert rv.mimetype == "text/html"449 with app.open_resource("static/index.html") as f:450 rv.direct_passthrough = False451 assert rv.data == f.read()452 rv.close()453454 def test_send_file_xsendfile(self, app, req_ctx, catch_deprecation_warnings):455 app.use_x_sendfile = True456 rv = flask.send_file("static/index.html")457 assert rv.direct_passthrough458 assert "x-sendfile" in rv.headers459 assert rv.headers["x-sendfile"] == os.path.join(460 app.root_path, "static/index.html"461 )462 assert rv.mimetype == "text/html"463 rv.close()464465 def test_send_file_last_modified(self, app, client):466 last_modified = datetime.datetime(1999, 1, 1)467468 @app.route("/")469 def index():470 return flask.send_file(471 StringIO("party like it's"),472 last_modified=last_modified,473 mimetype="text/plain",474 )475476 rv = client.get("/")477 assert rv.last_modified == last_modified478479 def test_send_file_object_without_mimetype(self, app, req_ctx):480 with pytest.raises(ValueError) as excinfo:481 flask.send_file(StringIO("LOL"))482 assert "Unable to infer MIME-type" in str(excinfo)483 assert "no filename is available" in str(excinfo)484485 flask.send_file(StringIO("LOL"), attachment_filename="filename")486487 def test_send_file_object(self, app, req_ctx):488 with open(os.path.join(app.root_path, "static/index.html"), mode="rb") as f:489 rv = flask.send_file(f, mimetype="text/html")490 rv.direct_passthrough = False491 with app.open_resource("static/index.html") as f:492 assert rv.data == f.read()493 assert rv.mimetype == "text/html"494 rv.close()495496 app.use_x_sendfile = True497498 with open(os.path.join(app.root_path, "static/index.html")) as f:499 rv = flask.send_file(f, mimetype="text/html")500 assert rv.mimetype == "text/html"501 assert "x-sendfile" not in rv.headers502 rv.close()503504 app.use_x_sendfile = False505 f = StringIO("Test")506 rv = flask.send_file(f, mimetype="application/octet-stream")507 rv.direct_passthrough = False508 assert rv.data == b"Test"509 assert rv.mimetype == "application/octet-stream"510 rv.close()511512 class PyStringIO(object):513 def __init__(self, *args, **kwargs):514 self._io = StringIO(*args, **kwargs)515516 def __getattr__(self, name):517 return getattr(self._io, name)518519 f = PyStringIO("Test")520 f.name = "test.txt"521 rv = flask.send_file(f, attachment_filename=f.name)522 rv.direct_passthrough = False523 assert rv.data == b"Test"524 assert rv.mimetype == "text/plain"525 rv.close()526527 f = StringIO("Test")528 rv = flask.send_file(f, mimetype="text/plain")529 rv.direct_passthrough = False530 assert rv.data == b"Test"531 assert rv.mimetype == "text/plain"532 rv.close()533534 app.use_x_sendfile = True535536 f = StringIO("Test")537 rv = flask.send_file(f, mimetype="text/html")538 assert "x-sendfile" not in rv.headers539 rv.close()540541 def test_send_file_pathlike(self, app, req_ctx):542 rv = flask.send_file(FakePath("static/index.html"))543 assert rv.direct_passthrough544 assert rv.mimetype == "text/html"545 with app.open_resource("static/index.html") as f:546 rv.direct_passthrough = False547 assert rv.data == f.read()548 rv.close()549550 @pytest.mark.skipif(551 not callable(getattr(Range, "to_content_range_header", None)),552 reason="not implemented within werkzeug",553 )554 def test_send_file_range_request(self, app, client):555 @app.route("/")556 def index():557 return flask.send_file("static/index.html", conditional=True)558559 rv = client.get("/", headers={"Range": "bytes=4-15"})560 assert rv.status_code == 206561 with app.open_resource("static/index.html") as f:562 assert rv.data == f.read()[4:16]563 rv.close()564565 rv = client.get("/", headers={"Range": "bytes=4-"})566 assert rv.status_code == 206567 with app.open_resource("static/index.html") as f:568 assert rv.data == f.read()[4:]569 rv.close()570571 rv = client.get("/", headers={"Range": "bytes=4-1000"})572 assert rv.status_code == 206573 with app.open_resource("static/index.html") as f:574 assert rv.data == f.read()[4:]575 rv.close()576577 rv = client.get("/", headers={"Range": "bytes=-10"})578 assert rv.status_code == 206579 with app.open_resource("static/index.html") as f:580 assert rv.data == f.read()[-10:]581 rv.close()582583 rv = client.get("/", headers={"Range": "bytes=1000-"})584 assert rv.status_code == 416585 rv.close()586587 rv = client.get("/", headers={"Range": "bytes=-"})588 assert rv.status_code == 416589 rv.close()590591 rv = client.get("/", headers={"Range": "somethingsomething"})592 assert rv.status_code == 416593 rv.close()594595 last_modified = datetime.datetime.utcfromtimestamp(596 os.path.getmtime(os.path.join(app.root_path, "static/index.html"))597 ).replace(microsecond=0)598599 rv = client.get(600 "/", headers={"Range": "bytes=4-15", "If-Range": http_date(last_modified)}601 )602 assert rv.status_code == 206603 rv.close()604605 rv = client.get(606 "/",607 headers={608 "Range": "bytes=4-15",609 "If-Range": http_date(datetime.datetime(1999, 1, 1)),610 },611 )612 assert rv.status_code == 200613 rv.close()614615 def test_send_file_range_request_bytesio(self, app, client):616 @app.route("/")617 def index():618 file = io.BytesIO(b"somethingsomething")619 return flask.send_file(620 file, attachment_filename="filename", conditional=True621 )622623 rv = client.get("/", headers={"Range": "bytes=4-15"})624 assert rv.status_code == 206625 assert rv.data == b"somethingsomething"[4:16]626 rv.close()627628 @pytest.mark.skipif(629 not callable(getattr(Range, "to_content_range_header", None)),630 reason="not implemented within werkzeug",631 )632 def test_send_file_range_request_xsendfile_invalid(self, app, client):633 # https://github.com/pallets/flask/issues/2526634 app.use_x_sendfile = True635636 @app.route("/")637 def index():638 return flask.send_file("static/index.html", conditional=True)639640 rv = client.get("/", headers={"Range": "bytes=1000-"})641 assert rv.status_code == 416642 rv.close()643644 def test_attachment(self, app, req_ctx):645 app = flask.Flask(__name__)646 with app.test_request_context():647 with open(os.path.join(app.root_path, "static/index.html")) as f:648 rv = flask.send_file(649 f, as_attachment=True, attachment_filename="index.html"650 )651 value, options = parse_options_header(rv.headers["Content-Disposition"])652 assert value == "attachment"653 rv.close()654655 with open(os.path.join(app.root_path, "static/index.html")) as f:656 rv = flask.send_file(657 f, as_attachment=True, attachment_filename="index.html"658 )659 value, options = parse_options_header(rv.headers["Content-Disposition"])660 assert value == "attachment"661 assert options["filename"] == "index.html"662 assert "filename*" not in rv.headers["Content-Disposition"]663 rv.close()664665 rv = flask.send_file("static/index.html", as_attachment=True)666 value, options = parse_options_header(rv.headers["Content-Disposition"])667 assert value == "attachment"668 assert options["filename"] == "index.html"669 rv.close()670671 rv = flask.send_file(672 StringIO("Test"),673 as_attachment=True,674 attachment_filename="index.txt",675 add_etags=False,676 )677 assert rv.mimetype == "text/plain"678 value, options = parse_options_header(rv.headers["Content-Disposition"])679 assert value == "attachment"680 assert options["filename"] == "index.txt"681 rv.close()682683 @pytest.mark.usefixtures("req_ctx")684 @pytest.mark.parametrize(685 ("filename", "ascii", "utf8"),686 (687 ("index.html", "index.html", False),688 (689 u"Ñandú/pingüino.txt",690 '"Nandu/pinguino.txt"',691 "%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt",692 ),693 (u"Vögel.txt", "Vogel.txt", "V%C3%B6gel.txt"),694 # Native string not marked as Unicode on Python 2695 ("tést.txt", "test.txt", "t%C3%A9st.txt"),696 ),697 )698 def test_attachment_filename_encoding(self, filename, ascii, utf8):699 rv = flask.send_file(700 "static/index.html", as_attachment=True, attachment_filename=filename701 )702 rv.close()703 content_disposition = rv.headers["Content-Disposition"]704 assert "filename=%s" % ascii in content_disposition705 if utf8:706 assert "filename*=UTF-8''" + utf8 in content_disposition707 else:708 assert "filename*=UTF-8''" not in content_disposition709710 def test_static_file(self, app, req_ctx):711 # default cache timeout is 12 hours712713 # Test with static file handler.714 rv = app.send_static_file("index.html")715 cc = parse_cache_control_header(rv.headers["Cache-Control"])716 assert cc.max_age == 12 * 60 * 60717 rv.close()718 # Test again with direct use of send_file utility.719 rv = flask.send_file("static/index.html")720 cc = parse_cache_control_header(rv.headers["Cache-Control"])721 assert cc.max_age == 12 * 60 * 60722 rv.close()723 app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 3600724725 # Test with static file handler.726 rv = app.send_static_file("index.html")727 cc = parse_cache_control_header(rv.headers["Cache-Control"])728 assert cc.max_age == 3600729 rv.close()730 # Test again with direct use of send_file utility.731 rv = flask.send_file("static/index.html")732 cc = parse_cache_control_header(rv.headers["Cache-Control"])733 assert cc.max_age == 3600734 rv.close()735736 # Test with static file handler.737 rv = app.send_static_file(FakePath("index.html"))738 cc = parse_cache_control_header(rv.headers["Cache-Control"])739 assert cc.max_age == 3600740 rv.close()741742 class StaticFileApp(flask.Flask):743 def get_send_file_max_age(self, filename):744 return 10745746 app = StaticFileApp(__name__)747 with app.test_request_context():748 # Test with static file handler.749 rv = app.send_static_file("index.html")750 cc = parse_cache_control_header(rv.headers["Cache-Control"])751 assert cc.max_age == 10752 rv.close()753 # Test again with direct use of send_file utility.754 rv = flask.send_file("static/index.html")755 cc = parse_cache_control_header(rv.headers["Cache-Control"])756 assert cc.max_age == 10757 rv.close()758759 def test_send_from_directory(self, app, req_ctx):760 app.root_path = os.path.join(761 os.path.dirname(__file__), "test_apps", "subdomaintestmodule"762 )763 rv = flask.send_from_directory("static", "hello.txt")764 rv.direct_passthrough = False765 assert rv.data.strip() == b"Hello Subdomain"766 rv.close()767768 def test_send_from_directory_pathlike(self, app, req_ctx):769 app.root_path = os.path.join(770 os.path.dirname(__file__), "test_apps", "subdomaintestmodule"771 )772 rv = flask.send_from_directory(FakePath("static"), FakePath("hello.txt"))773 rv.direct_passthrough = False774 assert rv.data.strip() == b"Hello Subdomain"775 rv.close()776777 def test_send_from_directory_bad_request(self, app, req_ctx):778 app.root_path = os.path.join(779 os.path.dirname(__file__), "test_apps", "subdomaintestmodule"780 )781782 with pytest.raises(BadRequest):783 flask.send_from_directory("static", "bad\x00")784785786class TestUrlFor(object):787 def test_url_for_with_anchor(self, app, req_ctx):788 @app.route("/")789 def index():790 return "42"791792 assert flask.url_for("index", _anchor="x y") == "/#x%20y"793794 def test_url_for_with_scheme(self, app, req_ctx):795 @app.route("/")796 def index():797 return "42"798799 assert (800 flask.url_for("index", _external=True, _scheme="https")801 == "https://localhost/"802 )803804 def test_url_for_with_scheme_not_external(self, app, req_ctx):805 @app.route("/")806 def index():807 return "42"808809 pytest.raises(ValueError, flask.url_for, "index", _scheme="https")810811 def test_url_for_with_alternating_schemes(self, app, req_ctx):812 @app.route("/")813 def index():814 return "42"815816 assert flask.url_for("index", _external=True) == "http://localhost/"817 assert (818 flask.url_for("index", _external=True, _scheme="https")819 == "https://localhost/"820 )821 assert flask.url_for("index", _external=True) == "http://localhost/"822823 def test_url_with_method(self, app, req_ctx):824 from flask.views import MethodView825826 class MyView(MethodView):827 def get(self, id=None):828 if id is None:829 return "List"830 return "Get %d" % id831832 def post(self):833 return "Create"834835 myview = MyView.as_view("myview")836 app.add_url_rule("/myview/", methods=["GET"], view_func=myview)837 app.add_url_rule("/myview/<int:id>", methods=["GET"], view_func=myview)838 app.add_url_rule("/myview/create", methods=["POST"], view_func=myview)839840 assert flask.url_for("myview", _method="GET") == "/myview/"841 assert flask.url_for("myview", id=42, _method="GET") == "/myview/42"842 assert flask.url_for("myview", _method="POST") == "/myview/create"843844845class TestNoImports(object):846 """Test Flasks are created without import.847848 Avoiding ``__import__`` helps create Flask instances where there are errors849 at import time. Those runtime errors will be apparent to the user soon850 enough, but tools which build Flask instances meta-programmatically benefit851 from a Flask which does not ``__import__``. Instead of importing to852 retrieve file paths or metadata on a module or package, use the pkgutil and853 imp modules in the Python standard library.854 """855856 def test_name_with_import_error(self, modules_tmpdir):857 modules_tmpdir.join("importerror.py").write("raise NotImplementedError()")858 try:859 flask.Flask("importerror")860 except NotImplementedError:861 assert False, "Flask(import_name) is importing import_name."862863864class TestStreaming(object):865 def test_streaming_with_context(self, app, client):866 @app.route("/")867 def index():868 def generate():869 yield "Hello "870 yield flask.request.args["name"]871 yield "!"872873 return flask.Response(flask.stream_with_context(generate()))874875 rv = client.get("/?name=World")876 assert rv.data == b"Hello World!"877878 def test_streaming_with_context_as_decorator(self, app, client):879 @app.route("/")880 def index():881 @flask.stream_with_context882 def generate(hello):883 yield hello884 yield flask.request.args["name"]885 yield "!"886887 return flask.Response(generate("Hello "))888889 rv = client.get("/?name=World")890 assert rv.data == b"Hello World!"891892 def test_streaming_with_context_and_custom_close(self, app, client):893 called = []894895 class Wrapper(object):896 def __init__(self, gen):897 self._gen = gen898899 def __iter__(self):900 return self901902 def close(self):903 called.append(42)904905 def __next__(self):906 return next(self._gen)907908 next = __next__909910 @app.route("/")911 def index():912 def generate():913 yield "Hello "914 yield flask.request.args["name"]915 yield "!"916917 return flask.Response(flask.stream_with_context(Wrapper(generate())))918919 rv = client.get("/?name=World")920 assert rv.data == b"Hello World!"921 assert called == [42]922923 def test_stream_keeps_session(self, app, client):924 @app.route("/")925 def index():926 flask.session["test"] = "flask"927928 @flask.stream_with_context929 def gen():930 yield flask.session["test"]931932 return flask.Response(gen())933934 rv = client.get("/")935 assert rv.data == b"flask"936937938class TestSafeJoin(object):939 def test_safe_join(self):940 # Valid combinations of *args and expected joined paths.941 passing = (942 (("a/b/c",), "a/b/c"),943 (("/", "a/", "b/", "c/"), "/a/b/c"),944 (("a", "b", "c"), "a/b/c"),945 (("/a", "b/c"), "/a/b/c"),946 (("a/b", "X/../c"), "a/b/c"),947 (("/a/b", "c/X/.."), "/a/b/c"),948 # If last path is '' add a slash949 (("/a/b/c", ""), "/a/b/c/"),950 # Preserve dot slash951 (("/a/b/c", "./"), "/a/b/c/."),952 (("a/b/c", "X/.."), "a/b/c/."),953 # Base directory is always considered safe954 (("../", "a/b/c"), "../a/b/c"),955 (("/..",), "/.."),956 )957958 for args, expected in passing:959 assert flask.safe_join(*args) == expected960961 def test_safe_join_exceptions(self):962 # Should raise werkzeug.exceptions.NotFound on unsafe joins.963 failing = (964 # path.isabs and ``..'' checks965 ("/a", "b", "/c"),966 ("/a", "../b/c"),967 ("/a", "..", "b/c"),968 # Boundaries violations after path normalization969 ("/a", "b/../b/../../c"),970 ("/a", "b", "c/../.."),971 ("/a", "b/../../c"),972 )973974 for args in failing:975 with pytest.raises(NotFound):976 print(flask.safe_join(*args))977978979980class TestHelpers(object):981 @pytest.mark.parametrize(982 "debug, expected_flag, expected_default_flag",983 [984 ("", False, False),985 ("0", False, False),986 ("False", False, False),987 ("No", False, False),988 ("True", True, True),989 ],990 )991 def test_get_debug_flag(992 self, monkeypatch, debug, expected_flag, expected_default_flag993 ):994 monkeypatch.setenv("FLASK_DEBUG", debug)995 if expected_flag is None:996 assert get_debug_flag() is None997 else:998 assert get_debug_flag() == expected_flag999 assert get_debug_flag() == expected_default_flag10001001 @pytest.mark.parametrize(1002 "env, ref_env, debug",1003 [1004 ("", "production", False),1005 ("production", "production", False),1006 ("development", "development", True),1007 ("other", "other", False),1008 ],1009 )1010 def test_get_env(self, monkeypatch, env, ref_env, debug):1011 monkeypatch.setenv("FLASK_ENV", env)1012 assert get_debug_flag() == debug1013 assert get_env() == ref_env10141015 def test_make_response(self):1016 app = flask.Flask(__name__)1017 with app.test_request_context():1018 rv = flask.helpers.make_response()1019 assert rv.status_code == 2001020 assert rv.mimetype == "text/html"10211022 rv = flask.helpers.make_response("Hello")1023 assert rv.status_code == 2001024 assert rv.data == b"Hello"1025 assert rv.mimetype == "text/html"10261027 @pytest.mark.parametrize("mode", ("r", "rb", "rt"))1028 def test_open_resource(self, mode):1029 app = flask.Flask(__name__)10301031 with app.open_resource("static/index.html", mode) as f:1032 assert "<h1>Hello World!</h1>" in str(f.read())10331034 @pytest.mark.parametrize("mode", ("w", "x", "a", "r+"))1035 def test_open_resource_exceptions(self, mode):1036 app = flask.Flask(__name__)10371038 with pytest.raises(ValueError):1039 app.open_resource("static/index.html", mode)