From ad709be46e660b76263a50bfecdb390f0863a90c Mon Sep 17 00:00:00 2001 From: icreatedanaccount Date: Mon, 6 May 2019 10:56:35 -0400 Subject: [PATCH] Allow mode='rt' on open_resource() helper --- flask/helpers.py | 2 ++ tests/test_helpers.py | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/flask/helpers.py b/flask/helpers.py index 19cb4c99..78f4b37c 100644 --- a/flask/helpers.py +++ b/flask/helpers.py @@ -1055,6 +1055,8 @@ class _PackageBoundObject(object): subfolders use forward slashes as separator. :param mode: resource file opening mode, default is 'rb'. """ + if mode == 'rt': + mode = 'r' if mode not in ("r", "rb"): raise ValueError("Resources can only be opened for reading") return open(os.path.join(self.root_path, resource), mode) diff --git a/tests/test_helpers.py b/tests/test_helpers.py index d65a5f5e..e7730da0 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -1014,6 +1014,7 @@ class TestSafeJoin(object): print(flask.safe_join(*args)) + class TestHelpers(object): @pytest.mark.parametrize( "debug, expected_flag, expected_default_flag", @@ -1060,3 +1061,27 @@ class TestHelpers(object): assert rv.status_code == 200 assert rv.data == b"Hello" assert rv.mimetype == "text/html" + + @pytest.mark.parametrize('mode', [ + 'r', + 'rb', + 'rt' + ]) + def test_open_resource(self, mode): + app = flask.Flask(__name__) + with app.open_resource('static/index.html', mode) as f: + assert '

Hello World!

' in str(f.read()) + + @pytest.mark.parametrize('mode', [ + 'w', + 'x', + 'a', + 'b', + 't', + '+' + ]) + def test_open_resource_exceptions(self, mode): + app = flask.Flask(__name__) + with pytest.raises(ValueError): + app.open_resource('static/index.html', mode) +