test_format.py 28 KB

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