time_utils_unittest.py revision c9b79339b9792de002e9524e5303c475857c7192
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
5import contextlib
6import datetime
7import os
8import time
9import unittest
10
11import common
12
13from autotest_lib.client.common_lib import time_utils
14
15
16@contextlib.contextmanager
17def 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
35class 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
69if __name__ == '__main__':
70    unittest.main()
71