Changed humanize_megabytes

This commit is contained in:
Julio-Oliveira-Encora 2024-05-23 16:04:08 -03:00
parent 8e3d8ab6ed
commit a1fd983173
3 changed files with 49 additions and 7 deletions

View File

@ -61,7 +61,7 @@
{% if memory_sum %}
{{ memory_sum|humanize_megabytes }}
{% else %}
{{ ''|placeholder }}
{{ ''|placeholder }}
{% endif %}
</td>
</tr>

View File

@ -93,14 +93,31 @@ def humanize_speed(speed):
def humanize_megabytes(mb):
"""
Express a number of megabytes in the most suitable unit (e.g. gigabytes or terabytes).
It considers the mb value as megabytes and converts it to the most suitable unit.
"""
# Factors in bytes
factors = {
"mega": 1024 ** 2,
"giga": 1024 ** 3,
"tera": 1024 ** 4,
}
if not mb:
return ''
if not mb % 1048576: # 1024^2
return f'{int(mb / 1048576)} TB'
if not mb % 1024:
return f'{int(mb / 1024)} GB'
return f'{int(mb) / (1048576):.2f} MB'
return ""
print(factors['mega'])
bytes = int(mb * 1024**2)
if bytes >= factors["tera"]:
return f"{bytes / factors["tera"]:.2f} TB"
if bytes >= factors["giga"]:
return f"{bytes / factors["giga"]:.2f} GB"
if bytes >= factors["mega"]:
return f"{bytes / factors["mega"]:.2f} MB"
@register.filter()

View File

@ -0,0 +1,25 @@
from utilities.templatetags.helpers import humanize_megabytes
from utilities.testing import TestCase
class TestConvertByteSize(TestCase):
def test_humanize_megabytes_converts_megabytes(self):
"""Test that humanize_megabytes converts megabytes to the most suitable unit."""
self.assertEqual(humanize_megabytes(1), "1.00 MB")
def test_humanize_megabytes_converts_to_gigabytes(self):
"""Test that humanize_megabytes converts megabytes to gigabytes."""
self.assertEqual(humanize_megabytes(1024), "1.00 GB")
def test_humanize_megabytes_converts_to_terabytes(self):
"""Test that humanize_megabytes converts megabytes to terabytes."""
self.assertEqual(humanize_megabytes(1048576), "1.00 TB")
def test_humanize_megabytes_returns_empty_for_none(self):
"""Test that humanize_megabytes returns empty for None."""
self.assertEqual(humanize_megabytes(None), '')
def test_humanize_megabytes_without_unit(self):
"""Test that humanize_megabytes returns the value without unit."""
self.assertEqual(humanize_megabytes(123456789), "117.74 TB")