diff --git a/lib/utils.py b/lib/utils.py index 0af26132af8fd49b70cfdb871cba8e24fc96222b..5aaa0ca7f94a5436a9134914c985610d0b0d5e81 100644 --- a/lib/utils.py +++ b/lib/utils.py @@ -1934,6 +1934,21 @@ def LockFile(fd): raise +def FormatTime(val): + """Formats a time value. + + @type val: float or None + @param val: the timestamp as returned by time.time() + @return: a string value or N/A if we don't have a valid timestamp + + """ + if val is None or not isinstance(val, (int, float)): + return "N/A" + # these two codes works on Linux, but they are not guaranteed on all + # platforms + return time.strftime("%F %T", time.localtime(val)) + + class FileLock(object): """Utility class for file locks. diff --git a/test/ganeti.utils_unittest.py b/test/ganeti.utils_unittest.py index 415ffa7d6b3e47cc2ec6fba343a556b4221c19f4..5abe8a2b612cab17b2ec1be8d1acb2a4a5c41ad1 100755 --- a/test/ganeti.utils_unittest.py +++ b/test/ganeti.utils_unittest.py @@ -45,7 +45,7 @@ from ganeti.utils import IsProcessAlive, RunCmd, \ ParseUnit, AddAuthorizedKey, RemoveAuthorizedKey, \ ShellQuote, ShellQuoteArgs, TcpPing, ListVisibleFiles, \ SetEtcHostsEntry, RemoveEtcHostsEntry, FirstFree, OwnIpAddress, \ - TailFile, ForceDictType, SafeEncode, IsNormAbsPath + TailFile, ForceDictType, SafeEncode, IsNormAbsPath, FormatTime from ganeti.errors import LockError, UnitParseError, GenericError, \ ProgrammerError @@ -987,5 +987,21 @@ class TestSafeEncode(unittest.TestCase): self.failUnlessEqual(txt, SafeEncode(txt)) +class TestFormatTime(unittest.TestCase): + """Testing case for FormatTime""" + + def testNone(self): + self.failUnlessEqual(FormatTime(None), "N/A") + + def testInvalid(self): + self.failUnlessEqual(FormatTime(()), "N/A") + + def testNow(self): + # tests that we accept time.time input + FormatTime(time.time()) + # tests that we accept int input + FormatTime(int(time.time())) + + if __name__ == '__main__': unittest.main()