Skip to content

Commit

Permalink
Fix rollover from ZB to 1.0 YB (#206)
Browse files Browse the repository at this point in the history
  • Loading branch information
hugovk authored Oct 1, 2024
2 parents 922c547 + be8796c commit 56b4fa8
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
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

0 comments on commit 56b4fa8

Please sign in to comment.