From 4cc8abe701ffc08ca3263d733d15966072bce20a Mon Sep 17 00:00:00 2001 From: patchwright Date: Fri, 19 Jun 2026 04:52:39 +0200 Subject: [PATCH] fix: clamp convert_size_bytes_to_string at largest unit (#184) --- src/fsutil/converters.py | 2 +- tests/test_converters.py | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/fsutil/converters.py b/src/fsutil/converters.py index 2399269..c83f199 100644 --- a/src/fsutil/converters.py +++ b/src/fsutil/converters.py @@ -11,7 +11,7 @@ def convert_size_bytes_to_string(size: int) -> str: units = SIZE_UNITS factor = 0 factor_limit = len(units) - 1 - while (size_num >= 1024) and (factor <= factor_limit): + while (size_num >= 1024) and (factor < factor_limit): size_num /= 1024 factor += 1 size_units = units[factor] diff --git a/tests/test_converters.py b/tests/test_converters.py index f7e95f1..06b03bb 100644 --- a/tests/test_converters.py +++ b/tests/test_converters.py @@ -19,6 +19,21 @@ def test_convert_size_bytes_to_string(size_bytes, expected_output): assert fsutil.convert_size_bytes_to_string(size_bytes) == expected_output +@pytest.mark.parametrize( + "size_bytes, expected_output", + [ + (2**80, "1.00 YB"), + (2**90, "1024.00 YB"), + (2**100, "1048576.00 YB"), + ], +) +def test_convert_size_bytes_to_string_saturates_at_largest_unit( + size_bytes, expected_output +): + # Sizes at or above 1024 YB must clamp to the YB unit, not raise IndexError. + assert fsutil.convert_size_bytes_to_string(size_bytes) == expected_output + + @pytest.mark.parametrize( "size_string, expected_output", [