diff --git a/src/humanize/filesize.py b/src/humanize/filesize.py index fb675fd..f1ef2e3 100644 --- a/src/humanize/filesize.py +++ b/src/humanize/filesize.py @@ -4,9 +4,10 @@ __lazy_modules__ = {"humanize.i18n", "math"} -from math import log +from math import isfinite, log from humanize.i18n import _gettext as _ +from humanize.number import _format_not_finite suffixes = { "decimal": ( @@ -90,6 +91,10 @@ def naturalsize( base = 1024 if (gnu or binary) else 1000 bytes_ = float(value) + if not isfinite(bytes_): + # Match the rest of the library (see humanize.number): format NaN and + # infinities instead of crashing or emitting a bogus suffix like "inf QB". + return _format_not_finite(bytes_) abs_bytes = abs(bytes_) if abs_bytes == 1 and not gnu: diff --git a/tests/test_filesize.py b/tests/test_filesize.py index e695639..9cea09b 100644 --- a/tests/test_filesize.py +++ b/tests/test_filesize.py @@ -4,6 +4,8 @@ from __future__ import annotations +import math + import pytest import humanize @@ -103,3 +105,18 @@ def test_naturalsize(test_args: list[int] | list[int | bool], expected: str) -> test_args[0] = f"-{test_args[0]}" assert humanize.naturalsize(*test_args) == "-" + expected + + +@pytest.mark.parametrize( + "value, expected", + [ + (math.nan, "NaN"), + (math.inf, "+Inf"), + (-math.inf, "-Inf"), + ("nan", "NaN"), + ("inf", "+Inf"), + ("-inf", "-Inf"), + ], +) +def test_naturalsize_non_finite(value: float | str, expected: str) -> None: + assert humanize.naturalsize(value) == expected