summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDenis Laxalde <denis.laxalde@logilab.fr>2019-07-26 16:13:02 +0200
committerDenis Laxalde <denis.laxalde@logilab.fr>2019-07-26 16:13:02 +0200
commit131b6bd58b7aaed997576fe363da2c80fdcb0a67 (patch)
tree84e18d013b9a822b55cf5dd83d119789f29c0caa
parent0dc34dc2792b7c846b6d683cc251f05f065940e6 (diff)
downloadlogilab-common-131b6bd58b7aaed997576fe363da2c80fdcb0a67.tar.gz
Raise a ValueError in case of invalid unit in textutils.apply_units()
The original KeyError comes from 57e242dffe89 which no justification. I believe it was meant to be a ValueError as in other errors in this function. Also, _ensure_correctly_typed() in cubicweb/web/formfields.py will catch ValueError. Adding a test for this.
-rw-r--r--logilab/common/textutils.py4
-rw-r--r--test/unittest_textutils.py3
2 files changed, 5 insertions, 2 deletions
diff --git a/logilab/common/textutils.py b/logilab/common/textutils.py
index 356b1a8..95a5e00 100644
--- a/logilab/common/textutils.py
+++ b/logilab/common/textutils.py
@@ -371,8 +371,8 @@ def apply_units(string, units, inter=None, final=float, blank_reg=_BLANK_RE,
try:
value *= units[unit.lower()]
except KeyError:
- raise KeyError('invalid unit %s. valid units are %s' %
- (unit, units.keys()))
+ raise ValueError('invalid unit %s. valid units are %s' %
+ (unit, units.keys()))
values.append(value)
return final(sum(values))
diff --git a/test/unittest_textutils.py b/test/unittest_textutils.py
index 330d49c..2fa648a 100644
--- a/test/unittest_textutils.py
+++ b/test/unittest_textutils.py
@@ -190,6 +190,9 @@ class UnitsTC(TestCase):
self.assertRaises(ValueError, tu.apply_units, 'wrong input', self.units)
self.assertRaises(ValueError, tu.apply_units, 'wrong13 input', self.units)
self.assertRaises(ValueError, tu.apply_units, 'wrong input42', self.units)
+ with self.assertRaises(ValueError) as cm:
+ tu.apply_units('42 cakes', self.units)
+ self.assertIn('invalid unit cakes.', str(cm.exception))
RGX = re.compile('abcd')
class PrettyMatchTC(TestCase):