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