Home | History | Annotate | Download | only in common_lib
      1 # Copyright (c) 2014 The Chromium Authors. All rights reserved.
      2 # Use of this source code is governed by a BSD-style license that can be
      3 # found in the LICENSE file.
      4 
      5 import contextlib
      6 import datetime
      7 import os
      8 import time
      9 import unittest
     10 
     11 import common
     12 
     13 from autotest_lib.client.common_lib import time_utils
     14 
     15 
     16 @contextlib.contextmanager
     17 def set_time_zone(tz):
     18     """Temporarily set the timezone to the specified value.
     19 
     20     This is needed because the unittest can be run in a server not in PST.
     21 
     22     @param tz: Name of the timezone for test, e.g., US/Pacific
     23     """
     24     old_environ = os.environ.copy()
     25     try:
     26         os.environ['TZ'] = tz
     27         time.tzset()
     28         yield
     29     finally:
     30         os.environ.clear()
     31         os.environ.update(old_environ)
     32         time.tzset()
     33 
     34 
     35 class time_utils_unittest(unittest.TestCase):
     36     """Unittest for time_utils function."""
     37 
     38     TIME_STRING = "2014-08-20 14:23:56"
     39     TIME_SECONDS = 1408569836
     40     TIME_OBJ = datetime.datetime(year=2014, month=8, day=20, hour=14,
     41                                  minute=23, second=56)
     42 
     43     def test_date_string_to_epoch_time(self):
     44         """Test date parsing in date_string_to_epoch_time()."""
     45         with set_time_zone('US/Pacific'):
     46             parsed_seconds = time_utils.date_string_to_epoch_time(
     47                     self.TIME_STRING)
     48             self.assertEqual(self.TIME_SECONDS, parsed_seconds)
     49 
     50 
     51     def test_epoch_time_to_date_string(self):
     52         """Test function epoch_time_to_date_string."""
     53         with set_time_zone('US/Pacific'):
     54             time_string = time_utils.epoch_time_to_date_string(
     55                     self.TIME_SECONDS)
     56             self.assertEqual(self.TIME_STRING, time_string)
     57 
     58 
     59     def test_to_epoch_time_success(self):
     60         """Test function to_epoch_time."""
     61         with set_time_zone('US/Pacific'):
     62             self.assertEqual(self.TIME_SECONDS,
     63                              time_utils.to_epoch_time(self.TIME_STRING))
     64 
     65             self.assertEqual(self.TIME_SECONDS,
     66                              time_utils.to_epoch_time(self.TIME_OBJ))
     67 
     68 
     69 if __name__ == '__main__':
     70     unittest.main()
     71