1from test.support import verbose, TestFailed 2import locale 3import sys 4import re 5import test.support as support 6import unittest 7from test.support.import_helper import import_module 8 9maxsize = 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 16def 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 51def 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 75def 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 92def 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 97class 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 287 def test_str_format(self): 288 testformat("%r", "\u0378", "'\\u0378'") # non printable 289 testformat("%a", "\u0378", "'\\u0378'") # non printable 290 testformat("%r", "\u0374", "'\u0374'") # printable 291 testformat("%a", "\u0374", "'\\u0374'") # printable 292 293 # Test exception for unknown format characters, etc. 294 if verbose: 295 print('Testing exceptions') 296 test_exc('abc %b', 1, ValueError, 297 "unsupported format character 'b' (0x62) at index 5") 298 #test_exc(unicode('abc %\u3000','raw-unicode-escape'), 1, ValueError, 299 # "unsupported format character '?' (0x3000) at index 5") 300 test_exc('%g', '1', TypeError, "must be real number, not str") 301 test_exc('no format', '1', TypeError, 302 "not all arguments converted during string formatting") 303 test_exc('%c', -1, OverflowError, "%c arg not in range(0x110000)") 304 test_exc('%c', sys.maxunicode+1, OverflowError, 305 "%c arg not in range(0x110000)") 306 #test_exc('%c', 2**128, OverflowError, "%c arg not in range(0x110000)") 307 test_exc('%c', 3.14, TypeError, "%c requires int or char") 308 test_exc('%c', 'ab', TypeError, "%c requires int or char") 309 test_exc('%c', b'x', TypeError, "%c requires int or char") 310 311 if maxsize == 2**31-1: 312 # crashes 2.2.1 and earlier: 313 try: 314 "%*d"%(maxsize, -127) 315 except MemoryError: 316 pass 317 else: 318 raise TestFailed('"%*d"%(maxsize, -127) should fail') 319 320 def test_bytes_and_bytearray_format(self): 321 # %c will insert a single byte, either from an int in range(256), or 322 # from a bytes argument of length 1, not from a str. 323 testcommon(b"%c", 7, b"\x07") 324 testcommon(b"%c", b"Z", b"Z") 325 testcommon(b"%c", bytearray(b"Z"), b"Z") 326 testcommon(b"%5c", 65, b" A") 327 testcommon(b"%-5c", 65, b"A ") 328 # %b will insert a series of bytes, either from a type that supports 329 # the Py_buffer protocol, or something that has a __bytes__ method 330 class FakeBytes(object): 331 def __bytes__(self): 332 return b'123' 333 fb = FakeBytes() 334 testcommon(b"%b", b"abc", b"abc") 335 testcommon(b"%b", bytearray(b"def"), b"def") 336 testcommon(b"%b", fb, b"123") 337 testcommon(b"%b", memoryview(b"abc"), b"abc") 338 # # %s is an alias for %b -- should only be used for Py2/3 code 339 testcommon(b"%s", b"abc", b"abc") 340 testcommon(b"%s", bytearray(b"def"), b"def") 341 testcommon(b"%s", fb, b"123") 342 testcommon(b"%s", memoryview(b"abc"), b"abc") 343 # %a will give the equivalent of 344 # repr(some_obj).encode('ascii', 'backslashreplace') 345 testcommon(b"%a", 3.14, b"3.14") 346 testcommon(b"%a", b"ghi", b"b'ghi'") 347 testcommon(b"%a", "jkl", b"'jkl'") 348 testcommon(b"%a", "\u0544", b"'\\u0544'") 349 # %r is an alias for %a 350 testcommon(b"%r", 3.14, b"3.14") 351 testcommon(b"%r", b"ghi", b"b'ghi'") 352 testcommon(b"%r", "jkl", b"'jkl'") 353 testcommon(b"%r", "\u0544", b"'\\u0544'") 354 355 # Test exception for unknown format characters, etc. 356 if verbose: 357 print('Testing exceptions') 358 test_exc(b'%g', '1', TypeError, "float argument required, not str") 359 test_exc(b'%g', b'1', TypeError, "float argument required, not bytes") 360 test_exc(b'no format', 7, TypeError, 361 "not all arguments converted during bytes formatting") 362 test_exc(b'no format', b'1', TypeError, 363 "not all arguments converted during bytes formatting") 364 test_exc(b'no format', bytearray(b'1'), TypeError, 365 "not all arguments converted during bytes formatting") 366 test_exc(b"%c", -1, OverflowError, 367 "%c arg not in range(256)") 368 test_exc(b"%c", 256, OverflowError, 369 "%c arg not in range(256)") 370 test_exc(b"%c", 2**128, OverflowError, 371 "%c arg not in range(256)") 372 test_exc(b"%c", b"Za", TypeError, 373 "%c requires an integer in range(256) or a single byte") 374 test_exc(b"%c", "Y", TypeError, 375 "%c requires an integer in range(256) or a single byte") 376 test_exc(b"%c", 3.14, TypeError, 377 "%c requires an integer in range(256) or a single byte") 378 test_exc(b"%b", "Xc", TypeError, 379 "%b requires a bytes-like object, " 380 "or an object that implements __bytes__, not 'str'") 381 test_exc(b"%s", "Wd", TypeError, 382 "%b requires a bytes-like object, " 383 "or an object that implements __bytes__, not 'str'") 384 385 if maxsize == 2**31-1: 386 # crashes 2.2.1 and earlier: 387 try: 388 "%*d"%(maxsize, -127) 389 except MemoryError: 390 pass 391 else: 392 raise TestFailed('"%*d"%(maxsize, -127) should fail') 393 394 def test_nul(self): 395 # test the null character 396 testcommon("a\0b", (), 'a\0b') 397 testcommon("a%cb", (0,), 'a\0b') 398 testformat("a%sb", ('c\0d',), 'ac\0db') 399 testcommon(b"a%sb", (b'c\0d',), b'ac\0db') 400 401 def test_non_ascii(self): 402 testformat("\u20ac=%f", (1.0,), "\u20ac=1.000000") 403 404 self.assertEqual(format("abc", "\u2007<5"), "abc\u2007\u2007") 405 self.assertEqual(format(123, "\u2007<5"), "123\u2007\u2007") 406 self.assertEqual(format(12.3, "\u2007<6"), "12.3\u2007\u2007") 407 self.assertEqual(format(0j, "\u2007<4"), "0j\u2007\u2007") 408 self.assertEqual(format(1+2j, "\u2007<8"), "(1+2j)\u2007\u2007") 409 410 self.assertEqual(format("abc", "\u2007>5"), "\u2007\u2007abc") 411 self.assertEqual(format(123, "\u2007>5"), "\u2007\u2007123") 412 self.assertEqual(format(12.3, "\u2007>6"), "\u2007\u200712.3") 413 self.assertEqual(format(1+2j, "\u2007>8"), "\u2007\u2007(1+2j)") 414 self.assertEqual(format(0j, "\u2007>4"), "\u2007\u20070j") 415 416 self.assertEqual(format("abc", "\u2007^5"), "\u2007abc\u2007") 417 self.assertEqual(format(123, "\u2007^5"), "\u2007123\u2007") 418 self.assertEqual(format(12.3, "\u2007^6"), "\u200712.3\u2007") 419 self.assertEqual(format(1+2j, "\u2007^8"), "\u2007(1+2j)\u2007") 420 self.assertEqual(format(0j, "\u2007^4"), "\u20070j\u2007") 421 422 def test_locale(self): 423 try: 424 oldloc = locale.setlocale(locale.LC_ALL) 425 locale.setlocale(locale.LC_ALL, '') 426 except locale.Error as err: 427 self.skipTest("Cannot set locale: {}".format(err)) 428 try: 429 localeconv = locale.localeconv() 430 sep = localeconv['thousands_sep'] 431 point = localeconv['decimal_point'] 432 grouping = localeconv['grouping'] 433 434 text = format(123456789, "n") 435 if grouping: 436 self.assertIn(sep, text) 437 self.assertEqual(text.replace(sep, ''), '123456789') 438 439 text = format(1234.5, "n") 440 if grouping: 441 self.assertIn(sep, text) 442 self.assertIn(point, text) 443 self.assertEqual(text.replace(sep, ''), '1234' + point + '5') 444 finally: 445 locale.setlocale(locale.LC_ALL, oldloc) 446 447 @support.cpython_only 448 def test_optimisations(self): 449 text = "abcde" # 5 characters 450 451 self.assertIs("%s" % text, text) 452 self.assertIs("%.5s" % text, text) 453 self.assertIs("%.10s" % text, text) 454 self.assertIs("%1s" % text, text) 455 self.assertIs("%5s" % text, text) 456 457 self.assertIs("{0}".format(text), text) 458 self.assertIs("{0:s}".format(text), text) 459 self.assertIs("{0:.5s}".format(text), text) 460 self.assertIs("{0:.10s}".format(text), text) 461 self.assertIs("{0:1s}".format(text), text) 462 self.assertIs("{0:5s}".format(text), text) 463 464 self.assertIs(text % (), text) 465 self.assertIs(text.format(), text) 466 467 def test_precision(self): 468 f = 1.2 469 self.assertEqual(format(f, ".0f"), "1") 470 self.assertEqual(format(f, ".3f"), "1.200") 471 with self.assertRaises(ValueError) as cm: 472 format(f, ".%sf" % (sys.maxsize + 1)) 473 474 c = complex(f) 475 self.assertEqual(format(c, ".0f"), "1+0j") 476 self.assertEqual(format(c, ".3f"), "1.200+0.000j") 477 with self.assertRaises(ValueError) as cm: 478 format(c, ".%sf" % (sys.maxsize + 1)) 479 480 @support.cpython_only 481 def test_precision_c_limits(self): 482 _testcapi = import_module("_testcapi") 483 INT_MAX = _testcapi.INT_MAX 484 485 f = 1.2 486 with self.assertRaises(ValueError) as cm: 487 format(f, ".%sf" % (INT_MAX + 1)) 488 489 c = complex(f) 490 with self.assertRaises(ValueError) as cm: 491 format(c, ".%sf" % (INT_MAX + 1)) 492 493 def test_g_format_has_no_trailing_zeros(self): 494 # regression test for bugs.python.org/issue40780 495 self.assertEqual("%.3g" % 1505.0, "1.5e+03") 496 self.assertEqual("%#.3g" % 1505.0, "1.50e+03") 497 498 self.assertEqual(format(1505.0, ".3g"), "1.5e+03") 499 self.assertEqual(format(1505.0, "#.3g"), "1.50e+03") 500 501 self.assertEqual(format(12300050.0, ".6g"), "1.23e+07") 502 self.assertEqual(format(12300050.0, "#.6g"), "1.23000e+07") 503 504 def test_with_two_commas_in_format_specifier(self): 505 error_msg = re.escape("Cannot specify ',' with ','.") 506 with self.assertRaisesRegex(ValueError, error_msg): 507 '{:,,}'.format(1) 508 509 def test_with_two_underscore_in_format_specifier(self): 510 error_msg = re.escape("Cannot specify '_' with '_'.") 511 with self.assertRaisesRegex(ValueError, error_msg): 512 '{:__}'.format(1) 513 514 def test_with_a_commas_and_an_underscore_in_format_specifier(self): 515 error_msg = re.escape("Cannot specify both ',' and '_'.") 516 with self.assertRaisesRegex(ValueError, error_msg): 517 '{:,_}'.format(1) 518 519 def test_with_an_underscore_and_a_comma_in_format_specifier(self): 520 error_msg = re.escape("Cannot specify both ',' and '_'.") 521 with self.assertRaisesRegex(ValueError, error_msg): 522 '{:_,}'.format(1) 523 524 def test_better_error_message_format(self): 525 # https://bugs.python.org/issue20524 526 for value in [12j, 12, 12.0, "12"]: 527 with self.subTest(value=value): 528 # The format spec must be invalid for all types we're testing. 529 # '%M' will suffice. 530 bad_format_spec = '%M' 531 err = re.escape("Invalid format specifier " 532 f"'{bad_format_spec}' for object of type " 533 f"'{type(value).__name__}'") 534 with self.assertRaisesRegex(ValueError, err): 535 f"xx{{value:{bad_format_spec}}}yy".format(value=value) 536 537 # Also test the builtin format() function. 538 with self.assertRaisesRegex(ValueError, err): 539 format(value, bad_format_spec) 540 541 # Also test f-strings. 542 with self.assertRaisesRegex(ValueError, err): 543 eval("f'xx{value:{bad_format_spec}}yy'") 544 545 def test_unicode_in_error_message(self): 546 str_err = re.escape( 547 "Invalid format specifier '%ЫйЯЧ' for object of type 'str'") 548 with self.assertRaisesRegex(ValueError, str_err): 549 "{a:%ЫйЯЧ}".format(a='a') 550 551 def test_negative_zero(self): 552 ## default behavior 553 self.assertEqual(f"{-0.:.1f}", "-0.0") 554 self.assertEqual(f"{-.01:.1f}", "-0.0") 555 self.assertEqual(f"{-0:.1f}", "0.0") # integers do not distinguish -0 556 557 ## z sign option 558 self.assertEqual(f"{0.:z.1f}", "0.0") 559 self.assertEqual(f"{0.:z6.1f}", " 0.0") 560 self.assertEqual(f"{-1.:z6.1f}", " -1.0") 561 self.assertEqual(f"{-0.:z.1f}", "0.0") 562 self.assertEqual(f"{.01:z.1f}", "0.0") 563 self.assertEqual(f"{-0:z.1f}", "0.0") # z is allowed for integer input 564 self.assertEqual(f"{-.01:z.1f}", "0.0") 565 self.assertEqual(f"{0.:z.2f}", "0.00") 566 self.assertEqual(f"{-0.:z.2f}", "0.00") 567 self.assertEqual(f"{.001:z.2f}", "0.00") 568 self.assertEqual(f"{-.001:z.2f}", "0.00") 569 570 self.assertEqual(f"{0.:z.1e}", "0.0e+00") 571 self.assertEqual(f"{-0.:z.1e}", "0.0e+00") 572 self.assertEqual(f"{0.:z.1E}", "0.0E+00") 573 self.assertEqual(f"{-0.:z.1E}", "0.0E+00") 574 575 self.assertEqual(f"{-0.001:z.2e}", "-1.00e-03") # tests for mishandled 576 # rounding 577 self.assertEqual(f"{-0.001:z.2g}", "-0.001") 578 self.assertEqual(f"{-0.001:z.2%}", "-0.10%") 579 580 self.assertEqual(f"{-00000.000001:z.1f}", "0.0") 581 self.assertEqual(f"{-00000.:z.1f}", "0.0") 582 self.assertEqual(f"{-.0000000000:z.1f}", "0.0") 583 584 self.assertEqual(f"{-00000.000001:z.2f}", "0.00") 585 self.assertEqual(f"{-00000.:z.2f}", "0.00") 586 self.assertEqual(f"{-.0000000000:z.2f}", "0.00") 587 588 self.assertEqual(f"{.09:z.1f}", "0.1") 589 self.assertEqual(f"{-.09:z.1f}", "-0.1") 590 591 self.assertEqual(f"{-0.: z.0f}", " 0") 592 self.assertEqual(f"{-0.:+z.0f}", "+0") 593 self.assertEqual(f"{-0.:-z.0f}", "0") 594 self.assertEqual(f"{-1.: z.0f}", "-1") 595 self.assertEqual(f"{-1.:+z.0f}", "-1") 596 self.assertEqual(f"{-1.:-z.0f}", "-1") 597 598 self.assertEqual(f"{0.j:z.1f}", "0.0+0.0j") 599 self.assertEqual(f"{-0.j:z.1f}", "0.0+0.0j") 600 self.assertEqual(f"{.01j:z.1f}", "0.0+0.0j") 601 self.assertEqual(f"{-.01j:z.1f}", "0.0+0.0j") 602 603 self.assertEqual(f"{-0.:z>6.1f}", "zz-0.0") # test fill, esp. 'z' fill 604 self.assertEqual(f"{-0.:z>z6.1f}", "zzz0.0") 605 self.assertEqual(f"{-0.:x>z6.1f}", "xxx0.0") 606 self.assertEqual(f"{-0.:>z6.1f}", "0.0") # multi-byte fill char 607 608 def test_specifier_z_error(self): 609 error_msg = re.compile("Invalid format specifier '.*z.*'") 610 with self.assertRaisesRegex(ValueError, error_msg): 611 f"{0:z+f}" # wrong position 612 with self.assertRaisesRegex(ValueError, error_msg): 613 f"{0:fz}" # wrong position 614 615 error_msg = re.escape("Negative zero coercion (z) not allowed") 616 with self.assertRaisesRegex(ValueError, error_msg): 617 f"{0:zd}" # can't apply to int presentation type 618 with self.assertRaisesRegex(ValueError, error_msg): 619 f"{'x':zs}" # can't apply to string 620 621 error_msg = re.escape("unsupported format character 'z'") 622 with self.assertRaisesRegex(ValueError, error_msg): 623 "%z.1f" % 0 # not allowed in old style string interpolation 624 with self.assertRaisesRegex(ValueError, error_msg): 625 b"%z.1f" % 0 626 627 628if __name__ == "__main__": 629 unittest.main() 630