[master 2/3] Extend Size.convertTo() to work with arbitrary Size() values.
mulkieran
installerbot-noreply at redhat.com
Tue Jun 16 13:55:21 UTC 2015
From: mulhern <amulhern at redhat.com>
Related: #56
Signed-off-by: mulhern <amulhern at redhat.com>
---
blivet/size.py | 13 ++++++++++++-
tests/size_test.py | 10 ++++++++++
2 files changed, 22 insertions(+), 1 deletion(-)
diff --git a/blivet/size.py b/blivet/size.py
index 610b3ec..4904558 100644
--- a/blivet/size.py
+++ b/blivet/size.py
@@ -337,10 +337,21 @@ def convertTo(self, spec=None):
""" Return the size in the units indicated by the specifier.
:param spec: a units specifier
+ :type spec: a units specifier or :class:`Size`
:returns: a numeric value in the units indicated by the specifier
:rtype: Decimal
+ :raises ValueError: if Size unit specifier is non-positive
+
+ .. versionadded:: 1.6
+ spec parameter may be Size as well as units specifier.
"""
- return Decimal(self) / Decimal((spec or B).factor)
+ spec = B if spec is None else spec
+ factor = Decimal(getattr(spec, "factor", spec))
+
+ if factor <= 0:
+ raise ValueError("invalid conversion unit: %s" % factor)
+
+ return Decimal(self) / factor
def humanReadable(self, max_places=2, strip=True, min_value=1, xlate=True):
""" Return a string representation of this size with appropriate
diff --git a/tests/size_test.py b/tests/size_test.py
index e60f90a..cf076d2 100644
--- a/tests/size_test.py
+++ b/tests/size_test.py
@@ -179,6 +179,16 @@ def testConvertToPrecision(self):
self.assertEqual(s.convertTo(KiB), 1792)
self.assertEqual(s.convertTo(MiB), Decimal("1.75"))
+ def testConvertToWithSize(self):
+ s = Size(1835008)
+ self.assertEqual(s.convertTo(Size(1)), s.convertTo(B))
+ self.assertEqual(s.convertTo(Size(1024)), s.convertTo(KiB))
+ self.assertEqual(Size(512).convertTo(Size(1024)), Decimal("0.5"))
+ self.assertEqual(Size(1024).convertTo(Size(512)), Decimal(2))
+
+ with self.assertRaises(ValueError):
+ s.convertTo(Size(0))
+
def testNegative(self):
s = Size("-500MiB")
self.assertEqual(s.humanReadable(), "-500 MiB")
--
To view this commit on github, visit https://github.com/rhinstaller/blivet/commit/b4958003f27bf76affecbcedf82c4b969df135ea
More information about the anaconda-patches
mailing list