Commit 3b813dd2 authored by Iustin Pop's avatar Iustin Pop
Browse files

Add utils.FormatTime and a simple unittest



We don't format with subsecond-precision.
Signed-off-by: default avatarIustin Pop <iustin@google.com>
Reviewed-by: default avatarMichael Hanselmann <hansmi@google.com>
parent 03298ebe
......@@ -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.
......
......@@ -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()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment