Merge pull request #525 from somospocos/bytefmt-refactor

bumblebee.util.bytefmt() refactor
This commit is contained in:
tobi-wan-kenobi 2020-01-13 14:15:21 +01:00 committed by GitHub
commit fd72d84fec
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 3 deletions

View file

@ -45,12 +45,24 @@ def execute(cmd, wait=True):
logging.info(u"command returned '{}'".format("" if not rv else rv))
return rv
def bytefmt(num):
def bytefmt(num, fmt="{:.2f}"):
"""
format a value of bytes to a more human readable pattern
example: 15 * 1024 becomes 15KiB
Args:
num (int): bytes
fmt (string): format
Return: string
"""
for unit in ["", "Ki", "Mi", "Gi"]:
if num < 1024.0:
return "{:.2f}{}B".format(num, unit)
return "{}{}B".format(fmt, unit).format(num)
num /= 1024.0
return "{:.2f}GiB".format(num*1024.0)
return "{}GiB".format(fmt).format(num*1024.0)
def durationfmt(duration, shorten=False, suffix=False):
duration = int(duration)

View file

@ -24,6 +24,13 @@ class TestUtil(unittest.TestCase):
self.assertEquals(bu.bytefmt(22 * 1024 * 1024 * 1024), "22.00GiB")
self.assertEquals(bu.bytefmt(35 * 1024 * 1024 * 1024 * 1024), "35840.00GiB")
fmt = "{:.0f}"
self.assertEquals(bu.bytefmt(10, fmt), "10B")
self.assertEquals(bu.bytefmt(15 * 1024, fmt), "15KiB")
self.assertEquals(bu.bytefmt(20 * 1024 * 1024, fmt), "20MiB")
self.assertEquals(bu.bytefmt(22 * 1024 * 1024 * 1024, fmt), "22GiB")
self.assertEquals(bu.bytefmt(35 * 1024 * 1024 * 1024 * 1024, fmt), "35840GiB")
def test_durationfmt(self):
self.assertEquals(bu.durationfmt(00), "00:00")
self.assertEquals(bu.durationfmt(25), "00:25")