From ee9dd85d83f377807eafe7691b3c776350e8d8b6 Mon Sep 17 00:00:00 2001 From: JSap0914 Date: Tue, 16 Jun 2026 17:39:43 +0900 Subject: [PATCH] fix(helper): handle negative byte counts in get_readable_size --- jina/helper.py | 10 ++++++---- tests/unit/test_helper.py | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/jina/helper.py b/jina/helper.py index b5bcd9759b4b8..0b85177a33674 100644 --- a/jina/helper.py +++ b/jina/helper.py @@ -209,14 +209,16 @@ def get_readable_size(num_bytes: Union[int, float]) -> str: :return: Human readable string representation. """ num_bytes = int(num_bytes) + sign = '-' if num_bytes < 0 else '' + num_bytes = abs(num_bytes) if num_bytes < 1024: - return f'{num_bytes} Bytes' + return f'{sign}{num_bytes} Bytes' elif num_bytes < 1024**2: - return f'{num_bytes / 1024:.1f} KB' + return f'{sign}{num_bytes / 1024:.1f} KB' elif num_bytes < 1024**3: - return f'{num_bytes / (1024 ** 2):.1f} MB' + return f'{sign}{num_bytes / (1024 ** 2):.1f} MB' else: - return f'{num_bytes / (1024 ** 3):.1f} GB' + return f'{sign}{num_bytes / (1024 ** 3):.1f} GB' def batch_iterator( diff --git a/tests/unit/test_helper.py b/tests/unit/test_helper.py index 7833c36a3e3c4..43adc25ae7dce 100644 --- a/tests/unit/test_helper.py +++ b/tests/unit/test_helper.py @@ -15,6 +15,7 @@ deprecated_alias, dunder_get, find_request_binding, + get_readable_size, get_ci_vendor, is_generator, is_port_free, @@ -426,3 +427,21 @@ def test_is_generator(): assert not is_generator(async_normal_func) assert is_generator(yield_from_generator_func) assert is_generator(async_yield_generator_func) + + +@pytest.mark.parametrize( + 'num_bytes, expected', + [ + (0, '0 Bytes'), + (512, '512 Bytes'), + (1536, '1.5 KB'), + (2 * 1024**2, '2.0 MB'), + (3 * 1024**3, '3.0 GB'), + (-512, '-512 Bytes'), + (-1536, '-1.5 KB'), + (-2 * 1024**2, '-2.0 MB'), + (-5 * 1024**3, '-5.0 GB'), + ], +) +def test_get_readable_size(num_bytes, expected): + assert get_readable_size(num_bytes) == expected