From 1663b97eaafb0dccd0fa523c1a083032f7d0bd9c Mon Sep 17 00:00:00 2001 From: David de la Iglesia Castro Date: Mon, 30 May 2022 17:12:21 +0200 Subject: [PATCH] api: open: Raise ValueError if rev is used in wrong mode. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #7405 Co-authored-by: Peter Rowlands (변기호) --- dvc/api.py | 4 ++++ tests/unit/test_api.py | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 tests/unit/test_api.py diff --git a/dvc/api.py b/dvc/api.py index af719c119..a57a67fef 100644 --- a/dvc/api.py +++ b/dvc/api.py @@ -90,6 +90,7 @@ def open( # noqa, pylint: disable=redefined-builtin mode (str, optional): Specifies the mode in which the file is opened. Defaults to "r" (read). Mirrors the namesake parameter in builtin `open()`_. + Only reading `mode` is supported. encoding(str, optional): `Codec`_ used to decode the file contents. Defaults to None. This should only be used in text mode. @@ -104,6 +105,7 @@ def open( # noqa, pylint: disable=redefined-builtin Raises: AttributeError: If this method is not used as a context manager. + ValueError: If non-read `mode` is used. Examples: @@ -178,6 +180,8 @@ def open( # noqa, pylint: disable=redefined-builtin https://docs.python.org/3/glossary.html#term-file-object """ + if "r" not in mode: + raise ValueError("Only reading `mode` is supported.") args = (path,) kwargs = { diff --git a/tests/unit/test_api.py b/tests/unit/test_api.py new file mode 100644 index 000000000..7f7eac1ac --- /dev/null +++ b/tests/unit/test_api.py @@ -0,0 +1,21 @@ +import pytest + +from dvc import api + + +def test_open_raises_error_if_no_context(tmp_dir, dvc): + tmp_dir.dvc_gen("foo", "foo-text") + + with pytest.raises( + AttributeError, match="should be used in a with statement." + ): + fd = api.open("foo") + fd.read() + + +def test_open_rev_raises_error_on_wrong_mode(tmp_dir, dvc): + tmp_dir.dvc_gen("foo", "foo-text") + + with pytest.raises(ValueError, match="Only reading `mode` is supported."): + with api.open("foo", mode="w"): + pass