fixed broken filesizeformat #53

Closed
wants to merge 2 commits into
from
View
@@ -337,7 +337,7 @@ def do_random(environment, seq):
return environment.undefined('No random item, sequence was empty.')
-def do_filesizeformat(value, binary=False):
+def do_filesizeformat(value, binary=False, precision=1):
"""Format the value like a 'human-readable' file size (i.e. 13 kB,
4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,
Giga, etc.), if the second parameter is set to `True` the binary
@@ -361,10 +361,10 @@ def do_filesizeformat(value, binary=False):
return "%d Bytes" % bytes
else:
for i, prefix in enumerate(prefixes):
- unit = base * base ** (i + 1)
+ unit = base ** (i + 2)
if bytes < unit:
- return "%.1f %s" % ((bytes / unit), prefix)
- return "%.1f %s" % ((bytes / unit), prefix)
+ return "%.*f %s" % (precision, base * bytes / unit, prefix)
+ return "%.*f %s" % (precision, base * bytes / unit, prefix)
def do_pprint(value, verbose=False):
@@ -73,20 +73,23 @@ def test_striptags(self):
def test_filesizeformat(self):
tmpl = env.from_string(
'{{ 100|filesizeformat }}|'
- '{{ 1000|filesizeformat }}|'
- '{{ 1000000|filesizeformat }}|'
- '{{ 1000000000|filesizeformat }}|'
- '{{ 1000000000000|filesizeformat }}|'
- '{{ 100|filesizeformat(true) }}|'
+ '{{ (10**3)|filesizeformat }}|'
+ '{{ (10**6)|filesizeformat }}|'
+ '{{ (10**9)|filesizeformat }}|'
+ '{{ (10**12)|filesizeformat }}|'
'{{ 1000|filesizeformat(true) }}|'
- '{{ 1000000|filesizeformat(true) }}|'
- '{{ 1000000000|filesizeformat(true) }}|'
- '{{ 1000000000000|filesizeformat(true) }}'
+ '{{ (2**10)|filesizeformat(true) }}|'
+ '{{ (2**20)|filesizeformat(true) }}|'
+ '{{ (2**30)|filesizeformat(true) }}|'
+ '{{ (2**40)|filesizeformat(true) }}|'
+ '{{ (10**3)|filesizeformat(binary=false, precision=2) }}|'
+ '{{ (2**10)|filesizeformat(binary=true, precision=2) }}'
)
out = tmpl.render()
assert out == (
- '100 Bytes|0.0 kB|0.0 MB|0.0 GB|0.0 TB|100 Bytes|'
- '1000 Bytes|1.0 KiB|0.9 MiB|0.9 GiB'
+ '100 Bytes|1.0 kB|1.0 MB|1.0 GB|1.0 TB|'
+ '1000 Bytes|1.0 KiB|1.0 MiB|1.0 GiB|1.0 TiB|'
+ '1.00 kB|1.00 KiB'
)
def test_first(self):