# retoor <retoor@molodetz.nl>
import re
from pathlib import Path
from devplacepy.templating import (
format_coins,
format_duration,
format_exact,
format_number,
format_speed,
)
FORMAT_JS = Path(__file__).resolve().parents[3] / "devplacepy" / "static" / "js" / "Format.js"
PARITY_VALUES = (
0,
1,
42,
999,
1000,
12345,
999999,
1000000,
1050000,
1500000,
9990000,
12500000,
150000000,
1000000000,
2340000000,
1000000000000,
5500000000000,
-42,
-1500000,
)
def _client_number(value):
amount = int(value)
magnitude = abs(amount)
if magnitude < 1000000:
return f"{amount:,}"
for limit, suffix in ((10**12, "T"), (10**9, "B"), (10**6, "M")):
if magnitude >= limit:
scaled = amount / limit
digits = 2 if abs(scaled) < 10 else 1
text = f"{scaled:.{digits}f}".rstrip("0").rstrip(".")
return f"{text}{suffix}"
return f"{amount:,}"
def test_server_and_client_number_formatting_agree():
for value in PARITY_VALUES:
assert format_number(value) == _client_number(value), value
def test_thousands_separated_below_the_compact_threshold():
assert format_number(999) == "999"
assert format_number(1000) == "1,000"
assert format_number(999999) == "999,999"
def test_compact_above_the_threshold():
assert format_number(1000000) == "1M"
assert format_number(1500000) == "1.5M"
assert format_number(150000000) == "150M"
assert format_number(2340000000) == "2.34B"
assert format_number(5500000000000) == "5.5T"
def test_coins_and_exact_helpers():
assert format_coins(1500000) == "1.5Mc"
assert format_coins(250) == "250c"
assert format_exact(1500000) == "1,500,000"
assert format_exact(0) == "0"
def test_speed_drops_trailing_zeros():
assert format_speed(1.0) == "1x"
assert format_speed(1.25) == "1.25x"
assert format_speed(2.5) == "2.5x"
def test_duration_matches_the_client_shape():
assert format_duration(0) == "0s"
assert format_duration(45) == "45s"
assert format_duration(90) == "1m 30s"
assert format_duration(3600) == "1h 0m"
assert format_duration(7325) == "2h 2m"
def test_client_module_keeps_the_same_thresholds():
source = FORMAT_JS.read_text()
assert "COMPACT_FROM = 1000000" in source
assert 'suffix: "T"' in source and 'suffix: "B"' in source and 'suffix: "M"' in source
assert 'toLocaleString("en-GB")' in source
assert re.search(r"static coins\(", source)
assert re.search(r"static duration\(", source)