mirror of
https://github.com/netbox-community/netbox.git
synced 2025-08-09 09:08:15 -06:00
Changed humanize_megabytes
This commit is contained in:
parent
8e3d8ab6ed
commit
a1fd983173
@ -61,7 +61,7 @@
|
||||
{% if memory_sum %}
|
||||
{{ memory_sum|humanize_megabytes }}
|
||||
{% else %}
|
||||
{{ ''|placeholder }}
|
||||
{{ ''|placeholder }}
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
|
@ -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()
|
||||
|
25
netbox/utilities/tests/test_humanize_megabytes_helper.py
Normal file
25
netbox/utilities/tests/test_humanize_megabytes_helper.py
Normal 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")
|
Loading…
Reference in New Issue
Block a user