An error like “invalid literal for int() with base 10” can be quite
confusing.
---
 lib/jstore.py                  |    9 ++++++++-
 test/ganeti.jstore_unittest.py |   19 +++++++++++++++++++
 2 files changed, 27 insertions(+), 1 deletions(-)

diff --git a/lib/jstore.py b/lib/jstore.py
index 320a034..f20da06 100644
--- a/lib/jstore.py
+++ b/lib/jstore.py
@@ -42,12 +42,19 @@ def _ReadNumericFile(file_name):
 
   """
   try:
-    return int(utils.ReadFile(file_name))
+    contents = utils.ReadFile(file_name)
   except EnvironmentError, err:
     if err.errno in (errno.ENOENT, ):
       return None
     raise
 
+  try:
+    return int(contents)
+  except (ValueError, TypeError), err:
+    # Couldn't convert to int
+    raise errors.JobQueueError("Content of file '%s' is not numeric: %s" %
+                               (file_name, err))
+
 
 def ReadSerial():
   """Read the serial file.
diff --git a/test/ganeti.jstore_unittest.py b/test/ganeti.jstore_unittest.py
index 88512a6..bc24415 100755
--- a/test/ganeti.jstore_unittest.py
+++ b/test/ganeti.jstore_unittest.py
@@ -78,5 +78,24 @@ class TestParseJobId(testutils.GanetiTestCase):
     self.assertRaises(errors.ParameterError, jstore.ParseJobId, [])
 
 
+class TestReadNumericFile(testutils.GanetiTestCase):
+  def testNonExistingFile(self):
+    result = jstore._ReadNumericFile("/tmp/this/file/does/not/exist")
+    self.assertTrue(result is None)
+
+  def testValidFile(self):
+    tmpfile = self._CreateTempFile()
+
+    for (data, exp) in [("123", 123), ("0\n", 0)]:
+      utils.WriteFile(tmpfile, data=data)
+      result = jstore._ReadNumericFile(tmpfile)
+      self.assertEqual(result, exp)
+
+  def testInvalidContent(self):
+    tmpfile = self._CreateTempFile()
+    utils.WriteFile(tmpfile, data="{wrong content")
+    self.assertRaises(errors.JobQueueError, jstore._ReadNumericFile, tmpfile)
+
+
 if __name__ == "__main__":
   testutils.GanetiTestProgram()
-- 
1.7.7.3

Reply via email to