diff --git a/src/rez/tests/test_utils_formatting.py b/src/rez/tests/test_utils_formatting.py new file mode 100644 index 000000000..a63388f3c --- /dev/null +++ b/src/rez/tests/test_utils_formatting.py @@ -0,0 +1,43 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright Contributors to the Rez Project + + +""" +unit tests for 'utils.formatting' module +""" +from rez.tests.util import TestBase +from rez.utils import formatting + + +class TestFormatting(TestBase): + def test_readable_units(self): + readable_units = formatting._readable_units( + 0, + formatting.memory_divs + ) + self.assertEqual(readable_units, "0 bytes") + + readable_units = formatting._readable_units( + 1024, + formatting.memory_divs + ) + self.assertEqual(readable_units, "1 Kb") + + readable_units = formatting._readable_units( + 1200, + formatting.memory_divs + ) + self.assertEqual(readable_units, "1.2 Kb") + + readable_units = formatting._readable_units( + -30000, + formatting.memory_divs + ) + self.assertEqual(readable_units, "-29 Kb") + + readable_units = formatting._readable_units( + 1024, + formatting.memory_divs, + plural_aware=True + ) + self.assertEqual(readable_units, "1 K") diff --git a/src/rez/utils/formatting.py b/src/rez/utils/formatting.py index 3f9c3587d..aa8aad41c 100644 --- a/src/rez/utils/formatting.py +++ b/src/rez/utils/formatting.py @@ -10,6 +10,7 @@ from rez.exceptions import PackageRequestError from pprint import pformat from enum import Enum +import math import os import os.path import re @@ -363,7 +364,9 @@ def readable_time_duration(secs): def readable_memory_size(bytes_): - """Convert number of bytes into human readable form, eg '1.2 Kb'. + """Convert number of bytes into human-readable form. + + This method rounds to 1 decimal place eg '1.2 Kb'. """ return _readable_units(bytes_, memory_divs) @@ -382,7 +385,8 @@ def _readable_units(value, divs, plural_aware=False): rounding = 0 if f > threshold else 1 f = round(f, rounding) f = int(f * 10) / 10.0 - if plural_aware and f == 1.0: + is_one = math.isclose(f, 1.0, rel_tol=1e-09, abs_tol=1e-09) + if plural_aware and is_one: unit = unit[:-1] txt = "%g %s" % (f, unit) break