Skip to content

Commit 199475a

Browse files
authored
Merge pull request #6166 from wangp-h/master
Add support for decimal values and flexible formatting in DataSize
2 parents 4fad5c6 + 3533673 commit 199475a

File tree

2 files changed

+10
-14
lines changed

2 files changed

+10
-14
lines changed

avocado/utils/data_structures.py

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525

2626

2727
import math
28+
import re
2829
import sys
2930

3031

@@ -328,23 +329,20 @@ class DataSize:
328329

329330
def __init__(self, data):
330331
try:
331-
norm_size = data.strip().lower()
332-
last = norm_size[-1]
333-
if last.isdigit():
334-
self._value = int(norm_size)
335-
self._unit = "b"
336-
elif last in self.MULTIPLIERS:
337-
self._value = int(norm_size[:-1])
338-
self._unit = last
339-
else:
332+
norm = str(data).strip().lower()
333+
match = re.match(r"^(\d+(\.\d+)?)(?:\s*([bkmgt]))?$", norm)
334+
if not match:
340335
raise ValueError
341336

342-
if self._value < 0:
337+
self._value = float(match.group(1))
338+
self._unit = match.group(3) or "b"
339+
340+
if self._unit not in self.MULTIPLIERS or self._value < 0:
343341
raise ValueError
344342

345343
except ValueError as exc:
346344
raise InvalidDataSize(
347-
'String not in size + unit format (i.e. "10M", "100k", ...)'
345+
f"Invalid data size '{data}'. Use formats like '10M', '2.5G', or '100'."
348346
) from exc
349347

350348
@property

selftests/unit/utils/data_structures.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -128,9 +128,6 @@ def test_invalid(self):
128128
self.assertRaises(
129129
data_structures.InvalidDataSize, data_structures.DataSize, "-100t"
130130
)
131-
self.assertRaises(
132-
data_structures.InvalidDataSize, data_structures.DataSize, "0.5g"
133-
)
134131
self.assertRaises(
135132
data_structures.InvalidDataSize, data_structures.DataSize, "10Mb"
136133
)
@@ -142,6 +139,7 @@ def test_value_and_type(self):
142139
def test_values(self):
143140
self.assertEqual(data_structures.DataSize("10m").b, 10485760)
144141
self.assertEqual(data_structures.DataSize("10M").b, 10485760)
142+
self.assertEqual(data_structures.DataSize("0.5g").b, 536870912)
145143

146144

147145
if __name__ == "__main__":

0 commit comments

Comments
 (0)