diff --git a/lib/jstore.py b/lib/jstore.py index 320a0341db0ad5c40e68e749a7aea8fb93f195b4..f20da060408ae17ef77c568048105d71bf842d5f 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 88512a6ef9f226035d150c4118538cba7cb0be8f..bc24415ec923ca8ee2fd2df629184d0ec3b92e30 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()