test_time.py 8.8 KB
Newer Older
1
from test import test_support
2
import time
3
import unittest
4

5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

class TimeTestCase(unittest.TestCase):

    def setUp(self):
        self.t = time.time()

    def test_data_attributes(self):
        time.altzone
        time.daylight
        time.timezone
        time.tzname

    def test_clock(self):
        time.clock()

    def test_conversions(self):
21
        self.assertTrue(time.ctime(self.t)
22
                     == time.asctime(time.localtime(self.t)))
23
        self.assertTrue(long(time.mktime(time.localtime(self.t)))
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
                     == long(self.t))

    def test_sleep(self):
        time.sleep(1.2)

    def test_strftime(self):
        tt = time.gmtime(self.t)
        for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
                          'j', 'm', 'M', 'p', 'S',
                          'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
            format = ' %' + directive
            try:
                time.strftime(format, tt)
            except ValueError:
                self.fail('conversion specifier: %r failed.' % format)

40 41
    def test_strftime_bounds_checking(self):
        # Make sure that strftime() checks the bounds of the various parts
42
        #of the time tuple (0 is valid for *all* values).
43

44
        # Check year [1900, max(int)]
45 46 47 48 49 50 51
        self.assertRaises(ValueError, time.strftime, '',
                            (1899, 1, 1, 0, 0, 0, 0, 1, -1))
        if time.accept2dyear:
            self.assertRaises(ValueError, time.strftime, '',
                                (-1, 1, 1, 0, 0, 0, 0, 1, -1))
            self.assertRaises(ValueError, time.strftime, '',
                                (100, 1, 1, 0, 0, 0, 0, 1, -1))
52
        # Check month [1, 12] + zero support
53
        self.assertRaises(ValueError, time.strftime, '',
54
                            (1900, -1, 1, 0, 0, 0, 0, 1, -1))
55 56
        self.assertRaises(ValueError, time.strftime, '',
                            (1900, 13, 1, 0, 0, 0, 0, 1, -1))
57
        # Check day of month [1, 31] + zero support
58
        self.assertRaises(ValueError, time.strftime, '',
59
                            (1900, 1, -1, 0, 0, 0, 0, 1, -1))
60 61
        self.assertRaises(ValueError, time.strftime, '',
                            (1900, 1, 32, 0, 0, 0, 0, 1, -1))
62
        # Check hour [0, 23]
63 64 65 66
        self.assertRaises(ValueError, time.strftime, '',
                            (1900, 1, 1, -1, 0, 0, 0, 1, -1))
        self.assertRaises(ValueError, time.strftime, '',
                            (1900, 1, 1, 24, 0, 0, 0, 1, -1))
67
        # Check minute [0, 59]
68 69 70 71
        self.assertRaises(ValueError, time.strftime, '',
                            (1900, 1, 1, 0, -1, 0, 0, 1, -1))
        self.assertRaises(ValueError, time.strftime, '',
                            (1900, 1, 1, 0, 60, 0, 0, 1, -1))
72
        # Check second [0, 61]
73 74 75 76 77 78 79 80 81 82 83 84
        self.assertRaises(ValueError, time.strftime, '',
                            (1900, 1, 1, 0, 0, -1, 0, 1, -1))
        # C99 only requires allowing for one leap second, but Python's docs say
        # allow two leap seconds (0..61)
        self.assertRaises(ValueError, time.strftime, '',
                            (1900, 1, 1, 0, 0, 62, 0, 1, -1))
        # No check for upper-bound day of week;
        #  value forced into range by a ``% 7`` calculation.
        # Start check at -2 since gettmarg() increments value before taking
        #  modulo.
        self.assertRaises(ValueError, time.strftime, '',
                            (1900, 1, 1, 0, 0, 0, -2, 1, -1))
85
        # Check day of the year [1, 366] + zero support
86
        self.assertRaises(ValueError, time.strftime, '',
87
                            (1900, 1, 1, 0, 0, 0, 0, -1, -1))
88 89 90
        self.assertRaises(ValueError, time.strftime, '',
                            (1900, 1, 1, 0, 0, 0, 0, 367, -1))

91 92 93 94 95 96 97 98
    def test_default_values_for_zero(self):
        # Make sure that using all zeros uses the proper default values.
        # No test for daylight savings since strftime() does not change output
        # based on its value.
        expected = "2000 01 01 00 00 00 1 001"
        result = time.strftime("%Y %m %d %H %M %S %w %j", (0,)*9)
        self.assertEquals(expected, result)

99
    def test_strptime(self):
100 101
        # Should be able to go round-trip from strftime to strptime without
        # throwing an exception.
102 103 104 105
        tt = time.gmtime(self.t)
        for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
                          'j', 'm', 'M', 'p', 'S',
                          'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
