Skip to content
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
16 changes: 3 additions & 13 deletions src/fsize/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,19 +196,9 @@ def __format__(self, format_spec: str) -> str:
)

# Convert the number to the appropriate unit
n = self.real
if unit == "K":
n = self.to_k()
elif unit == "M":
n = self.to_m()
elif unit == "G":
n = self.to_g()
elif unit == "T":
n = self.to_t()
elif unit == "P":
n = self.to_p()
elif unit == "E":
n = self.to_e()
if unit not in _UNIT_POWERS:
raise AssertionError(f"unhandled unit: {unit!r}")
n = self.real / self._convert ** _UNIT_POWERS[unit]

log_digits = math.ceil(math.log10(n)) if n > 0 else 0
out_format_spec = (
Expand Down
18 changes: 18 additions & 0 deletions tests/test_fsize_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,23 @@ def test_format_empty_spec():
assert format(z, "") == str(z)


def test_format_all_units():
"""Test that every unit in _UNIT_POWERS works via format."""
# Binary FSize (1 EiB)
val = FSize(1, "EiB")
assert format(val, "E") == "1"
assert format(val, "P") == "1024"
assert format(val, "T") == str(1024**2)
assert format(val, "G") == str(1024**3)
assert format(val, "M") == str(1024**4)
assert format(val, "K") == str(1024**5)
# Decimal FSize (1 EB)
val_dec = FSize(1, "EB")
assert format(val_dec, "E") == "1"
assert float(format(val_dec, "P")) == 1000
assert float(format(val_dec, "K")) == 1000**5


def test_format_combined_spec():
"""Test format with combined fill, align, width, grouping, and unit."""
x = FSize(1_048_576)
Expand All @@ -458,3 +475,4 @@ def test_format_combined_spec():
# Just unit (no optional fields)
assert float(format(x, "KiB")) == pytest.approx(1024.0)
assert float(format(x, "MiB")) == pytest.approx(1.0)

Loading