Debian Codegraph @

Lib/test/test_format.py

raw
1 from test.support import verbose, TestFailed
2 import locale
3 import sys
4 import re
5 import test.support as support
6 import unittest
7 from test.support.import_helper import import_module
8
9 maxsize = support.MAX_Py_ssize_t
10
11 # test string formatting operator (I am not sure if this is being tested
12 # elsewhere but, surely, some of the given cases are *not* tested because
13 # they crash python)
14 # test on bytes object as well
15
16 def testformat(formatstr, args, output=None, limit=None, overflowok=False):
17 if verbose:
18 if output:
19 print("{!a} % {!a} =? {!a} ...".format(formatstr, args, output),
20 end=' ')
21 else:
22 print("{!a} % {!a} works? ...".format(formatstr, args), end=' ')
23 try:
24 result = formatstr % args
25 except OverflowError:
26 if not overflowok:
27 raise
28 if verbose:
29 print('overflow (this is fine)')
30 else:
31 if output and limit is None and result != output:
32 if verbose:
33 print('no')
34 raise AssertionError("%r %% %r == %r != %r" %
35 (formatstr, args, result, output))
36 # when 'limit' is specified, it determines how many characters
37 # must match exactly; lengths must always match.
38 # ex: limit=5, '12345678' matches '12345___'
39 # (mainly for floating-point format tests for which an exact match
40 # can't be guaranteed due to rounding and representation errors)
41 elif output and limit is not None and (
42 len(result)!=len(output) or result[:limit]!=output[:limit]):
43 if verbose:
44 print('no')
45 print("%s %% %s == %s != %s" % \
46 (repr(formatstr), repr(args), repr(result), repr(output)))
47 else:
48 if verbose:
49 print('yes')
50
51 def testcommon(formatstr, args, output=None, limit=None, overflowok=False):
52 # if formatstr is a str, test str, bytes, and bytearray;
53 # otherwise, test bytes and bytearray
54 if isinstance(formatstr, str):
55 testformat(formatstr, args, output, limit, overflowok)
56 b_format = formatstr.encode('ascii')
57 else:
58 b_format = formatstr
59 ba_format = bytearray(b_format)
60 b_args = []
61 if not isinstance(args, tuple):
62 args = (args, )
63 b_args = tuple(args)
64 if output is None:
65 b_output = ba_output = None
66 else:
67 if isinstance(output, str):
68 b_output = output.encode('ascii')
69 else:
70 b_output = output
71 ba_output = bytearray(b_output)
72 testformat(b_format, b_args, b_output, limit, overflowok)
73 testformat(ba_format, b_args, ba_output, limit, overflowok)
74
75 def test_exc(formatstr, args, exception, excmsg):
76 try:
77 testformat(formatstr, args)
78 except exception as exc:
79 if str(exc) == excmsg:
80 if verbose:
81 print("yes")
82 else:
83 if verbose: print('no')
84 print('Unexpected ', exception, ':', repr(str(exc)))
85 except:
86 if verbose: print('no')
87 print('Unexpected exception')
88 raise
89 else:
90 raise TestFailed('did not get expected exception: %s' % excmsg)
91
92 def test_exc_common(formatstr, args, exception, excmsg):
93 # test str and bytes
94 test_exc(formatstr, args, exception, excmsg)
95 test_exc(formatstr.encode('ascii'), args, exception, excmsg)
96
97 class FormatTest(unittest.TestCase):
98
99 def test_common_format(self):
100 # test the format identifiers that work the same across
101 # str, bytes, and bytearrays (integer, float, oct, hex)
102 testcommon("%%", (), "%")
103 testcommon("%.1d", (1,), "1")
104 testcommon("%.*d", (sys.maxsize,1), overflowok=True) # expect overflow
105 testcommon("%.100d", (1,), '00000000000000000000000000000000000000'
106 '000000000000000000000000000000000000000000000000000000'
107 '00000001', overflowok=True)
108 testcommon("%#.117x", (1,), '0x00000000000000000000000000000000000'
109 '000000000000000000000000000000000000000000000000000000'
110 '0000000000000000000000000001',
111 overflowok=True)
112 testcommon("%#.118x", (1,), '0x00000000000000000000000000000000000'
113 '000000000000000000000000000000000000000000000000000000'
114 '00000000000000000000000000001',
115 overflowok=True)
116
117 testcommon("%f", (1.0,), "1.000000")
118 # these are trying to test the limits of the internal magic-number-length
119 # formatting buffer, if that number changes then these tests are less
120 # effective
121 testcommon("%#.*g", (109, -1.e+49/3.))
122 testcommon("%#.*g", (110, -1.e+49/3.))
123 testcommon("%#.*g", (110, -1.e+100/3.))
124 # test some ridiculously large precision, expect overflow
125 testcommon('%12.*f', (123456, 1.0))
126
127 # check for internal overflow validation on length of precision
128 # these tests should no longer cause overflow in Python
129 # 2.7/3.1 and later.
130 testcommon("%#.*g", (110, -1.e+100/3.))
131 testcommon("%#.*G", (110, -1.e+100/3.))
132 testcommon("%#.*f", (110, -1.e+100/3.))
133 testcommon("%#.*F", (110, -1.e+100/3.))
134 # Formatting of integers. Overflow is not ok
135 testcommon("%x", 10, "a")
136 testcommon("%x", 100000000000, "174876e800")
137 testcommon("%o", 10, "12")
138 testcommon("%o", 100000000000, "1351035564000")
139 testcommon("%d", 10, "10")
140 testcommon("%d", 100000000000, "100000000000")
141
142 big = 123456789012345678901234567890
143 testcommon("%d", big, "123456789012345678901234567890")
144 testcommon("%d", -big, "-123456789012345678901234567890")
145 testcommon("%5d", -big, "-123456789012345678901234567890")
146 testcommon("%31d", -big, "-123456789012345678901234567890")
147 testcommon("%32d", -big, " -123456789012345678901234567890")
148 testcommon("%-32d", -big, "-123456789012345678901234567890 ")
149 testcommon("%032d", -big, "-0123456789012345678901234567890")
150 testcommon("%-032d", -big, "-123456789012345678901234567890 ")
151 testcommon("%034d", -big, "-000123456789012345678901234567890")
152 testcommon("%034d", big, "0000123456789012345678901234567890")
153 testcommon("%0+34d", big, "+000123456789012345678901234567890")
154 testcommon("%+34d", big, " +123456789012345678901234567890")
155 testcommon("%34d", big, " 123456789012345678901234567890")
156 testcommon("%.2d", big, "123456789012345678901234567890")
157 testcommon("%.30d", big, "123456789012345678901234567890")
158 testcommon("%.31d", big, "0123456789012345678901234567890")
159 testcommon("%32.31d", big, " 0123456789012345678901234567890")
160 testcommon("%d", float(big), "123456________________________", 6)
161
162 big = 0x1234567890abcdef12345 # 21 hex digits
163 testcommon("%x", big, "1234567890abcdef12345")
164 testcommon("%x", -big, "-1234567890abcdef12345")
165 testcommon("%5x", -big, "-1234567890abcdef12345")
166 testcommon("%22x", -big, "-1234567890abcdef12345")
167 testcommon("%23x", -big, " -1234567890abcdef12345")
168 testcommon("%-23x", -big, "-1234567890abcdef12345 ")
169 testcommon("%023x", -big, "-01234567890abcdef12345")
170 testcommon("%-023x", -big, "-1234567890abcdef12345 ")
171 testcommon("%025x", -big, "-0001234567890abcdef12345")
172 testcommon("%025x", big, "00001234567890abcdef12345")
173 testcommon("%0+25x", big, "+0001234567890abcdef12345")
174 testcommon("%+25x", big, " +1234567890abcdef12345")
175 testcommon("%25x", big, " 1234567890abcdef12345")
176 testcommon("%.2x", big, "1234567890abcdef12345")
177 testcommon("%.21x", big, "1234567890abcdef12345")
178 testcommon("%.22x", big, "01234567890abcdef12345")
179 testcommon("%23.22x", big, " 01234567890abcdef12345")
180 testcommon("%-23.22x", big, "01234567890abcdef12345 ")
181 testcommon("%X", big, "1234567890ABCDEF12345")
182 testcommon("%#X", big, "0X1234567890ABCDEF12345")
183 testcommon("%#x", big, "0x1234567890abcdef12345")
184 testcommon("%#x", -big, "-0x1234567890abcdef12345")
185 testcommon("%#27x", big, " 0x1234567890abcdef12345")
186 testcommon("%#-27x", big, "0x1234567890abcdef12345 ")
187 testcommon("%#027x", big, "0x00001234567890abcdef12345")
188 testcommon("%#.23x", big, "0x001234567890abcdef12345")
189 testcommon("%#.23x", -big, "-0x001234567890abcdef12345")
190 testcommon("%#27.23x", big, " 0x001234567890abcdef12345")
191 testcommon("%#-27.23x", big, "0x001234567890abcdef12345 ")
192 testcommon("%#027.23x", big, "0x00001234567890abcdef12345")
193 testcommon("%#+.23x", big, "+0x001234567890abcdef12345")
194 testcommon("%# .23x", big, " 0x001234567890abcdef12345")
195 testcommon("%#+.23X", big, "+0X001234567890ABCDEF12345")
196 # next one gets two leading zeroes from precision, and another from the
197 # 0 flag and the width
198 testcommon("%#+027.23X", big, "+0X0001234567890ABCDEF12345")
199 testcommon("%# 027.23X", big, " 0X0001234567890ABCDEF12345")
200 # same, except no 0 flag
201 testcommon("%#+27.23X", big, " +0X001234567890ABCDEF12345")
202 testcommon("%#-+27.23x", big, "+0x001234567890abcdef12345 ")
203 testcommon("%#- 27.23x", big, " 0x001234567890abcdef12345 ")
204
205 big = 0o12345670123456701234567012345670 # 32 octal digits
206 testcommon("%o", big, "12345670123456701234567012345670")
207 testcommon("%o", -big, "-12345670123456701234567012345670")
208 testcommon("%5o", -big, "-12345670123456701234567012345670")
209 testcommon("%33o", -big, "-12345670123456701234567012345670")
210 testcommon("%34o", -big, " -12345670123456701234567012345670")
211 testcommon("%-34o", -big, "-12345670123456701234567012345670 ")
212 testcommon("%034o", -big, "-012345670123456701234567012345670")
213 testcommon("%-034o", -big, "-12345670123456701234567012345670 ")
214 testcommon("%036o", -big, "-00012345670123456701234567012345670")
215 testcommon("%036o", big, "000012345670123456701234567012345670")
216 testcommon("%0+36o", big, "+00012345670123456701234567012345670")
217 testcommon("%+36o", big, " +12345670123456701234567012345670")
218 testcommon("%36o", big, " 12345670123456701234567012345670")
219 testcommon("%.2o", big, "12345670123456701234567012345670")
220 testcommon("%.32o", big, "12345670123456701234567012345670")
221 testcommon("%.33o", big, "012345670123456701234567012345670")
222 testcommon("%34.33o", big, " 012345670123456701234567012345670")
223 testcommon("%-34.33o", big, "012345670123456701234567012345670 ")
224 testcommon("%o", big, "12345670123456701234567012345670")
225 testcommon("%#o", big, "0o12345670123456701234567012345670")
226 testcommon("%#o", -big, "-0o12345670123456701234567012345670")
227 testcommon("%#38o", big, " 0o12345670123456701234567012345670")
228 testcommon("%#-38o", big, "0o12345670123456701234567012345670 ")
229 testcommon("%#038o", big, "0o000012345670123456701234567012345670")
230 testcommon("%#.34o", big, "0o0012345670123456701234567012345670")
231 testcommon("%#.34o", -big, "-0o0012345670123456701234567012345670")
232 testcommon("%#38.34o", big, " 0o0012345670123456701234567012345670")
233 testcommon("%#-38.34o", big, "0o0012345670123456701234567012345670 ")
234 testcommon("%#038.34o", big, "0o000012345670123456701234567012345670")
235 testcommon("%#+.34o", big, "+0o0012345670123456701234567012345670")
236 testcommon("%# .34o", big, " 0o0012345670123456701234567012345670")
237 testcommon("%#+38.34o", big, " +0o0012345670123456701234567012345670")
238 testcommon("%#-+38.34o", big, "+0o0012345670123456701234567012345670 ")
239 testcommon("%#- 38.34o", big, " 0o0012345670123456701234567012345670 ")
240 testcommon("%#+038.34o", big, "+0o00012345670123456701234567012345670")
241 testcommon("%# 038.34o", big, " 0o00012345670123456701234567012345670")
242 # next one gets one leading zero from precision
243 testcommon("%.33o", big, "012345670123456701234567012345670")
244 # base marker added in spite of leading zero (different to Python 2)
245 testcommon("%#.33o", big, "0o012345670123456701234567012345670")
246 # reduce precision, and base marker is always added
247 testcommon("%#.32o", big, "0o12345670123456701234567012345670")
248 # one leading zero from precision, plus two from "0" flag & width
249 testcommon("%035.33o", big, "00012345670123456701234567012345670")
250 # base marker shouldn't change the size
251 testcommon("%0#35.33o", big, "0o012345670123456701234567012345670")
252
253 # Some small ints, in both Python int and flavors.
254 testcommon("%d", 42, "42")
255 testcommon("%d", -42, "-42")
256 testcommon("%d", 42.0, "42")
257 testcommon("%#x", 1, "0x1")
258 testcommon("%#X", 1, "0X1")
259 testcommon("%#o", 1, "0o1")
260 testcommon("%#o", 0, "0o0")
261 testcommon("%o", 0, "0")
262 testcommon("%d", 0, "0")
263 testcommon("%#x", 0, "0x0")
264 testcommon("%#X", 0, "0X0")
265 testcommon("%x", 0x42, "42")
266 testcommon("%x", -0x42, "-42")
267 testcommon("%o", 0o42, "42")
268 testcommon("%o", -0o42, "-42")
269 # alternate float formatting
270 testcommon('%g', 1.1, '1.1')
271 testcommon('%#g', 1.1, '1.10000')
272
273 if verbose:
274 print('Testing exceptions')
275 test_exc_common('%', (), ValueError, "incomplete format")
276 test_exc_common('% %s', 1, ValueError,
277 "unsupported format character '%' (0x25) at index 2")
278 test_exc_common('%d', '1', TypeError,
279 "%d format: a real number is required, not str")
280 test_exc_common('%d', b'1', TypeError,
281 "%d format: a real number is required, not bytes")
282 test_exc_common('%x', '1', TypeError,
283 "%x format: an integer is required, not str")
284 test_exc_common('%x', 3.14, TypeError,
285 "%x format: an integer is required, not float")
286 test_exc_common('%i', '1', TypeError,
287 "%i format: a real number is required, not str")
288 test_exc_common('%i', b'1', TypeError,
289 "%i format: a real number is required, not bytes")
290
291 def test_str_format(self):
292 testformat("%r", "\u0378", "'\\u0378'") # non printable
293 testformat("%a", "\u0378", "'\\u0378'") # non printable
294 testformat("%r", "\u0374", "'\u0374'") # printable
295 testformat("%a", "\u0374", "'\\u0374'") # printable
296
297 # Test exception for unknown format characters, etc.
298 if verbose:
299 print('Testing exceptions')
300 test_exc('abc %b', 1, ValueError,
301 "unsupported format character 'b' (0x62) at index 5")
302 #test_exc(unicode('abc %\u3000','raw-unicode-escape'), 1, ValueError,
303 # "unsupported format character '?' (0x3000) at index 5")
304 test_exc('%g', '1', TypeError, "must be real number, not str")
305 test_exc('no format', '1', TypeError,
306 "not all arguments converted during string formatting")
307 test_exc('%c', -1, OverflowError, "%c arg not in range(0x110000)")
308 test_exc('%c', sys.maxunicode+1, OverflowError,
309 "%c arg not in range(0x110000)")
310 #test_exc('%c', 2**128, OverflowError, "%c arg not in range(0x110000)")
311 test_exc('%c', 3.14, TypeError, "%c requires an int or a unicode character, not float")
312 test_exc('%c', 'ab', TypeError, "%c requires an int or a unicode character, not a string of length 2")
313 test_exc('%c', b'x', TypeError, "%c requires an int or a unicode character, not bytes")
314
315 if maxsize == 2**31-1:
316 # crashes 2.2.1 and earlier:
317 try:
318 "%*d"%(maxsize, -127)
319 except MemoryError:
320 pass
321 else:
322 raise TestFailed('"%*d"%(maxsize, -127) should fail')
323
324 def test_bytes_and_bytearray_format(self):
325 # %c will insert a single byte, either from an int in range(256), or
326 # from a bytes argument of length 1, not from a str.
327 testcommon(b"%c", 7, b"\x07")
328 testcommon(b"%c", b"Z", b"Z")
329 testcommon(b"%c", bytearray(b"Z"), b"Z")
330 testcommon(b"%5c", 65, b" A")
331 testcommon(b"%-5c", 65, b"A ")
332 # %b will insert a series of bytes, either from a type that supports
333 # the Py_buffer protocol, or something that has a __bytes__ method
334 class FakeBytes(object):
335 def __bytes__(self):
336 return b'123'
337 fb = FakeBytes()
338 testcommon(b"%b", b"abc", b"abc")
339 testcommon(b"%b", bytearray(b"def"), b"def")
340 testcommon(b"%b", fb, b"123")
341 testcommon(b"%b", memoryview(b"abc"), b"abc")
342 # # %s is an alias for %b -- should only be used for Py2/3 code
343 testcommon(b"%s", b"abc", b"abc")
344 testcommon(b"%s", bytearray(b"def"), b"def")
345 testcommon(b"%s", fb, b"123")
346 testcommon(b"%s", memoryview(b"abc"), b"abc")
347 # %a will give the equivalent of
348 # repr(some_obj).encode('ascii', 'backslashreplace')
349 testcommon(b"%a", 3.25, b"3.25")
350 testcommon(b"%a", b"ghi", b"b'ghi'")
351 testcommon(b"%a", "jkl", b"'jkl'")
352 testcommon(b"%a", "\u0544", b"'\\u0544'")
353 # %r is an alias for %a
354 testcommon(b"%r", 3.25, b"3.25")
355 testcommon(b"%r", b"ghi", b"b'ghi'")
356 testcommon(b"%r", "jkl", b"'jkl'")
357 testcommon(b"%r", "\u0544", b"'\\u0544'")
358
359 # Test exception for unknown format characters, etc.
360 if verbose:
361 print('Testing exceptions')
362 test_exc(b'%g', '1', TypeError, "float argument required, not str")
363 test_exc(b'%g', b'1', TypeError, "float argument required, not bytes")
364 test_exc(b'no format', 7, TypeError,
365 "not all arguments converted during bytes formatting")
366 test_exc(b'no format', b'1', TypeError,
367 "not all arguments converted during bytes formatting")
368 test_exc(b'no format', bytearray(b'1'), TypeError,
369 "not all arguments converted during bytes formatting")
370 test_exc(b"%c", -1, OverflowError,
371 "%c arg not in range(256)")
372 test_exc(b"%c", 256, OverflowError,
373 "%c arg not in range(256)")
374 test_exc(b"%c", 2**128, OverflowError,
375 "%c arg not in range(256)")
376 test_exc(b"%c", b"Za", TypeError,
377 "%c requires an integer in range(256) or a single byte, not a bytes object of length 2")
378 test_exc(b"%c", "Y", TypeError,
379 "%c requires an integer in range(256) or a single byte, not str")
380 test_exc(b"%c", 3.14, TypeError,
381 "%c requires an integer in range(256) or a single byte, not float")
382 test_exc(b"%b", "Xc", TypeError,
383 "%b requires a bytes-like object, "
384 "or an object that implements __bytes__, not 'str'")
385 test_exc(b"%s", "Wd", TypeError,
386 "%b requires a bytes-like object, "
387 "or an object that implements __bytes__, not 'str'")
388
389 if maxsize == 2**31-1:
390 # crashes 2.2.1 and earlier:
391 try:
392 "%*d"%(maxsize, -127)
393 except MemoryError:
394 pass
395 else:
396 raise TestFailed('"%*d"%(maxsize, -127) should fail')
397
398 def test_nul(self):
399 # test the null character
400 testcommon("a\0b", (), 'a\0b')
401 testcommon("a%cb", (0,), 'a\0b')
402 testformat("a%sb", ('c\0d',), 'ac\0db')
403 testcommon(b"a%sb", (b'c\0d',), b'ac\0db')
404
405 def test_non_ascii(self):
406 testformat("\u20ac=%f", (1.0,), "\u20ac=1.000000")
407
408 self.assertEqual(format("abc", "\u2007<5"), "abc\u2007\u2007")
409 self.assertEqual(format(123, "\u2007<5"), "123\u2007\u2007")
410 self.assertEqual(format(12.5, "\u2007<6"), "12.5\u2007\u2007")
411 self.assertEqual(format(0j, "\u2007<4"), "0j\u2007\u2007")
412 self.assertEqual(format(1+2j, "\u2007<8"), "(1+2j)\u2007\u2007")
413
414 self.assertEqual(format("abc", "\u2007>5"), "\u2007\u2007abc")
415 self.assertEqual(format(123, "\u2007>5"), "\u2007\u2007123")
416 self.assertEqual(format(12.5, "\u2007>6"), "\u2007\u200712.5")
417 self.assertEqual(format(1+2j, "\u2007>8"), "\u2007\u2007(1+2j)")
418 self.assertEqual(format(0j, "\u2007>4"), "\u2007\u20070j")
419
420 self.assertEqual(format("abc", "\u2007^5"), "\u2007abc\u2007")
421 self.assertEqual(format(123, "\u2007^5"), "\u2007123\u2007")
422 self.assertEqual(format(12.5, "\u2007^6"), "\u200712.5\u2007")
423 self.assertEqual(format(1+2j, "\u2007^8"), "\u2007(1+2j)\u2007")
424 self.assertEqual(format(0j, "\u2007^4"), "\u20070j\u2007")
425
426 def test_locale(self):
427 try:
428 oldloc = locale.setlocale(locale.LC_ALL)
429 locale.setlocale(locale.LC_ALL, '')
430 except locale.Error as err:
431 self.skipTest("Cannot set locale: {}".format(err))
432 try:
433 localeconv = locale.localeconv()
434 sep = localeconv['thousands_sep']
435 point = localeconv['decimal_point']
436 grouping = localeconv['grouping']
437
438 text = format(123456789, "n")
439 if grouping:
440 self.assertIn(sep, text)
441 self.assertEqual(text.replace(sep, ''), '123456789')
442
443 text = format(1234.5, "n")
444 if grouping:
445 self.assertIn(sep, text)
446 self.assertIn(point, text)
447 self.assertEqual(text.replace(sep, ''), '1234' + point + '5')
448 finally:
449 locale.setlocale(locale.LC_ALL, oldloc)
450
451 @support.cpython_only
452 def test_optimisations(self):
453 text = "abcde" # 5 characters
454
455 self.assertIs("%s" % text, text)
456 self.assertIs("%.5s" % text, text)
457 self.assertIs("%.10s" % text, text)
458 self.assertIs("%1s" % text, text)
459 self.assertIs("%5s" % text, text)
460
461 self.assertIs("{0}".format(text), text)
462 self.assertIs("{0:s}".format(text), text)
463 self.assertIs("{0:.5s}".format(text), text)
464 self.assertIs("{0:.10s}".format(text), text)
465 self.assertIs("{0:1s}".format(text), text)
466 self.assertIs("{0:5s}".format(text), text)
467
468 self.assertIs(text % (), text)
469 self.assertIs(text.format(), text)
470
471 def test_precision(self):
472 f = 1.2
473 self.assertEqual(format(f, ".0f"), "1")
474 self.assertEqual(format(f, ".3f"), "1.200")
475 with self.assertRaises(ValueError) as cm:
476 format(f, ".%sf" % (sys.maxsize + 1))
477
478 c = complex(f)
479 self.assertEqual(format(c, ".0f"), "1+0j")
480 self.assertEqual(format(c, ".3f"), "1.200+0.000j")
481 with self.assertRaises(ValueError) as cm:
482 format(c, ".%sf" % (sys.maxsize + 1))
483
484 @support.cpython_only
485 def test_precision_c_limits(self):
486 _testcapi = import_module("_testcapi")
487 INT_MAX = _testcapi.INT_MAX
488
489 f = 1.2
490 with self.assertRaises(ValueError) as cm:
491 format(f, ".%sf" % (INT_MAX + 1))
492
493 c = complex(f)
494 with self.assertRaises(ValueError) as cm:
495 format(c, ".%sf" % (INT_MAX + 1))
496
497 def test_g_format_has_no_trailing_zeros(self):
498 # regression test for bugs.python.org/issue40780
499 self.assertEqual("%.3g" % 1505.0, "1.5e+03")
500 self.assertEqual("%#.3g" % 1505.0, "1.50e+03")
501
502 self.assertEqual(format(1505.0, ".3g"), "1.5e+03")
503 self.assertEqual(format(1505.0, "#.3g"), "1.50e+03")
504
505 self.assertEqual(format(12300050.0, ".6g"), "1.23e+07")
506 self.assertEqual(format(12300050.0, "#.6g"), "1.23000e+07")
507
508 def test_with_two_commas_in_format_specifier(self):
509 error_msg = re.escape("Cannot specify ',' with ','.")
510 with self.assertRaisesRegex(ValueError, error_msg):
511 '{:,,}'.format(1)
512
513 def test_with_two_underscore_in_format_specifier(self):
514 error_msg = re.escape("Cannot specify '_' with '_'.")
515 with self.assertRaisesRegex(ValueError, error_msg):
516 '{:__}'.format(1)
517
518 def test_with_a_commas_and_an_underscore_in_format_specifier(self):
519 error_msg = re.escape("Cannot specify both ',' and '_'.")
520 with self.assertRaisesRegex(ValueError, error_msg):
521 '{:,_}'.format(1)
522 with self.assertRaisesRegex(ValueError, error_msg):
523 '{:.,_f}'.format(1.1)
524
525 def test_with_an_underscore_and_a_comma_in_format_specifier(self):
526 error_msg = re.escape("Cannot specify both ',' and '_'.")
527 with self.assertRaisesRegex(ValueError, error_msg):
528 '{:_,}'.format(1)
529 with self.assertRaisesRegex(ValueError, error_msg):
530 '{:._,f}'.format(1.1)
531
532 def test_better_error_message_format(self):
533 # https://bugs.python.org/issue20524
534 for value in [12j, 12, 12.0, "12"]:
535 with self.subTest(value=value):
536 # The format spec must be invalid for all types we're testing.
537 # '%M' will suffice.
538 bad_format_spec = '%M'
539 err = re.escape("Invalid format specifier "
540 f"'{bad_format_spec}' for object of type "
541 f"'{type(value).__name__}'")
542 with self.assertRaisesRegex(ValueError, err):
543 f"xx{{value:{bad_format_spec}}}yy".format(value=value)
544
545 # Also test the builtin format() function.
546 with self.assertRaisesRegex(ValueError, err):
547 format(value, bad_format_spec)
548
549 # Also test f-strings.
550 with self.assertRaisesRegex(ValueError, err):
551 eval("f'xx{value:{bad_format_spec}}yy'")
552
553 def test_unicode_in_error_message(self):
554 str_err = re.escape(
555 "Invalid format specifier '%ЫйЯЧ' for object of type 'str'")
556 with self.assertRaisesRegex(ValueError, str_err):
557 "{a:%ЫйЯЧ}".format(a='a')
558
559 def test_negative_zero(self):
560 ## default behavior
561 self.assertEqual(f"{-0.:.1f}", "-0.0")
562 self.assertEqual(f"{-.01:.1f}", "-0.0")
563 self.assertEqual(f"{-0:.1f}", "0.0") # integers do not distinguish -0
564
565 ## z sign option
566 self.assertEqual(f"{0.:z.1f}", "0.0")
567 self.assertEqual(f"{0.:z6.1f}", " 0.0")
568 self.assertEqual(f"{-1.:z6.1f}", " -1.0")
569 self.assertEqual(f"{-0.:z.1f}", "0.0")
570 self.assertEqual(f"{.01:z.1f}", "0.0")
571 self.assertEqual(f"{-0:z.1f}", "0.0") # z is allowed for integer input
572 self.assertEqual(f"{-.01:z.1f}", "0.0")
573 self.assertEqual(f"{0.:z.2f}", "0.00")
574 self.assertEqual(f"{-0.:z.2f}", "0.00")
575 self.assertEqual(f"{.001:z.2f}", "0.00")
576 self.assertEqual(f"{-.001:z.2f}", "0.00")
577
578 self.assertEqual(f"{0.:z.1e}", "0.0e+00")
579 self.assertEqual(f"{-0.:z.1e}", "0.0e+00")
580 self.assertEqual(f"{0.:z.1E}", "0.0E+00")
581 self.assertEqual(f"{-0.:z.1E}", "0.0E+00")
582
583 self.assertEqual(f"{-0.001:z.2e}", "-1.00e-03") # tests for mishandled
584 # rounding
585 self.assertEqual(f"{-0.001:z.2g}", "-0.001")
586 self.assertEqual(f"{-0.001:z.2%}", "-0.10%")
587
588 self.assertEqual(f"{-00000.000001:z.1f}", "0.0")
589 self.assertEqual(f"{-00000.:z.1f}", "0.0")
590 self.assertEqual(f"{-.0000000000:z.1f}", "0.0")
591
592 self.assertEqual(f"{-00000.000001:z.2f}", "0.00")
593 self.assertEqual(f"{-00000.:z.2f}", "0.00")
594 self.assertEqual(f"{-.0000000000:z.2f}", "0.00")
595
596 self.assertEqual(f"{.09:z.1f}", "0.1")
597 self.assertEqual(f"{-.09:z.1f}", "-0.1")
598
599 self.assertEqual(f"{-0.: z.0f}", " 0")
600 self.assertEqual(f"{-0.:+z.0f}", "+0")
601 self.assertEqual(f"{-0.:-z.0f}", "0")
602 self.assertEqual(f"{-1.: z.0f}", "-1")
603 self.assertEqual(f"{-1.:+z.0f}", "-1")
604 self.assertEqual(f"{-1.:-z.0f}", "-1")
605
606 self.assertEqual(f"{0.j:z.1f}", "0.0+0.0j")
607 self.assertEqual(f"{-0.j:z.1f}", "0.0+0.0j")
608 self.assertEqual(f"{.01j:z.1f}", "0.0+0.0j")
609 self.assertEqual(f"{-.01j:z.1f}", "0.0+0.0j")
610
611 self.assertEqual(f"{-0.:z>6.1f}", "zz-0.0") # test fill, esp. 'z' fill
612 self.assertEqual(f"{-0.:z>z6.1f}", "zzz0.0")
613 self.assertEqual(f"{-0.:x>z6.1f}", "xxx0.0")
614 self.assertEqual(f"{-0.:🖤>z6.1f}", "🖤🖤🖤0.0") # multi-byte fill char
615
616 def test_specifier_z_error(self):
617 error_msg = re.compile("Invalid format specifier '.*z.*'")
618 with self.assertRaisesRegex(ValueError, error_msg):
619 f"{0:z+f}" # wrong position
620 with self.assertRaisesRegex(ValueError, error_msg):
621 f"{0:fz}" # wrong position
622
623 error_msg = re.escape("Negative zero coercion (z) not allowed")
624 with self.assertRaisesRegex(ValueError, error_msg):
625 f"{0:zd}" # can't apply to int presentation type
626 with self.assertRaisesRegex(ValueError, error_msg):
627 f"{'x':zs}" # can't apply to string
628
629 error_msg = re.escape("unsupported format character 'z'")
630 with self.assertRaisesRegex(ValueError, error_msg):
631 "%z.1f" % 0 # not allowed in old style string interpolation
632 with self.assertRaisesRegex(ValueError, error_msg):
633 b"%z.1f" % 0
634
635
636 if __name__ == "__main__":
637 unittest.main()