make sizes more readable with function file_helpers.size_str
authorChristian Herdtweck <christian.herdtweck@intra2net.com>
Fri, 5 Feb 2016 10:16:40 +0000 (11:16 +0100)
committerChristian Herdtweck <christian.herdtweck@intra2net.com>
Fri, 5 Feb 2016 10:16:40 +0000 (11:16 +0100)
src/file_helpers.py
test/test_file_helpers.py

index 79eb2b3..b9e932b 100644 (file)
@@ -108,8 +108,9 @@ class FilesystemFillState:
         self.mount_point = None
 
     def __str__(self):
-        return '[Filesystem {0} mounted at {1}: {2}% used]' \
-               .format(self.name, self.mount_point, int(round(self.capacity)))
+        return '[Filesystem {0} mounted at {1}: {2}/{3} used]' \
+               .format(self.name, self.mount_point,
+                       size_str(self.used), size_str(self.size))
 
 
 def get_filesystem_fill_states(method=FS_FILL_METHOD_STATVFS):
@@ -401,3 +402,26 @@ def find_mount_point(path):
     while not os.path.ismount(path):
         path = os.path.dirname(path)
     return path
+
+
+def size_str(byte_number):
+    """ round byte_number to something easily human-readable like '1.5G' """
+
+    units = 'B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'
+    factor = 1024
+    thresh_add_comma = 10.   # below this, return 1.2G, above this return 12G
+
+    curr_fac = 1
+    curr_num = float(byte_number)
+    for unit in units:
+        if curr_num > factor:
+            curr_num /= factor
+            continue
+        elif curr_num < thresh_add_comma and unit != 'B':   # e.g. 1.2G
+            return '{0:.1f}{1}'.format(curr_num, unit)
+        else:   # e.g. 12G or 1B
+            return '{0:d}{1}'.format(int(round(curr_num)), unit)
+
+    # have an impossible amount of data.  (>1024**4 GB)
+    # undo last "/factor" and show thousand-separator
+    return '{0:,d}{1}'.format(int(round(curr_num*factor)), units[-1])
index 31c5769..c58a619 100644 (file)
@@ -62,11 +62,11 @@ class FileHelperTester(unittest.TestCase):
         state.capacity = 90
         state.mount_point = '/not/mounted'
 
-        expect = '[Filesystem {0} mounted at {1}: {2}% used]' \
-                 .format(state.name, state.mount_point, state.capacity)
+        expect = '[Filesystem dummy mounted at /not/mounted: 9.0G/10G used]'
 
         self.assertEqual(str(state), expect)
 
+
     def test_disc_stats_df(self):
         """ tests get_filesystem_fill_states using df """