From 3e018bb10d7693d765697d8eaab2114276fdf5c3 Mon Sep 17 00:00:00 2001 From: "SU, Yanyu" <238259854+TohruSu@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:53:10 +0900 Subject: [PATCH] Raise BoxError from box_from_string for YAML when no YAML library is installed --- AUTHORS.rst | 1 + CHANGES.rst | 5 +++++ box/from_file.py | 2 ++ test/test_coverage_paths.py | 14 ++++++++++++++ 4 files changed, 22 insertions(+) diff --git a/AUTHORS.rst b/AUTHORS.rst index b2f08ec3..4d0942a6 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -61,6 +61,7 @@ Code contributions: - gyanu2507 (gyanu2507) - Rahul (rahul05ranjan) - Anish Pentyala (anishpentyala) +- SU, Yanyu (TohruSu) Suggestions and bug reporting: diff --git a/CHANGES.rst b/CHANGES.rst index 826d7485..d77aeb6d 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,5 +1,10 @@ Changelog +Unreleased +---------- + +* Fixing box_from_string(string_type="yaml") raising TypeError instead of BoxError when no YAML library is installed and Box is not compiled with Cython (thanks to SU, Yanyu) + Version 8.0.1 ------------- diff --git a/box/from_file.py b/box/from_file.py index f6f2650b..2620b06b 100644 --- a/box/from_file.py +++ b/box/from_file.py @@ -156,6 +156,8 @@ def box_from_string(content: str, string_type: str = "json") -> Box | BoxList: raise BoxError("File is not TOML as expected") # A TOML document is always a table, so unlike the other formats it is never a BoxList elif string_type == "yaml": + if not yaml_available: + raise BoxError('yaml is unavailable on this system, please install the "ruamel.yaml" or "PyYAML" package') try: return Box.from_yaml(yaml_string=content) except YAMLError: diff --git a/test/test_coverage_paths.py b/test/test_coverage_paths.py index a60b7a9a..4bb8e7d8 100644 --- a/test/test_coverage_paths.py +++ b/test/test_coverage_paths.py @@ -342,6 +342,20 @@ def test_toon_unavailable(self, tmp_path, monkeypatch): with pytest.raises(BoxError, match="toon"): box_from_string("a: 1", string_type="toon") + def test_box_from_string_yaml_unavailable(self, monkeypatch): + # What from_file and Box look like without ruamel.yaml or PyYAML installed + def unavailable(cls, *args, **kwargs): + raise BoxError("yaml is unavailable on this system") + + monkeypatch.setattr(from_file, "yaml_available", False) + monkeypatch.setattr(from_file, "YAMLError", False) + monkeypatch.setattr(Box, "from_yaml", classmethod(unavailable)) + monkeypatch.setattr(BoxList, "from_yaml", classmethod(unavailable)) + with pytest.raises(BoxError, match="yaml is unavailable"): + box_from_string("a: 1", string_type="yaml") + with pytest.raises(BoxError, match="yaml is unavailable"): + box_from_string("- 1\n- 2\n", string_type="yaml") + def test_box_from_string_json(self): assert box_from_string('{"a": 1}').to_dict() == {"a": 1} assert box_from_string("[1, 2]").to_list() == [1, 2]