PageRenderTime 51ms CodeModel.GetById 25ms app.highlight 22ms RepoModel.GetById 2ms app.codeStats 0ms

/Lib/test/test_strftime.py

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