1"""
2Unittest for time.strftime
3"""
4
5import calendar
6import sys
7import re
8from test import support
9import time
10import unittest
11
12
13# helper functions
14def fixasctime(s):
15    if s[8] == ' ':
16        s = s[:8] + '0' + s[9:]
17    return s
18
19def escapestr(text, ampm):
20    """
21    Escape text to deal with possible locale values that have regex
22    syntax while allowing regex syntax used for comparison.
23    """
24    new_text = re.escape(text)
25    new_text = new_text.replace(re.escape(ampm), ampm)
26    new_text = new_text.replace(r'\%', '%')
27    new_text = new_text.replace(r'\:', ':')
28    new_text = new_text.replace(r'\?', '?')
29    return new_text
30
31
32class StrftimeTest(unittest.TestCase):
33
34    def _update_variables(self, now):
35        # we must update the local variables on every cycle
36        self.gmt = time.gmtime(now)
37        now = time.localtime(now)
38
39        if now[3] < 12: self.ampm='(AM|am)'
40        else: self.ampm='(PM|pm)'
41
42        self.jan1 = time.localtime(time.mktime((now[0], 1, 1, 0, 0, 0, 0, 1, 0)))
43
44        try:
45            if now[8]: self.tz = time.tzname[1]
46            else: self.tz = time.tzname[0]
47        except AttributeError:
48            self.tz = ''
49
50        if now[3] > 12: self.clock12 = now[3] - 12
51        elif now[3] > 0: self.clock12 = now[3]
52        else: self.clock12 = 12
53
54        self.now = now
55
56    def setUp(self):
57        try:
58            import java
59            java.util.Locale.setDefault(java.util.Locale.US)
60        except ImportError:
61            import locale
62            locale.setlocale(locale.LC_TIME, 'C')
63
64    def test_strftime(self):
65        now = time.time()
66        self._update_variables(now)
67        self.strftest1(now)
68        self.strftest2(now)
69
70        if support.verbose:
71            print("Strftime test, platform: %s, Python version: %s" % \
72                  (sys.platform, sys.version.split()[0]))
73
74        for j in range(-5, 5):
75            for i in range(25):
76                arg = now + (i+j*100)*23*3603
77                self._update_variables(arg)
78                self.strftest1(arg)
79                self.strftest2(arg)
80
81    def strftest1(self, now):
82        if support.verbose:
83            print("strftime test for", time.ctime(now))
84        now = self.now
85        # Make sure any characters that could be taken as regex syntax is
86        # escaped in escapestr()
87        expectations = (
88            ('%a', calendar.day_abbr[now[6]], 'abbreviated weekday name'),
89            ('%A', calendar.day_name[now[6]], 'full weekday name'),
90            ('%b', calendar.month_abbr[now[1]], 'abbreviated month name'),
91            ('%B', calendar.month_name[now[1]], 'full month name'),
92            # %c see below
93            ('%d', '%02d' % now[2], 'day of month as number (00-31)'),
94            ('%H', '%02d' % now[3], 'hour (00-23)'),
95            ('%I', '%02d' % self.clock12, 'hour (01-12)'),
96            ('%j', '%03d' % now[7], 'julian day (001-366)'),
97            ('%m', '%02d' % now[1], 'month as number (01-12)'),
98            ('%M', '%02d' % now[4], 'minute, (00-59)'),
99            ('%p', self.ampm, 'AM or PM as appropriate'),
100            ('%S', '%02d' % now[5], 'seconds of current time (00-60)'),
101            ('%U', '%02d' % ((now[7] + self.jan1[6])//7),
102             'week number of the year (Sun 1st)'),
103            ('%w', '0?%d' % ((1+now[6]) % 7), 'weekday as a number (Sun 1st)'),
104            ('%W', '%02d' % ((now[7] + (self.jan1[6] - 1)%7)//7),
105            'week number of the year (Mon 1st)'),
106            # %x see below
107            ('%X', '%02d:%02d:%02d' % (now[3], now[4], now[5]), '%H:%M:%S'),
108            ('%y', '%02d' % (now[0]%100), 'year without century'),
109            ('%Y', '%d' % now[0], 'year with century'),
110            # %Z see below
111            ('%%', '%', 'single percent sign'),
112        )
113
114        for e in expectations:
115            # musn't raise a value error
116            try:
117                result = time.strftime(e[0], now)
118            except ValueError as error:
119                self.fail("strftime '%s' format gave error: %s" % (e[0], error))
120            if re.match(escapestr(e[1], self.ampm), result):
121                continue
122            if not result or result[0] == '%':
123                self.fail("strftime does not support standard '%s' format (%s)"
124                          % (e[0], e[2]))
125            else:
126                self.fail("Conflict for %s (%s): expected %s, but got %s"
127                          % (e[0], e[2], e[1], result))
128
129    def strftest2(self, now):
130        nowsecs = str(int(now))[:-1]
131        now = self.now
132
133        nonstandard_expectations = (
134        # These are standard but don't have predictable output
135            ('%c', fixasctime(time.asctime(now)), 'near-asctime() format'),
136            ('%x', '%02d/%02d/%02d' % (now[1], now[2], (now[0]%100)),
137            '%m/%d/%y %H:%M:%S'),
138            ('%Z', '%s' % self.tz, 'time zone name'),
139
140            # These are some platform specific extensions
141            ('%D', '%02d/%02d/%02d' % (now[1], now[2], (now[0]%100)), 'mm/dd/yy'),
142            ('%e', '%2d' % now[2], 'day of month as number, blank padded ( 0-31)'),
143            ('%h', calendar.month_abbr[now[1]], 'abbreviated month name'),
144            ('%k', '%2d' % now[3], 'hour, blank padded ( 0-23)'),
145            ('%n', '\n', 'newline character'),
146            ('%r', '%02d:%02d:%02d %s' % (self.clock12, now[4], now[5], self.ampm),
147            '%I:%M:%S %p'),
148            ('%R', '%02d:%02d' % (now[3], now[4]), '%H:%M'),
149            ('%s', nowsecs, 'seconds since the Epoch in UCT'),
150            ('%t', '\t', 'tab character'),
151            ('%T', '%02d:%02d:%02d' % (now[3], now[4], now[5]), '%H:%M:%S'),
152            ('%3y', '%03d' % (now[0]%100),
153            'year without century rendered using fieldwidth'),
154        )
155
156
157        for e in nonstandard_expectations:
158            try:
159                result = time.strftime(e[0], now)
160            except ValueError as result:
161                msg = "Error for nonstandard '%s' format (%s): %s" % \
162                      (e[0], e[2], str(result))
163                if support.verbose:
164                    print(msg)
165                continue
166            if re.match(escapestr(e[1], self.ampm), result):
167                if support.verbose:
168                    print("Supports nonstandard '%s' format (%s)" % (e[0], e[2]))
169            elif not result or result[0] == '%':
170                if support.verbose:
171                    print("Does not appear to support '%s' format (%s)" % \
172                           (e[0], e[2]))
173            else:
174                if support.verbose:
175                    print("Conflict for nonstandard '%s' format (%s):" % \
176                           (e[0], e[2]))
177                    print("  Expected %s, but got %s" % (e[1], result))
178
179
180class Y1900Tests(unittest.TestCase):
181    """A limitation of the MS C runtime library is that it crashes if
182    a date before 1900 is passed with a format string containing "%y"
183    """
184
185    def test_y_before_1900(self):
186        # Issue #13674, #19634
187        t = (1899, 1, 1, 0, 0, 0, 0, 0, 0)
188        if (sys.platform == "win32"
189        or sys.platform.startswith(("aix", "sunos", "solaris"))):
190            with self.assertRaises(ValueError):
191                time.strftime("%y", t)
192        else:
193            self.assertEqual(time.strftime("%y", t), "99")
194
195    def test_y_1900(self):
196        self.assertEqual(
197            time.strftime("%y", (1900, 1, 1, 0, 0, 0, 0, 0, 0)), "00")
198
199    def test_y_after_1900(self):
200        self.assertEqual(
201            time.strftime("%y", (2013, 1, 1, 0, 0, 0, 0, 0, 0)), "13")
202
203if __name__ == '__main__':
204    unittest.main()
205