From 4fdedd09955867406dab6b673e7ac8daec62c6ce Mon Sep 17 00:00:00 2001 From: Michael Hanselmann <hansmi@google.com> Date: Mon, 8 Oct 2012 12:16:42 +0200 Subject: [PATCH] jstore: Nicer error message on non-numeric file content MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An error like βinvalid literal for int() with base 10β can be quite confusing. Signed-off-by: Michael Hanselmann <hansmi@google.com> Reviewed-by: Iustin Pop <iustin@google.com> --- lib/jstore.py | 9 ++++++++- test/ganeti.jstore_unittest.py | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/lib/jstore.py b/lib/jstore.py index 320a0341d..f20da0604 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 88512a6ef..bc24415ec 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() -- GitLab