Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix rollover from ZB to 1.0 YB #206

Merged
merged 5 commits into from
Oct 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/humanize/filesize.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def naturalsize(
gnu: bool = False,
format: str = "%.1f",
) -> str:
"""Format a number of bytes like a human readable filesize (e.g. 10 kB).
"""Format a number of bytes like a human-readable filesize (e.g. 10 kB).

By default, decimal suffixes (kB, MB) are used.

Expand Down Expand Up @@ -83,7 +83,11 @@ def naturalsize(
suffix = suffixes["decimal"]

base = 1024 if (gnu or binary) else 1000
bytes_ = float(value)
if isinstance(value, str):
bytes_ = float(value)
else:
bytes_ = value

abs_bytes = abs(bytes_)

if abs_bytes == 1 and not gnu:
Expand Down
21 changes: 18 additions & 3 deletions tests/test_filesize.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,17 @@
"test_args, expected",
[
([300], "300 Bytes"),
(["1000"], "1.0 kB"),
([10**3], "1.0 kB"),
([10**6], "1.0 MB"),
([10**9], "1.0 GB"),
([10**12], "1.0 TB"),
([10**15], "1.0 PB"),
([10**18], "1.0 EB"),
([10**21], "1.0 ZB"),
([10**24], "1.0 YB"),
([10**27], "1.0 RB"),
([10**30], "1.0 QB"),
([1000**1 * 31], "31.0 kB"),
([1000**2 * 32], "32.0 MB"),
([1000**3 * 33], "33.0 GB"),
Expand Down Expand Up @@ -67,6 +78,10 @@
def test_naturalsize(test_args: list[int] | list[int | bool], expected: str) -> None:
assert humanize.naturalsize(*test_args) == expected

args_with_negative = test_args
args_with_negative[0] *= -1
assert humanize.naturalsize(*args_with_negative) == "-" + expected
# Retest with negative input
if isinstance(test_args[0], int):
test_args[0] *= -1
else:
test_args[0] = f"-{test_args[0]}"

assert humanize.naturalsize(*test_args) == "-" + expected
Loading