blob: 8afd5b8f1fa53d72ec6af639797cba8197e91742 [file] [log] [blame]
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001from test.support import verbose, TestFailed
Victor Stinner41a863c2012-02-24 00:37:51 +01002import locale
Eric S. Raymondd8c628b2001-02-09 11:46:37 +00003import sys
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004import test.support as support
Christian Heimesf6cd9672008-03-26 13:45:42 +00005import unittest
6
Benjamin Petersonee8712c2008-05-20 21:35:26 +00007maxsize = support.MAX_Py_ssize_t
Marc-André Lemburgd70141a2000-06-30 10:26:29 +00008
9# test string formatting operator (I am not sure if this is being tested
10# elsewhere but, surely, some of the given cases are *not* tested because
11# they crash python)
Ethan Furmanb95b5612015-01-23 20:05:18 -080012# test on bytes object as well
Marc-André Lemburgd70141a2000-06-30 10:26:29 +000013
Mark Dickinsonb7be5702010-02-23 13:20:58 +000014def testformat(formatstr, args, output=None, limit=None, overflowok=False):
Tim Peters38fd5b62000-09-21 05:43:11 +000015 if verbose:
16 if output:
Ezio Melotti507eb092013-02-23 07:53:56 +020017 print("{!a} % {!a} =? {!a} ...".format(formatstr, args, output),
18 end=' ')
Tim Peters38fd5b62000-09-21 05:43:11 +000019 else:
Ezio Melotti507eb092013-02-23 07:53:56 +020020 print("{!a} % {!a} works? ...".format(formatstr, args), end=' ')
Tim Peters38fd5b62000-09-21 05:43:11 +000021 try:
22 result = formatstr % args
23 except OverflowError:
24 if not overflowok:
25 raise
26 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000027 print('overflow (this is fine)')
Tim Peters38fd5b62000-09-21 05:43:11 +000028 else:
Mark Dickinson5354a1f2010-02-07 13:15:37 +000029 if output and limit is None and result != output:
Guido van Rossumb5a755e2007-07-18 18:15:48 +000030 if verbose:
31 print('no')
Christian Heimesf6cd9672008-03-26 13:45:42 +000032 raise AssertionError("%r %% %r == %r != %r" %
33 (formatstr, args, result, output))
Christian Heimesa612dc02008-02-24 13:08:18 +000034 # when 'limit' is specified, it determines how many characters
35 # must match exactly; lengths must always match.
36 # ex: limit=5, '12345678' matches '12345___'
37 # (mainly for floating point format tests for which an exact match
38 # can't be guaranteed due to rounding and representation errors)
39 elif output and limit is not None and (
40 len(result)!=len(output) or result[:limit]!=output[:limit]):
41 if verbose:
42 print('no')
43 print("%s %% %s == %s != %s" % \
44 (repr(formatstr), repr(args), repr(result), repr(output)))
Tim Peters38fd5b62000-09-21 05:43:11 +000045 else:
46 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000047 print('yes')
Marc-André Lemburgd70141a2000-06-30 10:26:29 +000048
Ethan Furmanb95b5612015-01-23 20:05:18 -080049def testcommon(formatstr, args, output=None, limit=None, overflowok=False):
50 # if formatstr is a str, test str, bytes, and bytearray;
51 # otherwise, test bytes and bytearry
52 if isinstance(formatstr, str):
53 testformat(formatstr, args, output, limit, overflowok)
54 b_format = formatstr.encode('ascii')
55 else:
56 b_format = formatstr
57 ba_format = bytearray(b_format)
58 b_args = []
59 if not isinstance(args, tuple):
60 args = (args, )
61 b_args = tuple(args)
62 if output is None:
63 b_output = ba_output = None
64 else:
65 if isinstance(output, str):
66 b_output = output.encode('ascii')
67 else:
68 b_output = output
69 ba_output = bytearray(b_output)
70 testformat(b_format, b_args, b_output, limit, overflowok)
71 testformat(ba_format, b_args, ba_output, limit, overflowok)
72
Tim Peters38fd5b62000-09-21 05:43:11 +000073
Christian Heimesf6cd9672008-03-26 13:45:42 +000074class FormatTest(unittest.TestCase):
Ethan Furmanb95b5612015-01-23 20:05:18 -080075
76 def test_common_format(self):
77 # test the format identifiers that work the same across
78 # str, bytes, and bytearrays (integer, float, oct, hex)
79 testcommon("%.1d", (1,), "1")
80 testcommon("%.*d", (sys.maxsize,1), overflowok=True) # expect overflow
81 testcommon("%.100d", (1,), '00000000000000000000000000000000000000'
Mark Dickinsonb7be5702010-02-23 13:20:58 +000082 '000000000000000000000000000000000000000000000000000000'
83 '00000001', overflowok=True)
Ethan Furmanb95b5612015-01-23 20:05:18 -080084 testcommon("%#.117x", (1,), '0x00000000000000000000000000000000000'
Mark Dickinsonb7be5702010-02-23 13:20:58 +000085 '000000000000000000000000000000000000000000000000000000'
86 '0000000000000000000000000001',
87 overflowok=True)
Ethan Furmanb95b5612015-01-23 20:05:18 -080088 testcommon("%#.118x", (1,), '0x00000000000000000000000000000000000'
Mark Dickinsonb7be5702010-02-23 13:20:58 +000089 '000000000000000000000000000000000000000000000000000000'
90 '00000000000000000000000000001',
91 overflowok=True)
Marc-André Lemburgd70141a2000-06-30 10:26:29 +000092
Ethan Furmanb95b5612015-01-23 20:05:18 -080093 testcommon("%f", (1.0,), "1.000000")
Christian Heimesf6cd9672008-03-26 13:45:42 +000094 # these are trying to test the limits of the internal magic-number-length
95 # formatting buffer, if that number changes then these tests are less
96 # effective
Ethan Furmanb95b5612015-01-23 20:05:18 -080097 testcommon("%#.*g", (109, -1.e+49/3.))
98 testcommon("%#.*g", (110, -1.e+49/3.))
99 testcommon("%#.*g", (110, -1.e+100/3.))
Christian Heimesf6cd9672008-03-26 13:45:42 +0000100 # test some ridiculously large precision, expect overflow
Ethan Furmanb95b5612015-01-23 20:05:18 -0800101 testcommon('%12.*f', (123456, 1.0))
Mark Dickinson5354a1f2010-02-07 13:15:37 +0000102
Christian Heimesf6cd9672008-03-26 13:45:42 +0000103 # check for internal overflow validation on length of precision
Mark Dickinson5354a1f2010-02-07 13:15:37 +0000104 # these tests should no longer cause overflow in Python
105 # 2.7/3.1 and later.
Ethan Furmanb95b5612015-01-23 20:05:18 -0800106 testcommon("%#.*g", (110, -1.e+100/3.))
107 testcommon("%#.*G", (110, -1.e+100/3.))
108 testcommon("%#.*f", (110, -1.e+100/3.))
109 testcommon("%#.*F", (110, -1.e+100/3.))
Christian Heimesf6cd9672008-03-26 13:45:42 +0000110 # Formatting of integers. Overflow is not ok
Ethan Furmanb95b5612015-01-23 20:05:18 -0800111 testcommon("%x", 10, "a")
112 testcommon("%x", 100000000000, "174876e800")
113 testcommon("%o", 10, "12")
114 testcommon("%o", 100000000000, "1351035564000")
115 testcommon("%d", 10, "10")
116 testcommon("%d", 100000000000, "100000000000")
Christian Heimesf6cd9672008-03-26 13:45:42 +0000117 big = 123456789012345678901234567890
Ethan Furmanb95b5612015-01-23 20:05:18 -0800118 testcommon("%d", big, "123456789012345678901234567890")
119 testcommon("%d", -big, "-123456789012345678901234567890")
120 testcommon("%5d", -big, "-123456789012345678901234567890")
121 testcommon("%31d", -big, "-123456789012345678901234567890")
122 testcommon("%32d", -big, " -123456789012345678901234567890")
123 testcommon("%-32d", -big, "-123456789012345678901234567890 ")
124 testcommon("%032d", -big, "-0123456789012345678901234567890")
125 testcommon("%-032d", -big, "-123456789012345678901234567890 ")
126 testcommon("%034d", -big, "-000123456789012345678901234567890")
127 testcommon("%034d", big, "0000123456789012345678901234567890")
128 testcommon("%0+34d", big, "+000123456789012345678901234567890")
129 testcommon("%+34d", big, " +123456789012345678901234567890")
130 testcommon("%34d", big, " 123456789012345678901234567890")
131 testcommon("%.2d", big, "123456789012345678901234567890")
132 testcommon("%.30d", big, "123456789012345678901234567890")
133 testcommon("%.31d", big, "0123456789012345678901234567890")
134 testcommon("%32.31d", big, " 0123456789012345678901234567890")
135 testcommon("%d", float(big), "123456________________________", 6)
Christian Heimesf6cd9672008-03-26 13:45:42 +0000136 big = 0x1234567890abcdef12345 # 21 hex digits
Ethan Furmanb95b5612015-01-23 20:05:18 -0800137 testcommon("%x", big, "1234567890abcdef12345")
138 testcommon("%x", -big, "-1234567890abcdef12345")
139 testcommon("%5x", -big, "-1234567890abcdef12345")
140 testcommon("%22x", -big, "-1234567890abcdef12345")
141 testcommon("%23x", -big, " -1234567890abcdef12345")
142 testcommon("%-23x", -big, "-1234567890abcdef12345 ")
143 testcommon("%023x", -big, "-01234567890abcdef12345")
144 testcommon("%-023x", -big, "-1234567890abcdef12345 ")
145 testcommon("%025x", -big, "-0001234567890abcdef12345")
146 testcommon("%025x", big, "00001234567890abcdef12345")
147 testcommon("%0+25x", big, "+0001234567890abcdef12345")
148 testcommon("%+25x", big, " +1234567890abcdef12345")
149 testcommon("%25x", big, " 1234567890abcdef12345")
150 testcommon("%.2x", big, "1234567890abcdef12345")
151 testcommon("%.21x", big, "1234567890abcdef12345")
152 testcommon("%.22x", big, "01234567890abcdef12345")
153 testcommon("%23.22x", big, " 01234567890abcdef12345")
154 testcommon("%-23.22x", big, "01234567890abcdef12345 ")
155 testcommon("%X", big, "1234567890ABCDEF12345")
156 testcommon("%#X", big, "0X1234567890ABCDEF12345")
157 testcommon("%#x", big, "0x1234567890abcdef12345")
158 testcommon("%#x", -big, "-0x1234567890abcdef12345")
159 testcommon("%#.23x", -big, "-0x001234567890abcdef12345")
160 testcommon("%#+.23x", big, "+0x001234567890abcdef12345")
161 testcommon("%# .23x", big, " 0x001234567890abcdef12345")
162 testcommon("%#+.23X", big, "+0X001234567890ABCDEF12345")
163 testcommon("%#-+.23X", big, "+0X001234567890ABCDEF12345")
164 testcommon("%#-+26.23X", big, "+0X001234567890ABCDEF12345")
165 testcommon("%#-+27.23X", big, "+0X001234567890ABCDEF12345 ")
166 testcommon("%#+27.23X", big, " +0X001234567890ABCDEF12345")
Christian Heimesf6cd9672008-03-26 13:45:42 +0000167 # next one gets two leading zeroes from precision, and another from the
168 # 0 flag and the width
Ethan Furmanb95b5612015-01-23 20:05:18 -0800169 testcommon("%#+027.23X", big, "+0X0001234567890ABCDEF12345")
Christian Heimesf6cd9672008-03-26 13:45:42 +0000170 # same, except no 0 flag
Ethan Furmanb95b5612015-01-23 20:05:18 -0800171 testcommon("%#+27.23X", big, " +0X001234567890ABCDEF12345")
Christian Heimesf6cd9672008-03-26 13:45:42 +0000172 big = 0o12345670123456701234567012345670 # 32 octal digits
Ethan Furmanb95b5612015-01-23 20:05:18 -0800173 testcommon("%o", big, "12345670123456701234567012345670")
174 testcommon("%o", -big, "-12345670123456701234567012345670")
175 testcommon("%5o", -big, "-12345670123456701234567012345670")
176 testcommon("%33o", -big, "-12345670123456701234567012345670")
177 testcommon("%34o", -big, " -12345670123456701234567012345670")
178 testcommon("%-34o", -big, "-12345670123456701234567012345670 ")
179 testcommon("%034o", -big, "-012345670123456701234567012345670")
180 testcommon("%-034o", -big, "-12345670123456701234567012345670 ")
181 testcommon("%036o", -big, "-00012345670123456701234567012345670")
182 testcommon("%036o", big, "000012345670123456701234567012345670")
183 testcommon("%0+36o", big, "+00012345670123456701234567012345670")
184 testcommon("%+36o", big, " +12345670123456701234567012345670")
185 testcommon("%36o", big, " 12345670123456701234567012345670")
186 testcommon("%.2o", big, "12345670123456701234567012345670")
187 testcommon("%.32o", big, "12345670123456701234567012345670")
188 testcommon("%.33o", big, "012345670123456701234567012345670")
189 testcommon("%34.33o", big, " 012345670123456701234567012345670")
190 testcommon("%-34.33o", big, "012345670123456701234567012345670 ")
191 testcommon("%o", big, "12345670123456701234567012345670")
192 testcommon("%#o", big, "0o12345670123456701234567012345670")
193 testcommon("%#o", -big, "-0o12345670123456701234567012345670")
194 testcommon("%#.34o", -big, "-0o0012345670123456701234567012345670")
195 testcommon("%#+.34o", big, "+0o0012345670123456701234567012345670")
196 testcommon("%# .34o", big, " 0o0012345670123456701234567012345670")
197 testcommon("%#+.34o", big, "+0o0012345670123456701234567012345670")
198 testcommon("%#-+.34o", big, "+0o0012345670123456701234567012345670")
199 testcommon("%#-+37.34o", big, "+0o0012345670123456701234567012345670")
200 testcommon("%#+37.34o", big, "+0o0012345670123456701234567012345670")
Christian Heimesf6cd9672008-03-26 13:45:42 +0000201 # next one gets one leading zero from precision
Ethan Furmanb95b5612015-01-23 20:05:18 -0800202 testcommon("%.33o", big, "012345670123456701234567012345670")
Christian Heimesf6cd9672008-03-26 13:45:42 +0000203 # base marker shouldn't change that, since "0" is redundant
Ethan Furmanb95b5612015-01-23 20:05:18 -0800204 testcommon("%#.33o", big, "0o012345670123456701234567012345670")
Christian Heimesf6cd9672008-03-26 13:45:42 +0000205 # but reduce precision, and base marker should add a zero
Ethan Furmanb95b5612015-01-23 20:05:18 -0800206 testcommon("%#.32o", big, "0o12345670123456701234567012345670")
Christian Heimesf6cd9672008-03-26 13:45:42 +0000207 # one leading zero from precision, and another from "0" flag & width
Ethan Furmanb95b5612015-01-23 20:05:18 -0800208 testcommon("%034.33o", big, "0012345670123456701234567012345670")
Christian Heimesf6cd9672008-03-26 13:45:42 +0000209 # base marker shouldn't change that
Ethan Furmanb95b5612015-01-23 20:05:18 -0800210 testcommon("%0#34.33o", big, "0o012345670123456701234567012345670")
Christian Heimesf6cd9672008-03-26 13:45:42 +0000211 # Some small ints, in both Python int and flavors).
Ethan Furmanb95b5612015-01-23 20:05:18 -0800212 testcommon("%d", 42, "42")
213 testcommon("%d", -42, "-42")
214 testcommon("%d", 42, "42")
215 testcommon("%d", -42, "-42")
216 testcommon("%d", 42.0, "42")
217 testcommon("%#x", 1, "0x1")
218 testcommon("%#x", 1, "0x1")
219 testcommon("%#X", 1, "0X1")
220 testcommon("%#X", 1, "0X1")
221 testcommon("%#o", 1, "0o1")
222 testcommon("%#o", 1, "0o1")
223 testcommon("%#o", 0, "0o0")
224 testcommon("%#o", 0, "0o0")
225 testcommon("%o", 0, "0")
226 testcommon("%o", 0, "0")
227 testcommon("%d", 0, "0")
228 testcommon("%d", 0, "0")
229 testcommon("%#x", 0, "0x0")
230 testcommon("%#x", 0, "0x0")
231 testcommon("%#X", 0, "0X0")
232 testcommon("%#X", 0, "0X0")
233 testcommon("%x", 0x42, "42")
234 testcommon("%x", -0x42, "-42")
235 testcommon("%x", 0x42, "42")
236 testcommon("%x", -0x42, "-42")
237 testcommon("%o", 0o42, "42")
238 testcommon("%o", -0o42, "-42")
239 testcommon("%o", 0o42, "42")
240 testcommon("%o", -0o42, "-42")
241 # alternate float formatting
242 testcommon('%g', 1.1, '1.1')
243 testcommon('%#g', 1.1, '1.10000')
244
245 def test_str_format(self):
Amaury Forgeot d'Arca083f1e2008-09-10 23:51:42 +0000246 testformat("%r", "\u0378", "'\\u0378'") # non printable
247 testformat("%a", "\u0378", "'\\u0378'") # non printable
Amaury Forgeot d'Arca819caa2008-07-04 17:57:09 +0000248 testformat("%r", "\u0374", "'\u0374'") # printable
249 testformat("%a", "\u0374", "'\\u0374'") # printable
Eric Smith0923d1d2009-04-16 20:16:10 +0000250
Ethan Furmanb95b5612015-01-23 20:05:18 -0800251 # Test exception for unknown format characters, etc.
Christian Heimesf6cd9672008-03-26 13:45:42 +0000252 if verbose:
253 print('Testing exceptions')
254 def test_exc(formatstr, args, exception, excmsg):
255 try:
256 testformat(formatstr, args)
257 except exception as exc:
258 if str(exc) == excmsg:
259 if verbose:
260 print("yes")
261 else:
262 if verbose: print('no')
263 print('Unexpected ', exception, ':', repr(str(exc)))
264 except:
265 if verbose: print('no')
266 print('Unexpected exception')
267 raise
268 else:
269 raise TestFailed('did not get expected exception: %s' % excmsg)
Georg Brandl559e5d72008-06-11 18:37:52 +0000270 test_exc('abc %b', 1, ValueError,
271 "unsupported format character 'b' (0x62) at index 5")
Christian Heimesf6cd9672008-03-26 13:45:42 +0000272 #test_exc(unicode('abc %\u3000','raw-unicode-escape'), 1, ValueError,
273 # "unsupported format character '?' (0x3000) at index 5")
274 test_exc('%d', '1', TypeError, "%d format: a number is required, not str")
Serhiy Storchakade1c27f2015-04-04 17:29:28 +0300275 test_exc('%x', '1', TypeError, "%x format: an integer is required, not str")
Serhiy Storchaka2c7b5a92015-03-30 09:19:08 +0300276 test_exc('%x', 3.14, TypeError, "%x format: an integer is required, not float")
Serhiy Storchaka6db1f6f2016-06-06 13:00:03 +0300277 test_exc('%g', '1', TypeError, "must be real number, not str")
Christian Heimesf6cd9672008-03-26 13:45:42 +0000278 test_exc('no format', '1', TypeError,
279 "not all arguments converted during string formatting")
Serhiy Storchaka2c7b5a92015-03-30 09:19:08 +0300280 test_exc('%c', -1, OverflowError, "%c arg not in range(0x110000)")
281 test_exc('%c', sys.maxunicode+1, OverflowError,
282 "%c arg not in range(0x110000)")
283 #test_exc('%c', 2**128, OverflowError, "%c arg not in range(0x110000)")
284 test_exc('%c', 3.14, TypeError, "%c requires int or char")
285 test_exc('%c', 'ab', TypeError, "%c requires int or char")
286 test_exc('%c', b'x', TypeError, "%c requires int or char")
Ethan Furmanb95b5612015-01-23 20:05:18 -0800287
288 if maxsize == 2**31-1:
289 # crashes 2.2.1 and earlier:
290 try:
291 "%*d"%(maxsize, -127)
292 except MemoryError:
293 pass
294 else:
295 raise TestFailed('"%*d"%(maxsize, -127) should fail')
296
297 def test_bytes_and_bytearray_format(self):
298 # %c will insert a single byte, either from an int in range(256), or
299 # from a bytes argument of length 1, not from a str.
300 testcommon(b"%c", 7, b"\x07")
301 testcommon(b"%c", b"Z", b"Z")
302 testcommon(b"%c", bytearray(b"Z"), b"Z")
Victor Stinner0cdad1e2015-10-09 22:50:36 +0200303 testcommon(b"%5c", 65, b" A")
304 testcommon(b"%-5c", 65, b"A ")
Ethan Furmanb95b5612015-01-23 20:05:18 -0800305 # %b will insert a series of bytes, either from a type that supports
306 # the Py_buffer protocol, or something that has a __bytes__ method
307 class FakeBytes(object):
308 def __bytes__(self):
309 return b'123'
310 fb = FakeBytes()
311 testcommon(b"%b", b"abc", b"abc")
312 testcommon(b"%b", bytearray(b"def"), b"def")
313 testcommon(b"%b", fb, b"123")
314 # # %s is an alias for %b -- should only be used for Py2/3 code
315 testcommon(b"%s", b"abc", b"abc")
316 testcommon(b"%s", bytearray(b"def"), b"def")
317 testcommon(b"%s", fb, b"123")
318 # %a will give the equivalent of
319 # repr(some_obj).encode('ascii', 'backslashreplace')
320 testcommon(b"%a", 3.14, b"3.14")
321 testcommon(b"%a", b"ghi", b"b'ghi'")
322 testcommon(b"%a", "jkl", b"'jkl'")
323 testcommon(b"%a", "\u0544", b"'\\u0544'")
Ethan Furman62e977f2015-03-11 08:17:00 -0700324 # %r is an alias for %a
325 testcommon(b"%r", 3.14, b"3.14")
326 testcommon(b"%r", b"ghi", b"b'ghi'")
327 testcommon(b"%r", "jkl", b"'jkl'")
328 testcommon(b"%r", "\u0544", b"'\\u0544'")
Ethan Furmanb95b5612015-01-23 20:05:18 -0800329
330 # Test exception for unknown format characters, etc.
331 if verbose:
332 print('Testing exceptions')
333 def test_exc(formatstr, args, exception, excmsg):
334 try:
335 testformat(formatstr, args)
336 except exception as exc:
337 if str(exc) == excmsg:
338 if verbose:
339 print("yes")
340 else:
341 if verbose: print('no')
342 print('Unexpected ', exception, ':', repr(str(exc)))
343 except:
344 if verbose: print('no')
345 print('Unexpected exception')
346 raise
347 else:
348 raise TestFailed('did not get expected exception: %s' % excmsg)
349 test_exc(b'%d', '1', TypeError,
350 "%d format: a number is required, not str")
351 test_exc(b'%d', b'1', TypeError,
352 "%d format: a number is required, not bytes")
Serhiy Storchaka2c7b5a92015-03-30 09:19:08 +0300353 test_exc(b'%x', 3.14, TypeError,
354 "%x format: an integer is required, not float")
Ethan Furmanb95b5612015-01-23 20:05:18 -0800355 test_exc(b'%g', '1', TypeError, "float argument required, not str")
356 test_exc(b'%g', b'1', TypeError, "float argument required, not bytes")
357 test_exc(b'no format', 7, TypeError,
358 "not all arguments converted during bytes formatting")
359 test_exc(b'no format', b'1', TypeError,
360 "not all arguments converted during bytes formatting")
361 test_exc(b'no format', bytearray(b'1'), TypeError,
362 "not all arguments converted during bytes formatting")
Serhiy Storchaka41525e32015-04-03 20:53:46 +0300363 test_exc(b"%c", -1, OverflowError,
364 "%c arg not in range(256)")
365 test_exc(b"%c", 256, OverflowError,
366 "%c arg not in range(256)")
367 test_exc(b"%c", 2**128, OverflowError,
368 "%c arg not in range(256)")
Ethan Furmanb95b5612015-01-23 20:05:18 -0800369 test_exc(b"%c", b"Za", TypeError,
370 "%c requires an integer in range(256) or a single byte")
Serhiy Storchaka2c7b5a92015-03-30 09:19:08 +0300371 test_exc(b"%c", "Y", TypeError,
372 "%c requires an integer in range(256) or a single byte")
373 test_exc(b"%c", 3.14, TypeError,
Ethan Furmanb95b5612015-01-23 20:05:18 -0800374 "%c requires an integer in range(256) or a single byte")
375 test_exc(b"%b", "Xc", TypeError,
376 "%b requires bytes, or an object that implements __bytes__, not 'str'")
377 test_exc(b"%s", "Wd", TypeError,
378 "%b requires bytes, or an object that implements __bytes__, not 'str'")
Marc-André Lemburgd70141a2000-06-30 10:26:29 +0000379
Christian Heimesf6cd9672008-03-26 13:45:42 +0000380 if maxsize == 2**31-1:
381 # crashes 2.2.1 and earlier:
382 try:
383 "%*d"%(maxsize, -127)
384 except MemoryError:
385 pass
386 else:
387 raise TestFailed('"%*d"%(maxsize, -127) should fail')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000388
Victor Stinnera4ac6002012-01-21 15:50:49 +0100389 def test_non_ascii(self):
Victor Stinner184252a2012-06-16 02:57:41 +0200390 testformat("\u20ac=%f", (1.0,), "\u20ac=1.000000")
391
Victor Stinnera4ac6002012-01-21 15:50:49 +0100392 self.assertEqual(format("abc", "\u2007<5"), "abc\u2007\u2007")
393 self.assertEqual(format(123, "\u2007<5"), "123\u2007\u2007")
394 self.assertEqual(format(12.3, "\u2007<6"), "12.3\u2007\u2007")
395 self.assertEqual(format(0j, "\u2007<4"), "0j\u2007\u2007")
396 self.assertEqual(format(1+2j, "\u2007<8"), "(1+2j)\u2007\u2007")
397
398 self.assertEqual(format("abc", "\u2007>5"), "\u2007\u2007abc")
399 self.assertEqual(format(123, "\u2007>5"), "\u2007\u2007123")
400 self.assertEqual(format(12.3, "\u2007>6"), "\u2007\u200712.3")
401 self.assertEqual(format(1+2j, "\u2007>8"), "\u2007\u2007(1+2j)")
402 self.assertEqual(format(0j, "\u2007>4"), "\u2007\u20070j")
403
404 self.assertEqual(format("abc", "\u2007^5"), "\u2007abc\u2007")
405 self.assertEqual(format(123, "\u2007^5"), "\u2007123\u2007")
406 self.assertEqual(format(12.3, "\u2007^6"), "\u200712.3\u2007")
407 self.assertEqual(format(1+2j, "\u2007^8"), "\u2007(1+2j)\u2007")
408 self.assertEqual(format(0j, "\u2007^4"), "\u20070j\u2007")
409
Victor Stinner41a863c2012-02-24 00:37:51 +0100410 def test_locale(self):
411 try:
Stefan Krah0509d942012-02-27 10:18:51 +0100412 oldloc = locale.setlocale(locale.LC_ALL)
413 locale.setlocale(locale.LC_ALL, '')
Victor Stinner41a863c2012-02-24 00:37:51 +0100414 except locale.Error as err:
415 self.skipTest("Cannot set locale: {}".format(err))
416 try:
Victor Stinner90f50d42012-02-24 01:44:47 +0100417 localeconv = locale.localeconv()
418 sep = localeconv['thousands_sep']
419 point = localeconv['decimal_point']
420
Victor Stinner41a863c2012-02-24 00:37:51 +0100421 text = format(123456789, "n")
422 self.assertIn(sep, text)
423 self.assertEqual(text.replace(sep, ''), '123456789')
Victor Stinner90f50d42012-02-24 01:44:47 +0100424
425 text = format(1234.5, "n")
426 self.assertIn(sep, text)
427 self.assertIn(point, text)
428 self.assertEqual(text.replace(sep, ''), '1234' + point + '5')
Victor Stinner41a863c2012-02-24 00:37:51 +0100429 finally:
430 locale.setlocale(locale.LC_ALL, oldloc)
431
Victor Stinner621ef3d2012-10-02 00:33:47 +0200432 @support.cpython_only
433 def test_optimisations(self):
434 text = "abcde" # 5 characters
435
436 self.assertIs("%s" % text, text)
437 self.assertIs("%.5s" % text, text)
438 self.assertIs("%.10s" % text, text)
439 self.assertIs("%1s" % text, text)
440 self.assertIs("%5s" % text, text)
441
442 self.assertIs("{0}".format(text), text)
443 self.assertIs("{0:s}".format(text), text)
444 self.assertIs("{0:.5s}".format(text), text)
445 self.assertIs("{0:.10s}".format(text), text)
446 self.assertIs("{0:1s}".format(text), text)
447 self.assertIs("{0:5s}".format(text), text)
Victor Stinner41a863c2012-02-24 00:37:51 +0100448
Victor Stinnercfc4c132013-04-03 01:48:39 +0200449 self.assertIs(text % (), text)
450 self.assertIs(text.format(), text)
451
Victor Stinner2f084ec2013-06-23 14:54:30 +0200452 def test_precision(self):
Victor Stinner2f084ec2013-06-23 14:54:30 +0200453 f = 1.2
454 self.assertEqual(format(f, ".0f"), "1")
455 self.assertEqual(format(f, ".3f"), "1.200")
456 with self.assertRaises(ValueError) as cm:
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200457 format(f, ".%sf" % (sys.maxsize + 1))
Victor Stinner2f084ec2013-06-23 14:54:30 +0200458
459 c = complex(f)
Mark Dickinsonef8627b2013-10-13 11:04:36 +0100460 self.assertEqual(format(c, ".0f"), "1+0j")
461 self.assertEqual(format(c, ".3f"), "1.200+0.000j")
Victor Stinner2f084ec2013-06-23 14:54:30 +0200462 with self.assertRaises(ValueError) as cm:
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200463 format(c, ".%sf" % (sys.maxsize + 1))
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200464
465 @support.cpython_only
466 def test_precision_c_limits(self):
467 from _testcapi import INT_MAX
468
469 f = 1.2
Victor Stinner2f084ec2013-06-23 14:54:30 +0200470 with self.assertRaises(ValueError) as cm:
471 format(f, ".%sf" % (INT_MAX + 1))
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200472
473 c = complex(f)
474 with self.assertRaises(ValueError) as cm:
Mark Dickinsonef8627b2013-10-13 11:04:36 +0100475 format(c, ".%sf" % (INT_MAX + 1))
Victor Stinner2f084ec2013-06-23 14:54:30 +0200476
Tim Peters38fd5b62000-09-21 05:43:11 +0000477
Christian Heimesf6cd9672008-03-26 13:45:42 +0000478if __name__ == "__main__":
479 unittest.main()