From 6896bb35d86c4669b808c999468d124e4e0ea164 Mon Sep 17 00:00:00 2001 From: playlikeboy <108283560+playlikeboy@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:57:25 +0530 Subject: [PATCH] Reject empty stream values in binary Metadata Metadata.get_binary_from() checked the original value for emptiness instead of the bytes it read from it. An io.BytesIO or file object is always truthy, so an empty stream passed the "empty not allowed" check and an empty metadata entry ended up in the ZIM, while an empty bytes value was correctly rejected. Check the read bytes instead. --- CHANGELOG.md | 4 ++++ src/zimscraperlib/zim/metadata.py | 2 +- tests/zim/test_metadata.py | 15 +++++++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 77dcde76..c92526bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed + +- `Metadata` (and `CustomMetadata`/`XCustomMetadata`) now rejects an empty `io.BytesIO` or file-like value when empty is not allowed, like it already did for empty `bytes` + ## [5.6.0] - 2026-11-20 ### Added diff --git a/src/zimscraperlib/zim/metadata.py b/src/zimscraperlib/zim/metadata.py index 79e13907..d88cbdd3 100644 --- a/src/zimscraperlib/zim/metadata.py +++ b/src/zimscraperlib/zim/metadata.py @@ -240,7 +240,7 @@ def get_binary_from( bvalue = value.read() if isinstance(value, SupportsSeekableRead) and value.seekable(): value.seek(last_pos) - if not self.empty_allowed and not value: + if not self.empty_allowed and not bvalue: raise ValueError("Missing value (empty not allowed)") return bvalue diff --git a/tests/zim/test_metadata.py b/tests/zim/test_metadata.py index a361b4af..20301141 100644 --- a/tests/zim/test_metadata.py +++ b/tests/zim/test_metadata.py @@ -232,6 +232,21 @@ def test_blank_metadata(): metadata.Metadata(name="Blank", value=b"") +def test_blank_metadata_from_bytesio(): + with pytest.raises(ValueError, match=r"Missing value \(empty not allowed\)"): + metadata.Metadata(name="Blank", value=io.BytesIO(b"")) + + +def test_blank_metadata_from_file(tmp_path: pathlib.Path): + fpath = tmp_path / "empty" + fpath.write_bytes(b"") + with ( + open(fpath, "rb") as fh, + pytest.raises(ValueError, match=r"Missing value \(empty not allowed\)"), + ): + metadata.Metadata(name="Blank", value=fh) + + class MetadataInitConfig(NamedTuple): a_type: type nb_args: int