106 107
            format = '%' + directive
            strf_output = time.strftime(format, tt)
108
            try:
109
                time.strptime(strf_output, format)
110
            except ValueError:
111 112
                self.fail("conversion specifier %r failed with '%s' input." %
                          (format, strf_output))
113

114 115 116 117
    def test_asctime(self):
        time.asctime(time.gmtime(self.t))
        self.assertRaises(TypeError, time.asctime, 0)

118
    def test_tzset(self):
119 120 121
        if not hasattr(time, "tzset"):
            return # Can't test this; don't want the test suite to fail

122 123
        from os import environ

Tim Peters's avatar
Tim Peters committed
124
        # Epoch time of midnight Dec 25th 2002. Never DST in northern
125
        # hemisphere.
Tim Peters's avatar
Tim Peters committed
126
        xmas2002 = 1040774400.0
127

128 129 130 131 132
        # These formats are correct for 2002, and possibly future years
        # This format is the 'standard' as documented at:
        # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
        # They are also documented in the tzset(3) man page on most Unix
        # systems.
Tim Peters's avatar
Tim Peters committed
133
        eastern = 'EST+05EDT,M4.1.0,M10.5.0'
134 135 136
        victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
        utc='UTC+0'

137 138 139 140
        org_TZ = environ.get('TZ',None)
        try:
            # Make sure we can switch to UTC time and results are correct
            # Note that unknown timezones default to UTC.
141 142
            # Note that altzone is undefined in UTC, as there is no DST
            environ['TZ'] = eastern
143
            time.tzset()
144
            environ['TZ'] = utc
145
            time.tzset()
146
            self.assertEqual(
147 148
                time.gmtime(xmas2002), time.localtime(xmas2002)
                )
149 150 151
            self.assertEqual(time.daylight, 0)
            self.assertEqual(time.timezone, 0)
            self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
152

153 154
            # Make sure we can switch to US/Eastern
            environ['TZ'] = eastern
155
            time.tzset()
156 157 158 159 160 161 162 163
            self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
            self.assertEqual(time.tzname, ('EST', 'EDT'))
            self.assertEqual(len(time.tzname), 2)
            self.assertEqual(time.daylight, 1)
            self.assertEqual(time.timezone, 18000)
            self.assertEqual(time.altzone, 14400)
            self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
            self.assertEqual(len(time.tzname), 2)
164 165 166 167

            # Now go to the southern hemisphere.
            environ['TZ'] = victoria
            time.tzset()
168 169 170 171 172 173 174 175
            self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
            self.assertTrue(time.tzname[0] == 'AEST', str(time.tzname[0]))
            self.assertTrue(time.tzname[1] == 'AEDT', str(time.tzname[1]))
            self.assertEqual(len(time.tzname), 2)
            self.assertEqual(time.daylight, 1)
            self.assertEqual(time.timezone, -36000)
            self.assertEqual(time.altzone, -39600)
            self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)
176 177 178 179 180 181 182 183

        finally:
            # Repair TZ environment variable in case any other tests
            # rely on it.
            if org_TZ is not None:
                environ['TZ'] = org_TZ
            elif environ.has_key('TZ'):
                del environ['TZ']
184
            time.tzset()
Tim Peters's avatar
Tim Peters committed
185

186 187 188 189 190 191 192 193
    def test_insane_timestamps(self):
        # It's possible that some platform maps time_t to double,
        # and that this test will fail there.  This test should
        # exempt such platforms (provided they return reasonable
        # results!).
        for func in time.ctime, time.gmtime, time.localtime:
            for unreasonable in -1e200, 1e200:
                self.assertRaises(ValueError, func, unreasonable)
194

195 196 197 198 199 200 201 202
    def test_ctime_without_arg(self):
        # Not sure how to check the values, since the clock could tick
        # at any time.  Make sure these are at least accepted and
        # don't raise errors.
        time.ctime()
        time.ctime(None)

    def test_gmtime_without_arg(self):
203 204 205 206
        gt0 = time.gmtime()
        gt1 = time.gmtime(None)
        t0 = time.mktime(gt0)
        t1 = time.mktime(gt1)
207
        self.assertTrue(0 <= (t1-t0) < 0.2)
208 209

    def test_localtime_without_arg(self):
210 211 212 213
        lt0 = time.localtime()
        lt1 = time.localtime(None)
        t0 = time.mktime(lt0)
        t1 = time.mktime(lt1)
214
        self.assertTrue(0 <= (t1-t0) < 0.2)
215

216 217 218 219 220 221
def test_main():
    test_support.run_unittest(TimeTestCase)


if __name__ == "__main__":
    test_main()