test_unicode.py 123 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736
  1. """ Test script for the Unicode implementation.
  2. Written by Marc-Andre Lemburg (mal@lemburg.com).
  3. (c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
  4. """
  5. import _string
  6. import codecs
  7. import itertools
  8. import operator
  9. import pickle
  10. import struct
  11. import sys
  12. import textwrap
  13. import unicodedata
  14. import unittest
  15. import warnings
  16. from test.support import warnings_helper
  17. from test import support, string_tests
  18. from test.support.script_helper import assert_python_failure
  19. try:
  20. import _testcapi
  21. except ImportError:
  22. _testcapi = None
  23. # Error handling (bad decoder return)
  24. def search_function(encoding):
  25. def decode1(input, errors="strict"):
  26. return 42 # not a tuple
  27. def encode1(input, errors="strict"):
  28. return 42 # not a tuple
  29. def encode2(input, errors="strict"):
  30. return (42, 42) # no unicode
  31. def decode2(input, errors="strict"):
  32. return (42, 42) # no unicode
  33. if encoding=="test.unicode1":
  34. return (encode1, decode1, None, None)
  35. elif encoding=="test.unicode2":
  36. return (encode2, decode2, None, None)
  37. else:
  38. return None
  39. def duplicate_string(text):
  40. """
  41. Try to get a fresh clone of the specified text:
  42. new object with a reference count of 1.
  43. This is a best-effort: latin1 single letters and the empty
  44. string ('') are singletons and cannot be cloned.
  45. """
  46. return text.encode().decode()
  47. class StrSubclass(str):
  48. pass
  49. class UnicodeTest(string_tests.CommonTest,
  50. string_tests.MixinStrUnicodeUserStringTest,
  51. string_tests.MixinStrUnicodeTest,
  52. unittest.TestCase):
  53. type2test = str
  54. def setUp(self):
  55. codecs.register(search_function)
  56. self.addCleanup(codecs.unregister, search_function)
  57. def checkequalnofix(self, result, object, methodname, *args):
  58. method = getattr(object, methodname)
  59. realresult = method(*args)
  60. self.assertEqual(realresult, result)
  61. self.assertTrue(type(realresult) is type(result))
  62. # if the original is returned make sure that
  63. # this doesn't happen with subclasses
  64. if realresult is object:
  65. class usub(str):
  66. def __repr__(self):
  67. return 'usub(%r)' % str.__repr__(self)
  68. object = usub(object)
  69. method = getattr(object, methodname)
  70. realresult = method(*args)
  71. self.assertEqual(realresult, result)
  72. self.assertTrue(object is not realresult)
  73. def test_literals(self):
  74. self.assertEqual('\xff', '\u00ff')
  75. self.assertEqual('\uffff', '\U0000ffff')
  76. self.assertRaises(SyntaxError, eval, '\'\\Ufffffffe\'')
  77. self.assertRaises(SyntaxError, eval, '\'\\Uffffffff\'')
  78. self.assertRaises(SyntaxError, eval, '\'\\U%08x\'' % 0x110000)
  79. # raw strings should not have unicode escapes
  80. self.assertNotEqual(r"\u0020", " ")
  81. def test_ascii(self):
  82. if not sys.platform.startswith('java'):
  83. # Test basic sanity of repr()
  84. self.assertEqual(ascii('abc'), "'abc'")
  85. self.assertEqual(ascii('ab\\c'), "'ab\\\\c'")
  86. self.assertEqual(ascii('ab\\'), "'ab\\\\'")
  87. self.assertEqual(ascii('\\c'), "'\\\\c'")
  88. self.assertEqual(ascii('\\'), "'\\\\'")
  89. self.assertEqual(ascii('\n'), "'\\n'")
  90. self.assertEqual(ascii('\r'), "'\\r'")
  91. self.assertEqual(ascii('\t'), "'\\t'")
  92. self.assertEqual(ascii('\b'), "'\\x08'")
  93. self.assertEqual(ascii("'\""), """'\\'"'""")
  94. self.assertEqual(ascii("'\""), """'\\'"'""")
  95. self.assertEqual(ascii("'"), '''"'"''')
  96. self.assertEqual(ascii('"'), """'"'""")
  97. latin1repr = (
  98. "'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r"
  99. "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a"
  100. "\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHI"
  101. "JKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f"
  102. "\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d"
  103. "\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b"
  104. "\\x9c\\x9d\\x9e\\x9f\\xa0\\xa1\\xa2\\xa3\\xa4\\xa5\\xa6\\xa7\\xa8\\xa9"
  105. "\\xaa\\xab\\xac\\xad\\xae\\xaf\\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7"
  106. "\\xb8\\xb9\\xba\\xbb\\xbc\\xbd\\xbe\\xbf\\xc0\\xc1\\xc2\\xc3\\xc4\\xc5"
  107. "\\xc6\\xc7\\xc8\\xc9\\xca\\xcb\\xcc\\xcd\\xce\\xcf\\xd0\\xd1\\xd2\\xd3"
  108. "\\xd4\\xd5\\xd6\\xd7\\xd8\\xd9\\xda\\xdb\\xdc\\xdd\\xde\\xdf\\xe0\\xe1"
  109. "\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef"
  110. "\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd"
  111. "\\xfe\\xff'")
  112. testrepr = ascii(''.join(map(chr, range(256))))
  113. self.assertEqual(testrepr, latin1repr)
  114. # Test ascii works on wide unicode escapes without overflow.
  115. self.assertEqual(ascii("\U00010000" * 39 + "\uffff" * 4096),
  116. ascii("\U00010000" * 39 + "\uffff" * 4096))
  117. class WrongRepr:
  118. def __repr__(self):
  119. return b'byte-repr'
  120. self.assertRaises(TypeError, ascii, WrongRepr())
  121. def test_repr(self):
  122. if not sys.platform.startswith('java'):
  123. # Test basic sanity of repr()
  124. self.assertEqual(repr('abc'), "'abc'")
  125. self.assertEqual(repr('ab\\c'), "'ab\\\\c'")
  126. self.assertEqual(repr('ab\\'), "'ab\\\\'")
  127. self.assertEqual(repr('\\c'), "'\\\\c'")
  128. self.assertEqual(repr('\\'), "'\\\\'")
  129. self.assertEqual(repr('\n'), "'\\n'")
  130. self.assertEqual(repr('\r'), "'\\r'")
  131. self.assertEqual(repr('\t'), "'\\t'")
  132. self.assertEqual(repr('\b'), "'\\x08'")
  133. self.assertEqual(repr("'\""), """'\\'"'""")
  134. self.assertEqual(repr("'\""), """'\\'"'""")
  135. self.assertEqual(repr("'"), '''"'"''')
  136. self.assertEqual(repr('"'), """'"'""")
  137. latin1repr = (
  138. "'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r"
  139. "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a"
  140. "\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHI"
  141. "JKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f"
  142. "\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d"
  143. "\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b"
  144. "\\x9c\\x9d\\x9e\\x9f\\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9"
  145. "\xaa\xab\xac\\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7"
  146. "\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5"
  147. "\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3"
  148. "\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1"
  149. "\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef"
  150. "\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd"
  151. "\xfe\xff'")
  152. testrepr = repr(''.join(map(chr, range(256))))
  153. self.assertEqual(testrepr, latin1repr)
  154. # Test repr works on wide unicode escapes without overflow.
  155. self.assertEqual(repr("\U00010000" * 39 + "\uffff" * 4096),
  156. repr("\U00010000" * 39 + "\uffff" * 4096))
  157. class WrongRepr:
  158. def __repr__(self):
  159. return b'byte-repr'
  160. self.assertRaises(TypeError, repr, WrongRepr())
  161. def test_iterators(self):
  162. # Make sure unicode objects have an __iter__ method
  163. it = "\u1111\u2222\u3333".__iter__()
  164. self.assertEqual(next(it), "\u1111")
  165. self.assertEqual(next(it), "\u2222")
  166. self.assertEqual(next(it), "\u3333")
  167. self.assertRaises(StopIteration, next, it)
  168. def test_iterators_invocation(self):
  169. cases = [type(iter('abc')), type(iter('🚀'))]
  170. for cls in cases:
  171. with self.subTest(cls=cls):
  172. self.assertRaises(TypeError, cls)
  173. def test_iteration(self):
  174. cases = ['abc', '🚀🚀🚀', "\u1111\u2222\u3333"]
  175. for case in cases:
  176. with self.subTest(string=case):
  177. self.assertEqual(case, "".join(iter(case)))
  178. def test_exhausted_iterator(self):
  179. cases = ['abc', '🚀🚀🚀', "\u1111\u2222\u3333"]
  180. for case in cases:
  181. with self.subTest(case=case):
  182. iterator = iter(case)
  183. tuple(iterator)
  184. self.assertRaises(StopIteration, next, iterator)
  185. def test_pickle_iterator(self):
  186. cases = ['abc', '🚀🚀🚀', "\u1111\u2222\u3333"]
  187. for case in cases:
  188. with self.subTest(case=case):
  189. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  190. it = iter(case)
  191. with self.subTest(proto=proto):
  192. pickled = "".join(pickle.loads(pickle.dumps(it, proto)))
  193. self.assertEqual(case, pickled)
  194. def test_count(self):
  195. string_tests.CommonTest.test_count(self)
  196. # check mixed argument types
  197. self.checkequalnofix(3, 'aaa', 'count', 'a')
  198. self.checkequalnofix(0, 'aaa', 'count', 'b')
  199. self.checkequalnofix(3, 'aaa', 'count', 'a')
  200. self.checkequalnofix(0, 'aaa', 'count', 'b')
  201. self.checkequalnofix(0, 'aaa', 'count', 'b')
  202. self.checkequalnofix(1, 'aaa', 'count', 'a', -1)
  203. self.checkequalnofix(3, 'aaa', 'count', 'a', -10)
  204. self.checkequalnofix(2, 'aaa', 'count', 'a', 0, -1)
  205. self.checkequalnofix(0, 'aaa', 'count', 'a', 0, -10)
  206. # test mixed kinds
  207. self.checkequal(10, '\u0102' + 'a' * 10, 'count', 'a')
  208. self.checkequal(10, '\U00100304' + 'a' * 10, 'count', 'a')
  209. self.checkequal(10, '\U00100304' + '\u0102' * 10, 'count', '\u0102')
  210. self.checkequal(0, 'a' * 10, 'count', '\u0102')
  211. self.checkequal(0, 'a' * 10, 'count', '\U00100304')
  212. self.checkequal(0, '\u0102' * 10, 'count', '\U00100304')
  213. self.checkequal(10, '\u0102' + 'a_' * 10, 'count', 'a_')
  214. self.checkequal(10, '\U00100304' + 'a_' * 10, 'count', 'a_')
  215. self.checkequal(10, '\U00100304' + '\u0102_' * 10, 'count', '\u0102_')
  216. self.checkequal(0, 'a' * 10, 'count', 'a\u0102')
  217. self.checkequal(0, 'a' * 10, 'count', 'a\U00100304')
  218. self.checkequal(0, '\u0102' * 10, 'count', '\u0102\U00100304')
  219. def test_find(self):
  220. string_tests.CommonTest.test_find(self)
  221. # test implementation details of the memchr fast path
  222. self.checkequal(100, 'a' * 100 + '\u0102', 'find', '\u0102')
  223. self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0201')
  224. self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0120')
  225. self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0220')
  226. self.checkequal(100, 'a' * 100 + '\U00100304', 'find', '\U00100304')
  227. self.checkequal(-1, 'a' * 100 + '\U00100304', 'find', '\U00100204')
  228. self.checkequal(-1, 'a' * 100 + '\U00100304', 'find', '\U00102004')
  229. # check mixed argument types
  230. self.checkequalnofix(0, 'abcdefghiabc', 'find', 'abc')
  231. self.checkequalnofix(9, 'abcdefghiabc', 'find', 'abc', 1)
  232. self.checkequalnofix(-1, 'abcdefghiabc', 'find', 'def', 4)
  233. # test utf-8 non-ascii char
  234. self.checkequal(0, 'тест', 'find', 'т')
  235. self.checkequal(3, 'тест', 'find', 'т', 1)
  236. self.checkequal(-1, 'тест', 'find', 'т', 1, 3)
  237. self.checkequal(-1, 'тест', 'find', 'e') # english `e`
  238. # test utf-8 non-ascii slice
  239. self.checkequal(1, 'тест тест', 'find', 'ес')
  240. self.checkequal(1, 'тест тест', 'find', 'ес', 1)
  241. self.checkequal(1, 'тест тест', 'find', 'ес', 1, 3)
  242. self.checkequal(6, 'тест тест', 'find', 'ес', 2)
  243. self.checkequal(-1, 'тест тест', 'find', 'ес', 6, 7)
  244. self.checkequal(-1, 'тест тест', 'find', 'ес', 7)
  245. self.checkequal(-1, 'тест тест', 'find', 'ec') # english `ec`
  246. self.assertRaises(TypeError, 'hello'.find)
  247. self.assertRaises(TypeError, 'hello'.find, 42)
  248. # test mixed kinds
  249. self.checkequal(100, '\u0102' * 100 + 'a', 'find', 'a')
  250. self.checkequal(100, '\U00100304' * 100 + 'a', 'find', 'a')
  251. self.checkequal(100, '\U00100304' * 100 + '\u0102', 'find', '\u0102')
  252. self.checkequal(-1, 'a' * 100, 'find', '\u0102')
  253. self.checkequal(-1, 'a' * 100, 'find', '\U00100304')
  254. self.checkequal(-1, '\u0102' * 100, 'find', '\U00100304')
  255. self.checkequal(100, '\u0102' * 100 + 'a_', 'find', 'a_')
  256. self.checkequal(100, '\U00100304' * 100 + 'a_', 'find', 'a_')
  257. self.checkequal(100, '\U00100304' * 100 + '\u0102_', 'find', '\u0102_')
  258. self.checkequal(-1, 'a' * 100, 'find', 'a\u0102')
  259. self.checkequal(-1, 'a' * 100, 'find', 'a\U00100304')
  260. self.checkequal(-1, '\u0102' * 100, 'find', '\u0102\U00100304')
  261. def test_rfind(self):
  262. string_tests.CommonTest.test_rfind(self)
  263. # test implementation details of the memrchr fast path
  264. self.checkequal(0, '\u0102' + 'a' * 100 , 'rfind', '\u0102')
  265. self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0201')
  266. self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0120')
  267. self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0220')
  268. self.checkequal(0, '\U00100304' + 'a' * 100, 'rfind', '\U00100304')
  269. self.checkequal(-1, '\U00100304' + 'a' * 100, 'rfind', '\U00100204')
  270. self.checkequal(-1, '\U00100304' + 'a' * 100, 'rfind', '\U00102004')
  271. # check mixed argument types
  272. self.checkequalnofix(9, 'abcdefghiabc', 'rfind', 'abc')
  273. self.checkequalnofix(12, 'abcdefghiabc', 'rfind', '')
  274. self.checkequalnofix(12, 'abcdefghiabc', 'rfind', '')
  275. # test utf-8 non-ascii char
  276. self.checkequal(1, 'тест', 'rfind', 'е')
  277. self.checkequal(1, 'тест', 'rfind', 'е', 1)
  278. self.checkequal(-1, 'тест', 'rfind', 'е', 2)
  279. self.checkequal(-1, 'тест', 'rfind', 'e') # english `e`
  280. # test utf-8 non-ascii slice
  281. self.checkequal(6, 'тест тест', 'rfind', 'ес')
  282. self.checkequal(6, 'тест тест', 'rfind', 'ес', 1)
  283. self.checkequal(1, 'тест тест', 'rfind', 'ес', 1, 3)
  284. self.checkequal(6, 'тест тест', 'rfind', 'ес', 2)
  285. self.checkequal(-1, 'тест тест', 'rfind', 'ес', 6, 7)
  286. self.checkequal(-1, 'тест тест', 'rfind', 'ес', 7)
  287. self.checkequal(-1, 'тест тест', 'rfind', 'ec') # english `ec`
  288. # test mixed kinds
  289. self.checkequal(0, 'a' + '\u0102' * 100, 'rfind', 'a')
  290. self.checkequal(0, 'a' + '\U00100304' * 100, 'rfind', 'a')
  291. self.checkequal(0, '\u0102' + '\U00100304' * 100, 'rfind', '\u0102')
  292. self.checkequal(-1, 'a' * 100, 'rfind', '\u0102')
  293. self.checkequal(-1, 'a' * 100, 'rfind', '\U00100304')
  294. self.checkequal(-1, '\u0102' * 100, 'rfind', '\U00100304')
  295. self.checkequal(0, '_a' + '\u0102' * 100, 'rfind', '_a')
  296. self.checkequal(0, '_a' + '\U00100304' * 100, 'rfind', '_a')
  297. self.checkequal(0, '_\u0102' + '\U00100304' * 100, 'rfind', '_\u0102')
  298. self.checkequal(-1, 'a' * 100, 'rfind', '\u0102a')
  299. self.checkequal(-1, 'a' * 100, 'rfind', '\U00100304a')
  300. self.checkequal(-1, '\u0102' * 100, 'rfind', '\U00100304\u0102')
  301. def test_index(self):
  302. string_tests.CommonTest.test_index(self)
  303. self.checkequalnofix(0, 'abcdefghiabc', 'index', '')
  304. self.checkequalnofix(3, 'abcdefghiabc', 'index', 'def')
  305. self.checkequalnofix(0, 'abcdefghiabc', 'index', 'abc')
  306. self.checkequalnofix(9, 'abcdefghiabc', 'index', 'abc', 1)
  307. self.assertRaises(ValueError, 'abcdefghiabc'.index, 'hib')
  308. self.assertRaises(ValueError, 'abcdefghiab'.index, 'abc', 1)
  309. self.assertRaises(ValueError, 'abcdefghi'.index, 'ghi', 8)
  310. self.assertRaises(ValueError, 'abcdefghi'.index, 'ghi', -1)
  311. # test mixed kinds
  312. self.checkequal(100, '\u0102' * 100 + 'a', 'index', 'a')
  313. self.checkequal(100, '\U00100304' * 100 + 'a', 'index', 'a')
  314. self.checkequal(100, '\U00100304' * 100 + '\u0102', 'index', '\u0102')
  315. self.assertRaises(ValueError, ('a' * 100).index, '\u0102')
  316. self.assertRaises(ValueError, ('a' * 100).index, '\U00100304')
  317. self.assertRaises(ValueError, ('\u0102' * 100).index, '\U00100304')
  318. self.checkequal(100, '\u0102' * 100 + 'a_', 'index', 'a_')
  319. self.checkequal(100, '\U00100304' * 100 + 'a_', 'index', 'a_')
  320. self.checkequal(100, '\U00100304' * 100 + '\u0102_', 'index', '\u0102_')
  321. self.assertRaises(ValueError, ('a' * 100).index, 'a\u0102')
  322. self.assertRaises(ValueError, ('a' * 100).index, 'a\U00100304')
  323. self.assertRaises(ValueError, ('\u0102' * 100).index, '\u0102\U00100304')
  324. def test_rindex(self):
  325. string_tests.CommonTest.test_rindex(self)
  326. self.checkequalnofix(12, 'abcdefghiabc', 'rindex', '')
  327. self.checkequalnofix(3, 'abcdefghiabc', 'rindex', 'def')
  328. self.checkequalnofix(9, 'abcdefghiabc', 'rindex', 'abc')
  329. self.checkequalnofix(0, 'abcdefghiabc', 'rindex', 'abc', 0, -1)
  330. self.assertRaises(ValueError, 'abcdefghiabc'.rindex, 'hib')
  331. self.assertRaises(ValueError, 'defghiabc'.rindex, 'def', 1)
  332. self.assertRaises(ValueError, 'defghiabc'.rindex, 'abc', 0, -1)
  333. self.assertRaises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, 8)
  334. self.assertRaises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, -1)
  335. # test mixed kinds
  336. self.checkequal(0, 'a' + '\u0102' * 100, 'rindex', 'a')
  337. self.checkequal(0, 'a' + '\U00100304' * 100, 'rindex', 'a')
  338. self.checkequal(0, '\u0102' + '\U00100304' * 100, 'rindex', '\u0102')
  339. self.assertRaises(ValueError, ('a' * 100).rindex, '\u0102')
  340. self.assertRaises(ValueError, ('a' * 100).rindex, '\U00100304')
  341. self.assertRaises(ValueError, ('\u0102' * 100).rindex, '\U00100304')
  342. self.checkequal(0, '_a' + '\u0102' * 100, 'rindex', '_a')
  343. self.checkequal(0, '_a' + '\U00100304' * 100, 'rindex', '_a')
  344. self.checkequal(0, '_\u0102' + '\U00100304' * 100, 'rindex', '_\u0102')
  345. self.assertRaises(ValueError, ('a' * 100).rindex, '\u0102a')
  346. self.assertRaises(ValueError, ('a' * 100).rindex, '\U00100304a')
  347. self.assertRaises(ValueError, ('\u0102' * 100).rindex, '\U00100304\u0102')
  348. def test_maketrans_translate(self):
  349. # these work with plain translate()
  350. self.checkequalnofix('bbbc', 'abababc', 'translate',
  351. {ord('a'): None})
  352. self.checkequalnofix('iiic', 'abababc', 'translate',
  353. {ord('a'): None, ord('b'): ord('i')})
  354. self.checkequalnofix('iiix', 'abababc', 'translate',
  355. {ord('a'): None, ord('b'): ord('i'), ord('c'): 'x'})
  356. self.checkequalnofix('c', 'abababc', 'translate',
  357. {ord('a'): None, ord('b'): ''})
  358. self.checkequalnofix('xyyx', 'xzx', 'translate',
  359. {ord('z'): 'yy'})
  360. # this needs maketrans()
  361. self.checkequalnofix('abababc', 'abababc', 'translate',
  362. {'b': '<i>'})
  363. tbl = self.type2test.maketrans({'a': None, 'b': '<i>'})
  364. self.checkequalnofix('<i><i><i>c', 'abababc', 'translate', tbl)
  365. # test alternative way of calling maketrans()
  366. tbl = self.type2test.maketrans('abc', 'xyz', 'd')
  367. self.checkequalnofix('xyzzy', 'abdcdcbdddd', 'translate', tbl)
  368. # various tests switching from ASCII to latin1 or the opposite;
  369. # same length, remove a letter, or replace with a longer string.
  370. self.assertEqual("[a]".translate(str.maketrans('a', 'X')),
  371. "[X]")
  372. self.assertEqual("[a]".translate(str.maketrans({'a': 'X'})),
  373. "[X]")
  374. self.assertEqual("[a]".translate(str.maketrans({'a': None})),
  375. "[]")
  376. self.assertEqual("[a]".translate(str.maketrans({'a': 'XXX'})),
  377. "[XXX]")
  378. self.assertEqual("[a]".translate(str.maketrans({'a': '\xe9'})),
  379. "[\xe9]")
  380. self.assertEqual('axb'.translate(str.maketrans({'a': None, 'b': '123'})),
  381. "x123")
  382. self.assertEqual('axb'.translate(str.maketrans({'a': None, 'b': '\xe9'})),
  383. "x\xe9")
  384. # test non-ASCII (don't take the fast-path)
  385. self.assertEqual("[a]".translate(str.maketrans({'a': '<\xe9>'})),
  386. "[<\xe9>]")
  387. self.assertEqual("[\xe9]".translate(str.maketrans({'\xe9': 'a'})),
  388. "[a]")
  389. self.assertEqual("[\xe9]".translate(str.maketrans({'\xe9': None})),
  390. "[]")
  391. self.assertEqual("[\xe9]".translate(str.maketrans({'\xe9': '123'})),
  392. "[123]")
  393. self.assertEqual("[a\xe9]".translate(str.maketrans({'a': '<\u20ac>'})),
  394. "[<\u20ac>\xe9]")
  395. # invalid Unicode characters
  396. invalid_char = 0x10ffff+1
  397. for before in "a\xe9\u20ac\U0010ffff":
  398. mapping = str.maketrans({before: invalid_char})
  399. text = "[%s]" % before
  400. self.assertRaises(ValueError, text.translate, mapping)
  401. # errors
  402. self.assertRaises(TypeError, self.type2test.maketrans)
  403. self.assertRaises(ValueError, self.type2test.maketrans, 'abc', 'defg')
  404. self.assertRaises(TypeError, self.type2test.maketrans, 2, 'def')
  405. self.assertRaises(TypeError, self.type2test.maketrans, 'abc', 2)
  406. self.assertRaises(TypeError, self.type2test.maketrans, 'abc', 'def', 2)
  407. self.assertRaises(ValueError, self.type2test.maketrans, {'xy': 2})
  408. self.assertRaises(TypeError, self.type2test.maketrans, {(1,): 2})
  409. self.assertRaises(TypeError, 'hello'.translate)
  410. self.assertRaises(TypeError, 'abababc'.translate, 'abc', 'xyz')
  411. def test_split(self):
  412. string_tests.CommonTest.test_split(self)
  413. # test mixed kinds
  414. for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
  415. left *= 9
  416. right *= 9
  417. for delim in ('c', '\u0102', '\U00010302'):
  418. self.checkequal([left + right],
  419. left + right, 'split', delim)
  420. self.checkequal([left, right],
  421. left + delim + right, 'split', delim)
  422. self.checkequal([left + right],
  423. left + right, 'split', delim * 2)
  424. self.checkequal([left, right],
  425. left + delim * 2 + right, 'split', delim *2)
  426. def test_rsplit(self):
  427. string_tests.CommonTest.test_rsplit(self)
  428. # test mixed kinds
  429. for left, right in ('ba', 'юё', '\u0101\u0100', '\U00010301\U00010300'):
  430. left *= 9
  431. right *= 9
  432. for delim in ('c', 'ы', '\u0102', '\U00010302'):
  433. self.checkequal([left + right],
  434. left + right, 'rsplit', delim)
  435. self.checkequal([left, right],
  436. left + delim + right, 'rsplit', delim)
  437. self.checkequal([left + right],
  438. left + right, 'rsplit', delim * 2)
  439. self.checkequal([left, right],
  440. left + delim * 2 + right, 'rsplit', delim *2)
  441. # Check `None` as well:
  442. self.checkequal([left + right],
  443. left + right, 'rsplit', None)
  444. def test_partition(self):
  445. string_tests.MixinStrUnicodeUserStringTest.test_partition(self)
  446. # test mixed kinds
  447. self.checkequal(('ABCDEFGH', '', ''), 'ABCDEFGH', 'partition', '\u4200')
  448. for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
  449. left *= 9
  450. right *= 9
  451. for delim in ('c', '\u0102', '\U00010302'):
  452. self.checkequal((left + right, '', ''),
  453. left + right, 'partition', delim)
  454. self.checkequal((left, delim, right),
  455. left + delim + right, 'partition', delim)
  456. self.checkequal((left + right, '', ''),
  457. left + right, 'partition', delim * 2)
  458. self.checkequal((left, delim * 2, right),
  459. left + delim * 2 + right, 'partition', delim * 2)
  460. def test_rpartition(self):
  461. string_tests.MixinStrUnicodeUserStringTest.test_rpartition(self)
  462. # test mixed kinds
  463. self.checkequal(('', '', 'ABCDEFGH'), 'ABCDEFGH', 'rpartition', '\u4200')
  464. for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
  465. left *= 9
  466. right *= 9
  467. for delim in ('c', '\u0102', '\U00010302'):
  468. self.checkequal(('', '', left + right),
  469. left + right, 'rpartition', delim)
  470. self.checkequal((left, delim, right),
  471. left + delim + right, 'rpartition', delim)
  472. self.checkequal(('', '', left + right),
  473. left + right, 'rpartition', delim * 2)
  474. self.checkequal((left, delim * 2, right),
  475. left + delim * 2 + right, 'rpartition', delim * 2)
  476. def test_join(self):
  477. string_tests.MixinStrUnicodeUserStringTest.test_join(self)
  478. class MyWrapper:
  479. def __init__(self, sval): self.sval = sval
  480. def __str__(self): return self.sval
  481. # mixed arguments
  482. self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
  483. self.checkequalnofix('abcd', '', 'join', ('a', 'b', 'c', 'd'))
  484. self.checkequalnofix('w x y z', ' ', 'join', string_tests.Sequence('wxyz'))
  485. self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
  486. self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
  487. self.checkequalnofix('abcd', '', 'join', ('a', 'b', 'c', 'd'))
  488. self.checkequalnofix('w x y z', ' ', 'join', string_tests.Sequence('wxyz'))
  489. self.checkraises(TypeError, ' ', 'join', ['1', '2', MyWrapper('foo')])
  490. self.checkraises(TypeError, ' ', 'join', ['1', '2', '3', bytes()])
  491. self.checkraises(TypeError, ' ', 'join', [1, 2, 3])
  492. self.checkraises(TypeError, ' ', 'join', ['1', '2', 3])
  493. @unittest.skipIf(sys.maxsize > 2**32,
  494. 'needs too much memory on a 64-bit platform')
  495. def test_join_overflow(self):
  496. size = int(sys.maxsize**0.5) + 1
  497. seq = ('A' * size,) * size
  498. self.assertRaises(OverflowError, ''.join, seq)
  499. def test_replace(self):
  500. string_tests.CommonTest.test_replace(self)
  501. # method call forwarded from str implementation because of unicode argument
  502. self.checkequalnofix('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1)
  503. self.assertRaises(TypeError, 'replace'.replace, "r", 42)
  504. # test mixed kinds
  505. for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
  506. left *= 9
  507. right *= 9
  508. for delim in ('c', '\u0102', '\U00010302'):
  509. for repl in ('d', '\u0103', '\U00010303'):
  510. self.checkequal(left + right,
  511. left + right, 'replace', delim, repl)
  512. self.checkequal(left + repl + right,
  513. left + delim + right,
  514. 'replace', delim, repl)
  515. self.checkequal(left + right,
  516. left + right, 'replace', delim * 2, repl)
  517. self.checkequal(left + repl + right,
  518. left + delim * 2 + right,
  519. 'replace', delim * 2, repl)
  520. @support.cpython_only
  521. def test_replace_id(self):
  522. pattern = 'abc'
  523. text = 'abc def'
  524. self.assertIs(text.replace(pattern, pattern), text)
  525. def test_repeat_id_preserving(self):
  526. a = '123abc1@'
  527. b = '456zyx-+'
  528. self.assertEqual(id(a), id(a))
  529. self.assertNotEqual(id(a), id(b))
  530. self.assertNotEqual(id(a), id(a * -4))
  531. self.assertNotEqual(id(a), id(a * 0))
  532. self.assertEqual(id(a), id(a * 1))
  533. self.assertEqual(id(a), id(1 * a))
  534. self.assertNotEqual(id(a), id(a * 2))
  535. class SubStr(str):
  536. pass
  537. s = SubStr('qwerty()')
  538. self.assertEqual(id(s), id(s))
  539. self.assertNotEqual(id(s), id(s * -4))
  540. self.assertNotEqual(id(s), id(s * 0))
  541. self.assertNotEqual(id(s), id(s * 1))
  542. self.assertNotEqual(id(s), id(1 * s))
  543. self.assertNotEqual(id(s), id(s * 2))
  544. def test_bytes_comparison(self):
  545. with warnings_helper.check_warnings():
  546. warnings.simplefilter('ignore', BytesWarning)
  547. self.assertEqual('abc' == b'abc', False)
  548. self.assertEqual('abc' != b'abc', True)
  549. self.assertEqual('abc' == bytearray(b'abc'), False)
  550. self.assertEqual('abc' != bytearray(b'abc'), True)
  551. def test_comparison(self):
  552. # Comparisons:
  553. self.assertEqual('abc', 'abc')
  554. self.assertTrue('abcd' > 'abc')
  555. self.assertTrue('abc' < 'abcd')
  556. if 0:
  557. # Move these tests to a Unicode collation module test...
  558. # Testing UTF-16 code point order comparisons...
  559. # No surrogates, no fixup required.
  560. self.assertTrue('\u0061' < '\u20ac')
  561. # Non surrogate below surrogate value, no fixup required
  562. self.assertTrue('\u0061' < '\ud800\udc02')
  563. # Non surrogate above surrogate value, fixup required
  564. def test_lecmp(s, s2):
  565. self.assertTrue(s < s2)
  566. def test_fixup(s):
  567. s2 = '\ud800\udc01'
  568. test_lecmp(s, s2)
  569. s2 = '\ud900\udc01'
  570. test_lecmp(s, s2)
  571. s2 = '\uda00\udc01'
  572. test_lecmp(s, s2)
  573. s2 = '\udb00\udc01'
  574. test_lecmp(s, s2)
  575. s2 = '\ud800\udd01'
  576. test_lecmp(s, s2)
  577. s2 = '\ud900\udd01'
  578. test_lecmp(s, s2)
  579. s2 = '\uda00\udd01'
  580. test_lecmp(s, s2)
  581. s2 = '\udb00\udd01'
  582. test_lecmp(s, s2)
  583. s2 = '\ud800\ude01'
  584. test_lecmp(s, s2)
  585. s2 = '\ud900\ude01'
  586. test_lecmp(s, s2)
  587. s2 = '\uda00\ude01'
  588. test_lecmp(s, s2)
  589. s2 = '\udb00\ude01'
  590. test_lecmp(s, s2)
  591. s2 = '\ud800\udfff'
  592. test_lecmp(s, s2)
  593. s2 = '\ud900\udfff'
  594. test_lecmp(s, s2)
  595. s2 = '\uda00\udfff'
  596. test_lecmp(s, s2)
  597. s2 = '\udb00\udfff'
  598. test_lecmp(s, s2)
  599. test_fixup('\ue000')
  600. test_fixup('\uff61')
  601. # Surrogates on both sides, no fixup required
  602. self.assertTrue('\ud800\udc02' < '\ud84d\udc56')
  603. def test_islower(self):
  604. super().test_islower()
  605. self.checkequalnofix(False, '\u1FFc', 'islower')
  606. self.assertFalse('\u2167'.islower())
  607. self.assertTrue('\u2177'.islower())
  608. # non-BMP, uppercase
  609. self.assertFalse('\U00010401'.islower())
  610. self.assertFalse('\U00010427'.islower())
  611. # non-BMP, lowercase
  612. self.assertTrue('\U00010429'.islower())
  613. self.assertTrue('\U0001044E'.islower())
  614. # non-BMP, non-cased
  615. self.assertFalse('\U0001F40D'.islower())
  616. self.assertFalse('\U0001F46F'.islower())
  617. def test_isupper(self):
  618. super().test_isupper()
  619. if not sys.platform.startswith('java'):
  620. self.checkequalnofix(False, '\u1FFc', 'isupper')
  621. self.assertTrue('\u2167'.isupper())
  622. self.assertFalse('\u2177'.isupper())
  623. # non-BMP, uppercase
  624. self.assertTrue('\U00010401'.isupper())
  625. self.assertTrue('\U00010427'.isupper())
  626. # non-BMP, lowercase
  627. self.assertFalse('\U00010429'.isupper())
  628. self.assertFalse('\U0001044E'.isupper())
  629. # non-BMP, non-cased
  630. self.assertFalse('\U0001F40D'.isupper())
  631. self.assertFalse('\U0001F46F'.isupper())
  632. def test_istitle(self):
  633. super().test_istitle()
  634. self.checkequalnofix(True, '\u1FFc', 'istitle')
  635. self.checkequalnofix(True, 'Greek \u1FFcitlecases ...', 'istitle')
  636. # non-BMP, uppercase + lowercase
  637. self.assertTrue('\U00010401\U00010429'.istitle())
  638. self.assertTrue('\U00010427\U0001044E'.istitle())
  639. # apparently there are no titlecased (Lt) non-BMP chars in Unicode 6
  640. for ch in ['\U00010429', '\U0001044E', '\U0001F40D', '\U0001F46F']:
  641. self.assertFalse(ch.istitle(), '{!a} is not title'.format(ch))
  642. def test_isspace(self):
  643. super().test_isspace()
  644. self.checkequalnofix(True, '\u2000', 'isspace')
  645. self.checkequalnofix(True, '\u200a', 'isspace')
  646. self.checkequalnofix(False, '\u2014', 'isspace')
  647. # There are no non-BMP whitespace chars as of Unicode 12.
  648. for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
  649. '\U0001F40D', '\U0001F46F']:
  650. self.assertFalse(ch.isspace(), '{!a} is not space.'.format(ch))
  651. @support.requires_resource('cpu')
  652. def test_isspace_invariant(self):
  653. for codepoint in range(sys.maxunicode + 1):
  654. char = chr(codepoint)
  655. bidirectional = unicodedata.bidirectional(char)
  656. category = unicodedata.category(char)
  657. self.assertEqual(char.isspace(),
  658. (bidirectional in ('WS', 'B', 'S')
  659. or category == 'Zs'))
  660. def test_isalnum(self):
  661. super().test_isalnum()
  662. for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
  663. '\U0001D7F6', '\U00011066', '\U000104A0', '\U0001F107']:
  664. self.assertTrue(ch.isalnum(), '{!a} is alnum.'.format(ch))
  665. def test_isalpha(self):
  666. super().test_isalpha()
  667. self.checkequalnofix(True, '\u1FFc', 'isalpha')
  668. # non-BMP, cased
  669. self.assertTrue('\U00010401'.isalpha())
  670. self.assertTrue('\U00010427'.isalpha())
  671. self.assertTrue('\U00010429'.isalpha())
  672. self.assertTrue('\U0001044E'.isalpha())
  673. # non-BMP, non-cased
  674. self.assertFalse('\U0001F40D'.isalpha())
  675. self.assertFalse('\U0001F46F'.isalpha())
  676. def test_isascii(self):
  677. super().test_isascii()
  678. self.assertFalse("\u20ac".isascii())
  679. self.assertFalse("\U0010ffff".isascii())
  680. def test_isdecimal(self):
  681. self.checkequalnofix(False, '', 'isdecimal')
  682. self.checkequalnofix(False, 'a', 'isdecimal')
  683. self.checkequalnofix(True, '0', 'isdecimal')
  684. self.checkequalnofix(False, '\u2460', 'isdecimal') # CIRCLED DIGIT ONE
  685. self.checkequalnofix(False, '\xbc', 'isdecimal') # VULGAR FRACTION ONE QUARTER
  686. self.checkequalnofix(True, '\u0660', 'isdecimal') # ARABIC-INDIC DIGIT ZERO
  687. self.checkequalnofix(True, '0123456789', 'isdecimal')
  688. self.checkequalnofix(False, '0123456789a', 'isdecimal')
  689. self.checkraises(TypeError, 'abc', 'isdecimal', 42)
  690. for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
  691. '\U0001F40D', '\U0001F46F', '\U00011065', '\U0001F107']:
  692. self.assertFalse(ch.isdecimal(), '{!a} is not decimal.'.format(ch))
  693. for ch in ['\U0001D7F6', '\U00011066', '\U000104A0']:
  694. self.assertTrue(ch.isdecimal(), '{!a} is decimal.'.format(ch))
  695. def test_isdigit(self):
  696. super().test_isdigit()
  697. self.checkequalnofix(True, '\u2460', 'isdigit')
  698. self.checkequalnofix(False, '\xbc', 'isdigit')
  699. self.checkequalnofix(True, '\u0660', 'isdigit')
  700. for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
  701. '\U0001F40D', '\U0001F46F', '\U00011065']:
  702. self.assertFalse(ch.isdigit(), '{!a} is not a digit.'.format(ch))
  703. for ch in ['\U0001D7F6', '\U00011066', '\U000104A0', '\U0001F107']:
  704. self.assertTrue(ch.isdigit(), '{!a} is a digit.'.format(ch))
  705. def test_isnumeric(self):
  706. self.checkequalnofix(False, '', 'isnumeric')
  707. self.checkequalnofix(False, 'a', 'isnumeric')
  708. self.checkequalnofix(True, '0', 'isnumeric')
  709. self.checkequalnofix(True, '\u2460', 'isnumeric')
  710. self.checkequalnofix(True, '\xbc', 'isnumeric')
  711. self.checkequalnofix(True, '\u0660', 'isnumeric')
  712. self.checkequalnofix(True, '0123456789', 'isnumeric')
  713. self.checkequalnofix(False, '0123456789a', 'isnumeric')
  714. self.assertRaises(TypeError, "abc".isnumeric, 42)
  715. for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
  716. '\U0001F40D', '\U0001F46F']:
  717. self.assertFalse(ch.isnumeric(), '{!a} is not numeric.'.format(ch))
  718. for ch in ['\U00011065', '\U0001D7F6', '\U00011066',
  719. '\U000104A0', '\U0001F107']:
  720. self.assertTrue(ch.isnumeric(), '{!a} is numeric.'.format(ch))
  721. def test_isidentifier(self):
  722. self.assertTrue("a".isidentifier())
  723. self.assertTrue("Z".isidentifier())
  724. self.assertTrue("_".isidentifier())
  725. self.assertTrue("b0".isidentifier())
  726. self.assertTrue("bc".isidentifier())
  727. self.assertTrue("b_".isidentifier())
  728. self.assertTrue("µ".isidentifier())
  729. self.assertTrue("𝔘𝔫𝔦𝔠𝔬𝔡𝔢".isidentifier())
  730. self.assertFalse(" ".isidentifier())
  731. self.assertFalse("[".isidentifier())
  732. self.assertFalse("©".isidentifier())
  733. self.assertFalse("0".isidentifier())
  734. @support.cpython_only
  735. @support.requires_legacy_unicode_capi
  736. @unittest.skipIf(_testcapi is None, 'need _testcapi module')
  737. def test_isidentifier_legacy(self):
  738. u = '𝖀𝖓𝖎𝖈𝖔𝖉𝖊'
  739. self.assertTrue(u.isidentifier())
  740. with warnings_helper.check_warnings():
  741. warnings.simplefilter('ignore', DeprecationWarning)
  742. self.assertTrue(_testcapi.unicode_legacy_string(u).isidentifier())
  743. def test_isprintable(self):
  744. self.assertTrue("".isprintable())
  745. self.assertTrue(" ".isprintable())
  746. self.assertTrue("abcdefg".isprintable())
  747. self.assertFalse("abcdefg\n".isprintable())
  748. # some defined Unicode character
  749. self.assertTrue("\u0374".isprintable())
  750. # undefined character
  751. self.assertFalse("\u0378".isprintable())
  752. # single surrogate character
  753. self.assertFalse("\ud800".isprintable())
  754. self.assertTrue('\U0001F46F'.isprintable())
  755. self.assertFalse('\U000E0020'.isprintable())
  756. def test_surrogates(self):
  757. for s in ('a\uD800b\uDFFF', 'a\uDFFFb\uD800',
  758. 'a\uD800b\uDFFFa', 'a\uDFFFb\uD800a'):
  759. self.assertTrue(s.islower())
  760. self.assertFalse(s.isupper())
  761. self.assertFalse(s.istitle())
  762. for s in ('A\uD800B\uDFFF', 'A\uDFFFB\uD800',
  763. 'A\uD800B\uDFFFA', 'A\uDFFFB\uD800A'):
  764. self.assertFalse(s.islower())
  765. self.assertTrue(s.isupper())
  766. self.assertTrue(s.istitle())
  767. for meth_name in ('islower', 'isupper', 'istitle'):
  768. meth = getattr(str, meth_name)
  769. for s in ('\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF'):
  770. self.assertFalse(meth(s), '%a.%s() is False' % (s, meth_name))
  771. for meth_name in ('isalpha', 'isalnum', 'isdigit', 'isspace',
  772. 'isdecimal', 'isnumeric',
  773. 'isidentifier', 'isprintable'):
  774. meth = getattr(str, meth_name)
  775. for s in ('\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF',
  776. 'a\uD800b\uDFFF', 'a\uDFFFb\uD800',
  777. 'a\uD800b\uDFFFa', 'a\uDFFFb\uD800a'):
  778. self.assertFalse(meth(s), '%a.%s() is False' % (s, meth_name))
  779. def test_lower(self):
  780. string_tests.CommonTest.test_lower(self)
  781. self.assertEqual('\U00010427'.lower(), '\U0001044F')
  782. self.assertEqual('\U00010427\U00010427'.lower(),
  783. '\U0001044F\U0001044F')
  784. self.assertEqual('\U00010427\U0001044F'.lower(),
  785. '\U0001044F\U0001044F')
  786. self.assertEqual('X\U00010427x\U0001044F'.lower(),
  787. 'x\U0001044Fx\U0001044F')
  788. self.assertEqual('fi'.lower(), 'fi')
  789. self.assertEqual('\u0130'.lower(), '\u0069\u0307')
  790. # Special case for GREEK CAPITAL LETTER SIGMA U+03A3
  791. self.assertEqual('\u03a3'.lower(), '\u03c3')
  792. self.assertEqual('\u0345\u03a3'.lower(), '\u0345\u03c3')
  793. self.assertEqual('A\u0345\u03a3'.lower(), 'a\u0345\u03c2')
  794. self.assertEqual('A\u0345\u03a3a'.lower(), 'a\u0345\u03c3a')
  795. self.assertEqual('A\u0345\u03a3'.lower(), 'a\u0345\u03c2')
  796. self.assertEqual('A\u03a3\u0345'.lower(), 'a\u03c2\u0345')
  797. self.assertEqual('\u03a3\u0345 '.lower(), '\u03c3\u0345 ')
  798. self.assertEqual('\U0008fffe'.lower(), '\U0008fffe')
  799. self.assertEqual('\u2177'.lower(), '\u2177')
  800. def test_casefold(self):
  801. self.assertEqual('hello'.casefold(), 'hello')
  802. self.assertEqual('hELlo'.casefold(), 'hello')
  803. self.assertEqual('ß'.casefold(), 'ss')
  804. self.assertEqual('fi'.casefold(), 'fi')
  805. self.assertEqual('\u03a3'.casefold(), '\u03c3')
  806. self.assertEqual('A\u0345\u03a3'.casefold(), 'a\u03b9\u03c3')
  807. self.assertEqual('\u00b5'.casefold(), '\u03bc')
  808. def test_upper(self):
  809. string_tests.CommonTest.test_upper(self)
  810. self.assertEqual('\U0001044F'.upper(), '\U00010427')
  811. self.assertEqual('\U0001044F\U0001044F'.upper(),
  812. '\U00010427\U00010427')
  813. self.assertEqual('\U00010427\U0001044F'.upper(),
  814. '\U00010427\U00010427')
  815. self.assertEqual('X\U00010427x\U0001044F'.upper(),
  816. 'X\U00010427X\U00010427')
  817. self.assertEqual('fi'.upper(), 'FI')
  818. self.assertEqual('\u0130'.upper(), '\u0130')
  819. self.assertEqual('\u03a3'.upper(), '\u03a3')
  820. self.assertEqual('ß'.upper(), 'SS')
  821. self.assertEqual('\u1fd2'.upper(), '\u0399\u0308\u0300')
  822. self.assertEqual('\U0008fffe'.upper(), '\U0008fffe')
  823. self.assertEqual('\u2177'.upper(), '\u2167')
  824. def test_capitalize(self):
  825. string_tests.CommonTest.test_capitalize(self)
  826. self.assertEqual('\U0001044F'.capitalize(), '\U00010427')
  827. self.assertEqual('\U0001044F\U0001044F'.capitalize(),
  828. '\U00010427\U0001044F')
  829. self.assertEqual('\U00010427\U0001044F'.capitalize(),
  830. '\U00010427\U0001044F')
  831. self.assertEqual('\U0001044F\U00010427'.capitalize(),
  832. '\U00010427\U0001044F')
  833. self.assertEqual('X\U00010427x\U0001044F'.capitalize(),
  834. 'X\U0001044Fx\U0001044F')
  835. self.assertEqual('h\u0130'.capitalize(), 'H\u0069\u0307')
  836. exp = '\u0399\u0308\u0300\u0069\u0307'
  837. self.assertEqual('\u1fd2\u0130'.capitalize(), exp)
  838. self.assertEqual('finnish'.capitalize(), 'Finnish')
  839. self.assertEqual('A\u0345\u03a3'.capitalize(), 'A\u0345\u03c2')
  840. def test_title(self):
  841. super().test_title()
  842. self.assertEqual('\U0001044F'.title(), '\U00010427')
  843. self.assertEqual('\U0001044F\U0001044F'.title(),
  844. '\U00010427\U0001044F')
  845. self.assertEqual('\U0001044F\U0001044F \U0001044F\U0001044F'.title(),
  846. '\U00010427\U0001044F \U00010427\U0001044F')
  847. self.assertEqual('\U00010427\U0001044F \U00010427\U0001044F'.title(),
  848. '\U00010427\U0001044F \U00010427\U0001044F')
  849. self.assertEqual('\U0001044F\U00010427 \U0001044F\U00010427'.title(),
  850. '\U00010427\U0001044F \U00010427\U0001044F')
  851. self.assertEqual('X\U00010427x\U0001044F X\U00010427x\U0001044F'.title(),
  852. 'X\U0001044Fx\U0001044F X\U0001044Fx\U0001044F')
  853. self.assertEqual('fiNNISH'.title(), 'Finnish')
  854. self.assertEqual('A\u03a3 \u1fa1xy'.title(), 'A\u03c2 \u1fa9xy')
  855. self.assertEqual('A\u03a3A'.title(), 'A\u03c3a')
  856. def test_swapcase(self):
  857. string_tests.CommonTest.test_swapcase(self)
  858. self.assertEqual('\U0001044F'.swapcase(), '\U00010427')
  859. self.assertEqual('\U00010427'.swapcase(), '\U0001044F')
  860. self.assertEqual('\U0001044F\U0001044F'.swapcase(),
  861. '\U00010427\U00010427')
  862. self.assertEqual('\U00010427\U0001044F'.swapcase(),
  863. '\U0001044F\U00010427')
  864. self.assertEqual('\U0001044F\U00010427'.swapcase(),
  865. '\U00010427\U0001044F')
  866. self.assertEqual('X\U00010427x\U0001044F'.swapcase(),
  867. 'x\U0001044FX\U00010427')
  868. self.assertEqual('fi'.swapcase(), 'FI')
  869. self.assertEqual('\u0130'.swapcase(), '\u0069\u0307')
  870. # Special case for GREEK CAPITAL LETTER SIGMA U+03A3
  871. self.assertEqual('\u03a3'.swapcase(), '\u03c3')
  872. self.assertEqual('\u0345\u03a3'.swapcase(), '\u0399\u03c3')
  873. self.assertEqual('A\u0345\u03a3'.swapcase(), 'a\u0399\u03c2')
  874. self.assertEqual('A\u0345\u03a3a'.swapcase(), 'a\u0399\u03c3A')
  875. self.assertEqual('A\u0345\u03a3'.swapcase(), 'a\u0399\u03c2')
  876. self.assertEqual('A\u03a3\u0345'.swapcase(), 'a\u03c2\u0399')
  877. self.assertEqual('\u03a3\u0345 '.swapcase(), '\u03c3\u0399 ')
  878. self.assertEqual('\u03a3'.swapcase(), '\u03c3')
  879. self.assertEqual('ß'.swapcase(), 'SS')
  880. self.assertEqual('\u1fd2'.swapcase(), '\u0399\u0308\u0300')
  881. def test_center(self):
  882. string_tests.CommonTest.test_center(self)
  883. self.assertEqual('x'.center(2, '\U0010FFFF'),
  884. 'x\U0010FFFF')
  885. self.assertEqual('x'.center(3, '\U0010FFFF'),
  886. '\U0010FFFFx\U0010FFFF')
  887. self.assertEqual('x'.center(4, '\U0010FFFF'),
  888. '\U0010FFFFx\U0010FFFF\U0010FFFF')
  889. @unittest.skipUnless(sys.maxsize == 2**31 - 1, "requires 32-bit system")
  890. @support.cpython_only
  891. def test_case_operation_overflow(self):
  892. # Issue #22643
  893. size = 2**32//12 + 1
  894. try:
  895. s = "ü" * size
  896. except MemoryError:
  897. self.skipTest('no enough memory (%.0f MiB required)' % (size / 2**20))
  898. try:
  899. self.assertRaises(OverflowError, s.upper)
  900. finally:
  901. del s
  902. def test_contains(self):
  903. # Testing Unicode contains method
  904. self.assertIn('a', 'abdb')
  905. self.assertIn('a', 'bdab')
  906. self.assertIn('a', 'bdaba')
  907. self.assertIn('a', 'bdba')
  908. self.assertNotIn('a', 'bdb')
  909. self.assertIn('a', 'bdba')
  910. self.assertIn('a', ('a',1,None))
  911. self.assertIn('a', (1,None,'a'))
  912. self.assertIn('a', ('a',1,None))
  913. self.assertIn('a', (1,None,'a'))
  914. self.assertNotIn('a', ('x',1,'y'))
  915. self.assertNotIn('a', ('x',1,None))
  916. self.assertNotIn('abcd', 'abcxxxx')
  917. self.assertIn('ab', 'abcd')
  918. self.assertIn('ab', 'abc')
  919. self.assertIn('ab', (1,None,'ab'))
  920. self.assertIn('', 'abc')
  921. self.assertIn('', '')
  922. self.assertIn('', 'abc')
  923. self.assertNotIn('\0', 'abc')
  924. self.assertIn('\0', '\0abc')
  925. self.assertIn('\0', 'abc\0')
  926. self.assertIn('a', '\0abc')
  927. self.assertIn('asdf', 'asdf')
  928. self.assertNotIn('asdf', 'asd')
  929. self.assertNotIn('asdf', '')
  930. self.assertRaises(TypeError, "abc".__contains__)
  931. # test mixed kinds
  932. for fill in ('a', '\u0100', '\U00010300'):
  933. fill *= 9
  934. for delim in ('c', '\u0102', '\U00010302'):
  935. self.assertNotIn(delim, fill)
  936. self.assertIn(delim, fill + delim)
  937. self.assertNotIn(delim * 2, fill)
  938. self.assertIn(delim * 2, fill + delim * 2)
  939. def test_issue18183(self):
  940. '\U00010000\U00100000'.lower()
  941. '\U00010000\U00100000'.casefold()
  942. '\U00010000\U00100000'.upper()
  943. '\U00010000\U00100000'.capitalize()
  944. '\U00010000\U00100000'.title()
  945. '\U00010000\U00100000'.swapcase()
  946. '\U00100000'.center(3, '\U00010000')
  947. '\U00100000'.ljust(3, '\U00010000')
  948. '\U00100000'.rjust(3, '\U00010000')
  949. def test_format(self):
  950. self.assertEqual(''.format(), '')
  951. self.assertEqual('a'.format(), 'a')
  952. self.assertEqual('ab'.format(), 'ab')
  953. self.assertEqual('a{{'.format(), 'a{')
  954. self.assertEqual('a}}'.format(), 'a}')
  955. self.assertEqual('{{b'.format(), '{b')
  956. self.assertEqual('}}b'.format(), '}b')
  957. self.assertEqual('a{{b'.format(), 'a{b')
  958. # examples from the PEP:
  959. import datetime
  960. self.assertEqual("My name is {0}".format('Fred'), "My name is Fred")
  961. self.assertEqual("My name is {0[name]}".format(dict(name='Fred')),
  962. "My name is Fred")
  963. self.assertEqual("My name is {0} :-{{}}".format('Fred'),
  964. "My name is Fred :-{}")
  965. d = datetime.date(2007, 8, 18)
  966. self.assertEqual("The year is {0.year}".format(d),
  967. "The year is 2007")
  968. # classes we'll use for testing
  969. class C:
  970. def __init__(self, x=100):
  971. self._x = x
  972. def __format__(self, spec):
  973. return spec
  974. class D:
  975. def __init__(self, x):
  976. self.x = x
  977. def __format__(self, spec):
  978. return str(self.x)
  979. # class with __str__, but no __format__
  980. class E:
  981. def __init__(self, x):
  982. self.x = x
  983. def __str__(self):
  984. return 'E(' + self.x + ')'
  985. # class with __repr__, but no __format__ or __str__
  986. class F:
  987. def __init__(self, x):
  988. self.x = x
  989. def __repr__(self):
  990. return 'F(' + self.x + ')'
  991. # class with __format__ that forwards to string, for some format_spec's
  992. class G:
  993. def __init__(self, x):
  994. self.x = x
  995. def __str__(self):
  996. return "string is " + self.x
  997. def __format__(self, format_spec):
  998. if format_spec == 'd':
  999. return 'G(' + self.x + ')'
  1000. return object.__format__(self, format_spec)
  1001. class I(datetime.date):
  1002. def __format__(self, format_spec):
  1003. return self.strftime(format_spec)
  1004. class J(int):
  1005. def __format__(self, format_spec):
  1006. return int.__format__(self * 2, format_spec)
  1007. class M:
  1008. def __init__(self, x):
  1009. self.x = x
  1010. def __repr__(self):
  1011. return 'M(' + self.x + ')'
  1012. __str__ = None
  1013. class N:
  1014. def __init__(self, x):
  1015. self.x = x
  1016. def __repr__(self):
  1017. return 'N(' + self.x + ')'
  1018. __format__ = None
  1019. self.assertEqual(''.format(), '')
  1020. self.assertEqual('abc'.format(), 'abc')
  1021. self.assertEqual('{0}'.format('abc'), 'abc')
  1022. self.assertEqual('{0:}'.format('abc'), 'abc')
  1023. # self.assertEqual('{ 0 }'.format('abc'), 'abc')
  1024. self.assertEqual('X{0}'.format('abc'), 'Xabc')
  1025. self.assertEqual('{0}X'.format('abc'), 'abcX')
  1026. self.assertEqual('X{0}Y'.format('abc'), 'XabcY')
  1027. self.assertEqual('{1}'.format(1, 'abc'), 'abc')
  1028. self.assertEqual('X{1}'.format(1, 'abc'), 'Xabc')
  1029. self.assertEqual('{1}X'.format(1, 'abc'), 'abcX')
  1030. self.assertEqual('X{1}Y'.format(1, 'abc'), 'XabcY')
  1031. self.assertEqual('{0}'.format(-15), '-15')
  1032. self.assertEqual('{0}{1}'.format(-15, 'abc'), '-15abc')
  1033. self.assertEqual('{0}X{1}'.format(-15, 'abc'), '-15Xabc')
  1034. self.assertEqual('{{'.format(), '{')
  1035. self.assertEqual('}}'.format(), '}')
  1036. self.assertEqual('{{}}'.format(), '{}')
  1037. self.assertEqual('{{x}}'.format(), '{x}')
  1038. self.assertEqual('{{{0}}}'.format(123), '{123}')
  1039. self.assertEqual('{{{{0}}}}'.format(), '{{0}}')
  1040. self.assertEqual('}}{{'.format(), '}{')
  1041. self.assertEqual('}}x{{'.format(), '}x{')
  1042. # weird field names
  1043. self.assertEqual("{0[foo-bar]}".format({'foo-bar':'baz'}), 'baz')
  1044. self.assertEqual("{0[foo bar]}".format({'foo bar':'baz'}), 'baz')
  1045. self.assertEqual("{0[ ]}".format({' ':3}), '3')
  1046. self.assertEqual('{foo._x}'.format(foo=C(20)), '20')
  1047. self.assertEqual('{1}{0}'.format(D(10), D(20)), '2010')
  1048. self.assertEqual('{0._x.x}'.format(C(D('abc'))), 'abc')
  1049. self.assertEqual('{0[0]}'.format(['abc', 'def']), 'abc')
  1050. self.assertEqual('{0[1]}'.format(['abc', 'def']), 'def')
  1051. self.assertEqual('{0[1][0]}'.format(['abc', ['def']]), 'def')
  1052. self.assertEqual('{0[1][0].x}'.format(['abc', [D('def')]]), 'def')
  1053. # strings
  1054. self.assertEqual('{0:.3s}'.format('abc'), 'abc')
  1055. self.assertEqual('{0:.3s}'.format('ab'), 'ab')
  1056. self.assertEqual('{0:.3s}'.format('abcdef'), 'abc')
  1057. self.assertEqual('{0:.0s}'.format('abcdef'), '')
  1058. self.assertEqual('{0:3.3s}'.format('abc'), 'abc')
  1059. self.assertEqual('{0:2.3s}'.format('abc'), 'abc')
  1060. self.assertEqual('{0:2.2s}'.format('abc'), 'ab')
  1061. self.assertEqual('{0:3.2s}'.format('abc'), 'ab ')
  1062. self.assertEqual('{0:x<0s}'.format('result'), 'result')
  1063. self.assertEqual('{0:x<5s}'.format('result'), 'result')
  1064. self.assertEqual('{0:x<6s}'.format('result'), 'result')
  1065. self.assertEqual('{0:x<7s}'.format('result'), 'resultx')
  1066. self.assertEqual('{0:x<8s}'.format('result'), 'resultxx')
  1067. self.assertEqual('{0: <7s}'.format('result'), 'result ')
  1068. self.assertEqual('{0:<7s}'.format('result'), 'result ')
  1069. self.assertEqual('{0:>7s}'.format('result'), ' result')
  1070. self.assertEqual('{0:>8s}'.format('result'), ' result')
  1071. self.assertEqual('{0:^8s}'.format('result'), ' result ')
  1072. self.assertEqual('{0:^9s}'.format('result'), ' result ')
  1073. self.assertEqual('{0:^10s}'.format('result'), ' result ')
  1074. self.assertEqual('{0:8s}'.format('result'), 'result ')
  1075. self.assertEqual('{0:0s}'.format('result'), 'result')
  1076. self.assertEqual('{0:08s}'.format('result'), 'result00')
  1077. self.assertEqual('{0:<08s}'.format('result'), 'result00')
  1078. self.assertEqual('{0:>08s}'.format('result'), '00result')
  1079. self.assertEqual('{0:^08s}'.format('result'), '0result0')
  1080. self.assertEqual('{0:10000}'.format('a'), 'a' + ' ' * 9999)
  1081. self.assertEqual('{0:10000}'.format(''), ' ' * 10000)
  1082. self.assertEqual('{0:10000000}'.format(''), ' ' * 10000000)
  1083. # issue 12546: use \x00 as a fill character
  1084. self.assertEqual('{0:\x00<6s}'.format('foo'), 'foo\x00\x00\x00')
  1085. self.assertEqual('{0:\x01<6s}'.format('foo'), 'foo\x01\x01\x01')
  1086. self.assertEqual('{0:\x00^6s}'.format('foo'), '\x00foo\x00\x00')
  1087. self.assertEqual('{0:^6s}'.format('foo'), ' foo ')
  1088. self.assertEqual('{0:\x00<6}'.format(3), '3\x00\x00\x00\x00\x00')
  1089. self.assertEqual('{0:\x01<6}'.format(3), '3\x01\x01\x01\x01\x01')
  1090. self.assertEqual('{0:\x00^6}'.format(3), '\x00\x003\x00\x00\x00')
  1091. self.assertEqual('{0:<6}'.format(3), '3 ')
  1092. self.assertEqual('{0:\x00<6}'.format(3.14), '3.14\x00\x00')
  1093. self.assertEqual('{0:\x01<6}'.format(3.14), '3.14\x01\x01')
  1094. self.assertEqual('{0:\x00^6}'.format(3.14), '\x003.14\x00')
  1095. self.assertEqual('{0:^6}'.format(3.14), ' 3.14 ')
  1096. self.assertEqual('{0:\x00<12}'.format(3+2.0j), '(3+2j)\x00\x00\x00\x00\x00\x00')
  1097. self.assertEqual('{0:\x01<12}'.format(3+2.0j), '(3+2j)\x01\x01\x01\x01\x01\x01')
  1098. self.assertEqual('{0:\x00^12}'.format(3+2.0j), '\x00\x00\x00(3+2j)\x00\x00\x00')
  1099. self.assertEqual('{0:^12}'.format(3+2.0j), ' (3+2j) ')
  1100. # format specifiers for user defined type
  1101. self.assertEqual('{0:abc}'.format(C()), 'abc')
  1102. # !r, !s and !a coercions
  1103. self.assertEqual('{0!s}'.format('Hello'), 'Hello')
  1104. self.assertEqual('{0!s:}'.format('Hello'), 'Hello')
  1105. self.assertEqual('{0!s:15}'.format('Hello'), 'Hello ')
  1106. self.assertEqual('{0!s:15s}'.format('Hello'), 'Hello ')
  1107. self.assertEqual('{0!r}'.format('Hello'), "'Hello'")
  1108. self.assertEqual('{0!r:}'.format('Hello'), "'Hello'")
  1109. self.assertEqual('{0!r}'.format(F('Hello')), 'F(Hello)')
  1110. self.assertEqual('{0!r}'.format('\u0378'), "'\\u0378'") # nonprintable
  1111. self.assertEqual('{0!r}'.format('\u0374'), "'\u0374'") # printable
  1112. self.assertEqual('{0!r}'.format(F('\u0374')), 'F(\u0374)')
  1113. self.assertEqual('{0!a}'.format('Hello'), "'Hello'")
  1114. self.assertEqual('{0!a}'.format('\u0378'), "'\\u0378'") # nonprintable
  1115. self.assertEqual('{0!a}'.format('\u0374'), "'\\u0374'") # printable
  1116. self.assertEqual('{0!a:}'.format('Hello'), "'Hello'")
  1117. self.assertEqual('{0!a}'.format(F('Hello')), 'F(Hello)')
  1118. self.assertEqual('{0!a}'.format(F('\u0374')), 'F(\\u0374)')
  1119. # test fallback to object.__format__
  1120. self.assertEqual('{0}'.format({}), '{}')
  1121. self.assertEqual('{0}'.format([]), '[]')
  1122. self.assertEqual('{0}'.format([1]), '[1]')
  1123. self.assertEqual('{0:d}'.format(G('data')), 'G(data)')
  1124. self.assertEqual('{0!s}'.format(G('data')), 'string is data')
  1125. self.assertRaises(TypeError, '{0:^10}'.format, E('data'))
  1126. self.assertRaises(TypeError, '{0:^10s}'.format, E('data'))
  1127. self.assertRaises(TypeError, '{0:>15s}'.format, G('data'))
  1128. self.assertEqual("{0:date: %Y-%m-%d}".format(I(year=2007,
  1129. month=8,
  1130. day=27)),
  1131. "date: 2007-08-27")
  1132. # test deriving from a builtin type and overriding __format__
  1133. self.assertEqual("{0}".format(J(10)), "20")
  1134. # string format specifiers
  1135. self.assertEqual('{0:}'.format('a'), 'a')
  1136. # computed format specifiers
  1137. self.assertEqual("{0:.{1}}".format('hello world', 5), 'hello')
  1138. self.assertEqual("{0:.{1}s}".format('hello world', 5), 'hello')
  1139. self.assertEqual("{0:.{precision}s}".format('hello world', precision=5), 'hello')
  1140. self.assertEqual("{0:{width}.{precision}s}".format('hello world', width=10, precision=5), 'hello ')
  1141. self.assertEqual("{0:{width}.{precision}s}".format('hello world', width='10', precision='5'), 'hello ')
  1142. # test various errors
  1143. self.assertRaises(ValueError, '{'.format)
  1144. self.assertRaises(ValueError, '}'.format)
  1145. self.assertRaises(ValueError, 'a{'.format)
  1146. self.assertRaises(ValueError, 'a}'.format)
  1147. self.assertRaises(ValueError, '{a'.format)
  1148. self.assertRaises(ValueError, '}a'.format)
  1149. self.assertRaises(IndexError, '{0}'.format)
  1150. self.assertRaises(IndexError, '{1}'.format, 'abc')
  1151. self.assertRaises(KeyError, '{x}'.format)
  1152. self.assertRaises(ValueError, "}{".format)
  1153. self.assertRaises(ValueError, "abc{0:{}".format)
  1154. self.assertRaises(ValueError, "{0".format)
  1155. self.assertRaises(IndexError, "{0.}".format)
  1156. self.assertRaises(ValueError, "{0.}".format, 0)
  1157. self.assertRaises(ValueError, "{0[}".format)
  1158. self.assertRaises(ValueError, "{0[}".format, [])
  1159. self.assertRaises(KeyError, "{0]}".format)
  1160. self.assertRaises(ValueError, "{0.[]}".format, 0)
  1161. self.assertRaises(ValueError, "{0..foo}".format, 0)
  1162. self.assertRaises(ValueError, "{0[0}".format, 0)
  1163. self.assertRaises(ValueError, "{0[0:foo}".format, 0)
  1164. self.assertRaises(KeyError, "{c]}".format)
  1165. self.assertRaises(ValueError, "{{ {{{0}}".format, 0)
  1166. self.assertRaises(ValueError, "{0}}".format, 0)
  1167. self.assertRaises(KeyError, "{foo}".format, bar=3)
  1168. self.assertRaises(ValueError, "{0!x}".format, 3)
  1169. self.assertRaises(ValueError, "{0!}".format, 0)
  1170. self.assertRaises(ValueError, "{0!rs}".format, 0)
  1171. self.assertRaises(ValueError, "{!}".format)
  1172. self.assertRaises(IndexError, "{:}".format)
  1173. self.assertRaises(IndexError, "{:s}".format)
  1174. self.assertRaises(IndexError, "{}".format)
  1175. big = "23098475029384702983476098230754973209482573"
  1176. self.assertRaises(ValueError, ("{" + big + "}").format)
  1177. self.assertRaises(ValueError, ("{[" + big + "]}").format, [0])
  1178. # test number formatter errors:
  1179. self.assertRaises(ValueError, '{0:x}'.format, 1j)
  1180. self.assertRaises(ValueError, '{0:x}'.format, 1.0)
  1181. self.assertRaises(ValueError, '{0:X}'.format, 1j)
  1182. self.assertRaises(ValueError, '{0:X}'.format, 1.0)
  1183. self.assertRaises(ValueError, '{0:o}'.format, 1j)
  1184. self.assertRaises(ValueError, '{0:o}'.format, 1.0)
  1185. self.assertRaises(ValueError, '{0:u}'.format, 1j)
  1186. self.assertRaises(ValueError, '{0:u}'.format, 1.0)
  1187. self.assertRaises(ValueError, '{0:i}'.format, 1j)
  1188. self.assertRaises(ValueError, '{0:i}'.format, 1.0)
  1189. self.assertRaises(ValueError, '{0:d}'.format, 1j)
  1190. self.assertRaises(ValueError, '{0:d}'.format, 1.0)
  1191. # issue 6089
  1192. self.assertRaises(ValueError, "{0[0]x}".format, [None])
  1193. self.assertRaises(ValueError, "{0[0](10)}".format, [None])
  1194. # can't have a replacement on the field name portion
  1195. self.assertRaises(TypeError, '{0[{1}]}'.format, 'abcdefg', 4)
  1196. # exceed maximum recursion depth
  1197. self.assertRaises(ValueError, "{0:{1:{2}}}".format, 'abc', 's', '')
  1198. self.assertRaises(ValueError, "{0:{1:{2:{3:{4:{5:{6}}}}}}}".format,
  1199. 0, 1, 2, 3, 4, 5, 6, 7)
  1200. # string format spec errors
  1201. sign_msg = "Sign not allowed in string format specifier"
  1202. self.assertRaisesRegex(ValueError, sign_msg, "{0:-s}".format, '')
  1203. self.assertRaisesRegex(ValueError, sign_msg, format, "", "-")
  1204. space_msg = "Space not allowed in string format specifier"
  1205. self.assertRaisesRegex(ValueError, space_msg, "{: }".format, '')
  1206. self.assertRaises(ValueError, "{0:=s}".format, '')
  1207. # Alternate formatting is not supported
  1208. self.assertRaises(ValueError, format, '', '#')
  1209. self.assertRaises(ValueError, format, '', '#20')
  1210. # Non-ASCII
  1211. self.assertEqual("{0:s}{1:s}".format("ABC", "\u0410\u0411\u0412"),
  1212. 'ABC\u0410\u0411\u0412')
  1213. self.assertEqual("{0:.3s}".format("ABC\u0410\u0411\u0412"),
  1214. 'ABC')
  1215. self.assertEqual("{0:.0s}".format("ABC\u0410\u0411\u0412"),
  1216. '')
  1217. self.assertEqual("{[{}]}".format({"{}": 5}), "5")
  1218. self.assertEqual("{[{}]}".format({"{}" : "a"}), "a")
  1219. self.assertEqual("{[{]}".format({"{" : "a"}), "a")
  1220. self.assertEqual("{[}]}".format({"}" : "a"}), "a")
  1221. self.assertEqual("{[[]}".format({"[" : "a"}), "a")
  1222. self.assertEqual("{[!]}".format({"!" : "a"}), "a")
  1223. self.assertRaises(ValueError, "{a{}b}".format, 42)
  1224. self.assertRaises(ValueError, "{a{b}".format, 42)
  1225. self.assertRaises(ValueError, "{[}".format, 42)
  1226. self.assertEqual("0x{:0{:d}X}".format(0x0,16), "0x0000000000000000")
  1227. # Blocking fallback
  1228. m = M('data')
  1229. self.assertEqual("{!r}".format(m), 'M(data)')
  1230. self.assertRaises(TypeError, "{!s}".format, m)
  1231. self.assertRaises(TypeError, "{}".format, m)
  1232. n = N('data')
  1233. self.assertEqual("{!r}".format(n), 'N(data)')
  1234. self.assertEqual("{!s}".format(n), 'N(data)')
  1235. self.assertRaises(TypeError, "{}".format, n)
  1236. def test_format_map(self):
  1237. self.assertEqual(''.format_map({}), '')
  1238. self.assertEqual('a'.format_map({}), 'a')
  1239. self.assertEqual('ab'.format_map({}), 'ab')
  1240. self.assertEqual('a{{'.format_map({}), 'a{')
  1241. self.assertEqual('a}}'.format_map({}), 'a}')
  1242. self.assertEqual('{{b'.format_map({}), '{b')
  1243. self.assertEqual('}}b'.format_map({}), '}b')
  1244. self.assertEqual('a{{b'.format_map({}), 'a{b')
  1245. # using mappings
  1246. class Mapping(dict):
  1247. def __missing__(self, key):
  1248. return key
  1249. self.assertEqual('{hello}'.format_map(Mapping()), 'hello')
  1250. self.assertEqual('{a} {world}'.format_map(Mapping(a='hello')), 'hello world')
  1251. class InternalMapping:
  1252. def __init__(self):
  1253. self.mapping = {'a': 'hello'}
  1254. def __getitem__(self, key):
  1255. return self.mapping[key]
  1256. self.assertEqual('{a}'.format_map(InternalMapping()), 'hello')
  1257. class C:
  1258. def __init__(self, x=100):
  1259. self._x = x
  1260. def __format__(self, spec):
  1261. return spec
  1262. self.assertEqual('{foo._x}'.format_map({'foo': C(20)}), '20')
  1263. # test various errors
  1264. self.assertRaises(TypeError, ''.format_map)
  1265. self.assertRaises(TypeError, 'a'.format_map)
  1266. self.assertRaises(ValueError, '{'.format_map, {})
  1267. self.assertRaises(ValueError, '}'.format_map, {})
  1268. self.assertRaises(ValueError, 'a{'.format_map, {})
  1269. self.assertRaises(ValueError, 'a}'.format_map, {})
  1270. self.assertRaises(ValueError, '{a'.format_map, {})
  1271. self.assertRaises(ValueError, '}a'.format_map, {})
  1272. # issue #12579: can't supply positional params to format_map
  1273. self.assertRaises(ValueError, '{}'.format_map, {'a' : 2})
  1274. self.assertRaises(ValueError, '{}'.format_map, 'a')
  1275. self.assertRaises(ValueError, '{a} {}'.format_map, {"a" : 2, "b" : 1})
  1276. class BadMapping:
  1277. def __getitem__(self, key):
  1278. return 1/0
  1279. self.assertRaises(KeyError, '{a}'.format_map, {})
  1280. self.assertRaises(TypeError, '{a}'.format_map, [])
  1281. self.assertRaises(ZeroDivisionError, '{a}'.format_map, BadMapping())
  1282. def test_format_huge_precision(self):
  1283. format_string = ".{}f".format(sys.maxsize + 1)
  1284. with self.assertRaises(ValueError):
  1285. result = format(2.34, format_string)
  1286. def test_format_huge_width(self):
  1287. format_string = "{}f".format(sys.maxsize + 1)
  1288. with self.assertRaises(ValueError):
  1289. result = format(2.34, format_string)
  1290. def test_format_huge_item_number(self):
  1291. format_string = "{{{}:.6f}}".format(sys.maxsize + 1)
  1292. with self.assertRaises(ValueError):
  1293. result = format_string.format(2.34)
  1294. def test_format_auto_numbering(self):
  1295. class C:
  1296. def __init__(self, x=100):
  1297. self._x = x
  1298. def __format__(self, spec):
  1299. return spec
  1300. self.assertEqual('{}'.format(10), '10')
  1301. self.assertEqual('{:5}'.format('s'), 's ')
  1302. self.assertEqual('{!r}'.format('s'), "'s'")
  1303. self.assertEqual('{._x}'.format(C(10)), '10')
  1304. self.assertEqual('{[1]}'.format([1, 2]), '2')
  1305. self.assertEqual('{[a]}'.format({'a':4, 'b':2}), '4')
  1306. self.assertEqual('a{}b{}c'.format(0, 1), 'a0b1c')
  1307. self.assertEqual('a{:{}}b'.format('x', '^10'), 'a x b')
  1308. self.assertEqual('a{:{}x}b'.format(20, '#'), 'a0x14b')
  1309. # can't mix and match numbering and auto-numbering
  1310. self.assertRaises(ValueError, '{}{1}'.format, 1, 2)
  1311. self.assertRaises(ValueError, '{1}{}'.format, 1, 2)
  1312. self.assertRaises(ValueError, '{:{1}}'.format, 1, 2)
  1313. self.assertRaises(ValueError, '{0:{}}'.format, 1, 2)
  1314. # can mix and match auto-numbering and named
  1315. self.assertEqual('{f}{}'.format(4, f='test'), 'test4')
  1316. self.assertEqual('{}{f}'.format(4, f='test'), '4test')
  1317. self.assertEqual('{:{f}}{g}{}'.format(1, 3, g='g', f=2), ' 1g3')
  1318. self.assertEqual('{f:{}}{}{g}'.format(2, 4, f=1, g='g'), ' 14g')
  1319. def test_formatting(self):
  1320. string_tests.MixinStrUnicodeUserStringTest.test_formatting(self)
  1321. # Testing Unicode formatting strings...
  1322. self.assertEqual("%s, %s" % ("abc", "abc"), 'abc, abc')
  1323. self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", 1, 2, 3), 'abc, abc, 1, 2.000000, 3.00')
  1324. self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", 1, -2, 3), 'abc, abc, 1, -2.000000, 3.00')
  1325. self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 3.5), 'abc, abc, -1, -2.000000, 3.50')
  1326. self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 3.57), 'abc, abc, -1, -2.000000, 3.57')
  1327. self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 1003.57), 'abc, abc, -1, -2.000000, 1003.57')
  1328. if not sys.platform.startswith('java'):
  1329. self.assertEqual("%r, %r" % (b"abc", "abc"), "b'abc', 'abc'")
  1330. self.assertEqual("%r" % ("\u1234",), "'\u1234'")
  1331. self.assertEqual("%a" % ("\u1234",), "'\\u1234'")
  1332. self.assertEqual("%(x)s, %(y)s" % {'x':"abc", 'y':"def"}, 'abc, def')
  1333. self.assertEqual("%(x)s, %(\xfc)s" % {'x':"abc", '\xfc':"def"}, 'abc, def')
  1334. self.assertEqual('%c' % 0x1234, '\u1234')
  1335. self.assertEqual('%c' % 0x21483, '\U00021483')
  1336. self.assertRaises(OverflowError, "%c".__mod__, (0x110000,))
  1337. self.assertEqual('%c' % '\U00021483', '\U00021483')
  1338. self.assertRaises(TypeError, "%c".__mod__, "aa")
  1339. self.assertRaises(ValueError, "%.1\u1032f".__mod__, (1.0/3))
  1340. self.assertRaises(TypeError, "%i".__mod__, "aa")
  1341. # formatting jobs delegated from the string implementation:
  1342. self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
  1343. self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
  1344. self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
  1345. self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
  1346. self.assertEqual('...%(foo)s...' % {'foo':"abc",'def':123}, '...abc...')
  1347. self.assertEqual('...%(foo)s...' % {'foo':"abc",'def':123}, '...abc...')
  1348. self.assertEqual('...%s...%s...%s...%s...' % (1,2,3,"abc"), '...1...2...3...abc...')
  1349. self.assertEqual('...%%...%%s...%s...%s...%s...%s...' % (1,2,3,"abc"), '...%...%s...1...2...3...abc...')
  1350. self.assertEqual('...%s...' % "abc", '...abc...')
  1351. self.assertEqual('%*s' % (5,'abc',), ' abc')
  1352. self.assertEqual('%*s' % (-5,'abc',), 'abc ')
  1353. self.assertEqual('%*.*s' % (5,2,'abc',), ' ab')
  1354. self.assertEqual('%*.*s' % (5,3,'abc',), ' abc')
  1355. self.assertEqual('%i %*.*s' % (10, 5,3,'abc',), '10 abc')
  1356. self.assertEqual('%i%s %*.*s' % (10, 3, 5, 3, 'abc',), '103 abc')
  1357. self.assertEqual('%c' % 'a', 'a')
  1358. class Wrapper:
  1359. def __str__(self):
  1360. return '\u1234'
  1361. self.assertEqual('%s' % Wrapper(), '\u1234')
  1362. # issue 3382
  1363. NAN = float('nan')
  1364. INF = float('inf')
  1365. self.assertEqual('%f' % NAN, 'nan')
  1366. self.assertEqual('%F' % NAN, 'NAN')
  1367. self.assertEqual('%f' % INF, 'inf')
  1368. self.assertEqual('%F' % INF, 'INF')
  1369. # PEP 393
  1370. self.assertEqual('%.1s' % "a\xe9\u20ac", 'a')
  1371. self.assertEqual('%.2s' % "a\xe9\u20ac", 'a\xe9')
  1372. #issue 19995
  1373. class PseudoInt:
  1374. def __init__(self, value):
  1375. self.value = int(value)
  1376. def __int__(self):
  1377. return self.value
  1378. def __index__(self):
  1379. return self.value
  1380. class PseudoFloat:
  1381. def __init__(self, value):
  1382. self.value = float(value)
  1383. def __int__(self):
  1384. return int(self.value)
  1385. pi = PseudoFloat(3.1415)
  1386. letter_m = PseudoInt(109)
  1387. self.assertEqual('%x' % 42, '2a')
  1388. self.assertEqual('%X' % 15, 'F')
  1389. self.assertEqual('%o' % 9, '11')
  1390. self.assertEqual('%c' % 109, 'm')
  1391. self.assertEqual('%x' % letter_m, '6d')
  1392. self.assertEqual('%X' % letter_m, '6D')
  1393. self.assertEqual('%o' % letter_m, '155')
  1394. self.assertEqual('%c' % letter_m, 'm')
  1395. self.assertRaisesRegex(TypeError, '%x format: an integer is required, not float', operator.mod, '%x', 3.14)
  1396. self.assertRaisesRegex(TypeError, '%X format: an integer is required, not float', operator.mod, '%X', 2.11)
  1397. self.assertRaisesRegex(TypeError, '%o format: an integer is required, not float', operator.mod, '%o', 1.79)
  1398. self.assertRaisesRegex(TypeError, '%x format: an integer is required, not PseudoFloat', operator.mod, '%x', pi)
  1399. self.assertRaisesRegex(TypeError, '%x format: an integer is required, not complex', operator.mod, '%x', 3j)
  1400. self.assertRaisesRegex(TypeError, '%X format: an integer is required, not complex', operator.mod, '%X', 2j)
  1401. self.assertRaisesRegex(TypeError, '%o format: an integer is required, not complex', operator.mod, '%o', 1j)
  1402. self.assertRaisesRegex(TypeError, '%u format: a real number is required, not complex', operator.mod, '%u', 3j)
  1403. self.assertRaisesRegex(TypeError, '%i format: a real number is required, not complex', operator.mod, '%i', 2j)
  1404. self.assertRaisesRegex(TypeError, '%d format: a real number is required, not complex', operator.mod, '%d', 1j)
  1405. self.assertRaisesRegex(TypeError, '%c requires int or char', operator.mod, '%c', pi)
  1406. class RaisingNumber:
  1407. def __int__(self):
  1408. raise RuntimeError('int') # should not be `TypeError`
  1409. def __index__(self):
  1410. raise RuntimeError('index') # should not be `TypeError`
  1411. rn = RaisingNumber()
  1412. self.assertRaisesRegex(RuntimeError, 'int', operator.mod, '%d', rn)
  1413. self.assertRaisesRegex(RuntimeError, 'int', operator.mod, '%i', rn)
  1414. self.assertRaisesRegex(RuntimeError, 'int', operator.mod, '%u', rn)
  1415. self.assertRaisesRegex(RuntimeError, 'index', operator.mod, '%x', rn)
  1416. self.assertRaisesRegex(RuntimeError, 'index', operator.mod, '%X', rn)
  1417. self.assertRaisesRegex(RuntimeError, 'index', operator.mod, '%o', rn)
  1418. def test_formatting_with_enum(self):
  1419. # issue18780
  1420. import enum
  1421. class Float(float, enum.Enum):
  1422. # a mixed-in type will use the name for %s etc.
  1423. PI = 3.1415926
  1424. class Int(enum.IntEnum):
  1425. # IntEnum uses the value and not the name for %s etc.
  1426. IDES = 15
  1427. class Str(enum.StrEnum):
  1428. # StrEnum uses the value and not the name for %s etc.
  1429. ABC = 'abc'
  1430. # Testing Unicode formatting strings...
  1431. self.assertEqual("%s, %s" % (Str.ABC, Str.ABC),
  1432. 'abc, abc')
  1433. self.assertEqual("%s, %s, %d, %i, %u, %f, %5.2f" %
  1434. (Str.ABC, Str.ABC,
  1435. Int.IDES, Int.IDES, Int.IDES,
  1436. Float.PI, Float.PI),
  1437. 'abc, abc, 15, 15, 15, 3.141593, 3.14')
  1438. # formatting jobs delegated from the string implementation:
  1439. self.assertEqual('...%(foo)s...' % {'foo':Str.ABC},
  1440. '...abc...')
  1441. self.assertEqual('...%(foo)r...' % {'foo':Int.IDES},
  1442. '...<Int.IDES: 15>...')
  1443. self.assertEqual('...%(foo)s...' % {'foo':Int.IDES},
  1444. '...15...')
  1445. self.assertEqual('...%(foo)i...' % {'foo':Int.IDES},
  1446. '...15...')
  1447. self.assertEqual('...%(foo)d...' % {'foo':Int.IDES},
  1448. '...15...')
  1449. self.assertEqual('...%(foo)u...' % {'foo':Int.IDES, 'def':Float.PI},
  1450. '...15...')
  1451. self.assertEqual('...%(foo)f...' % {'foo':Float.PI,'def':123},
  1452. '...3.141593...')
  1453. def test_formatting_huge_precision(self):
  1454. format_string = "%.{}f".format(sys.maxsize + 1)
  1455. with self.assertRaises(ValueError):
  1456. result = format_string % 2.34
  1457. def test_issue28598_strsubclass_rhs(self):
  1458. # A subclass of str with an __rmod__ method should be able to hook
  1459. # into the % operator
  1460. class SubclassedStr(str):
  1461. def __rmod__(self, other):
  1462. return 'Success, self.__rmod__({!r}) was called'.format(other)
  1463. self.assertEqual('lhs %% %r' % SubclassedStr('rhs'),
  1464. "Success, self.__rmod__('lhs %% %r') was called")
  1465. @support.cpython_only
  1466. @unittest.skipIf(_testcapi is None, 'need _testcapi module')
  1467. def test_formatting_huge_precision_c_limits(self):
  1468. format_string = "%.{}f".format(_testcapi.INT_MAX + 1)
  1469. with self.assertRaises(ValueError):
  1470. result = format_string % 2.34
  1471. def test_formatting_huge_width(self):
  1472. format_string = "%{}f".format(sys.maxsize + 1)
  1473. with self.assertRaises(ValueError):
  1474. result = format_string % 2.34
  1475. def test_startswith_endswith_errors(self):
  1476. for meth in ('foo'.startswith, 'foo'.endswith):
  1477. with self.assertRaises(TypeError) as cm:
  1478. meth(['f'])
  1479. exc = str(cm.exception)
  1480. self.assertIn('str', exc)
  1481. self.assertIn('tuple', exc)
  1482. @support.run_with_locale('LC_ALL', 'de_DE', 'fr_FR')
  1483. def test_format_float(self):
  1484. # should not format with a comma, but always with C locale
  1485. self.assertEqual('1.0', '%.1f' % 1.0)
  1486. def test_constructor(self):
  1487. # unicode(obj) tests (this maps to PyObject_Unicode() at C level)
  1488. self.assertEqual(
  1489. str('unicode remains unicode'),
  1490. 'unicode remains unicode'
  1491. )
  1492. for text in ('ascii', '\xe9', '\u20ac', '\U0010FFFF'):
  1493. subclass = StrSubclass(text)
  1494. self.assertEqual(str(subclass), text)
  1495. self.assertEqual(len(subclass), len(text))
  1496. if text == 'ascii':
  1497. self.assertEqual(subclass.encode('ascii'), b'ascii')
  1498. self.assertEqual(subclass.encode('utf-8'), b'ascii')
  1499. self.assertEqual(
  1500. str('strings are converted to unicode'),
  1501. 'strings are converted to unicode'
  1502. )
  1503. class StringCompat:
  1504. def __init__(self, x):
  1505. self.x = x
  1506. def __str__(self):
  1507. return self.x
  1508. self.assertEqual(
  1509. str(StringCompat('__str__ compatible objects are recognized')),
  1510. '__str__ compatible objects are recognized'
  1511. )
  1512. # unicode(obj) is compatible to str():
  1513. o = StringCompat('unicode(obj) is compatible to str()')
  1514. self.assertEqual(str(o), 'unicode(obj) is compatible to str()')
  1515. self.assertEqual(str(o), 'unicode(obj) is compatible to str()')
  1516. for obj in (123, 123.45, 123):
  1517. self.assertEqual(str(obj), str(str(obj)))
  1518. # unicode(obj, encoding, error) tests (this maps to
  1519. # PyUnicode_FromEncodedObject() at C level)
  1520. if not sys.platform.startswith('java'):
  1521. self.assertRaises(
  1522. TypeError,
  1523. str,
  1524. 'decoding unicode is not supported',
  1525. 'utf-8',
  1526. 'strict'
  1527. )
  1528. self.assertEqual(
  1529. str(b'strings are decoded to unicode', 'utf-8', 'strict'),
  1530. 'strings are decoded to unicode'
  1531. )
  1532. if not sys.platform.startswith('java'):
  1533. self.assertEqual(
  1534. str(
  1535. memoryview(b'character buffers are decoded to unicode'),
  1536. 'utf-8',
  1537. 'strict'
  1538. ),
  1539. 'character buffers are decoded to unicode'
  1540. )
  1541. self.assertRaises(TypeError, str, 42, 42, 42)
  1542. def test_constructor_keyword_args(self):
  1543. """Pass various keyword argument combinations to the constructor."""
  1544. # The object argument can be passed as a keyword.
  1545. self.assertEqual(str(object='foo'), 'foo')
  1546. self.assertEqual(str(object=b'foo', encoding='utf-8'), 'foo')
  1547. # The errors argument without encoding triggers "decode" mode.
  1548. self.assertEqual(str(b'foo', errors='strict'), 'foo') # not "b'foo'"
  1549. self.assertEqual(str(object=b'foo', errors='strict'), 'foo')
  1550. def test_constructor_defaults(self):
  1551. """Check the constructor argument defaults."""
  1552. # The object argument defaults to '' or b''.
  1553. self.assertEqual(str(), '')
  1554. self.assertEqual(str(errors='strict'), '')
  1555. utf8_cent = '¢'.encode('utf-8')
  1556. # The encoding argument defaults to utf-8.
  1557. self.assertEqual(str(utf8_cent, errors='strict'), '¢')
  1558. # The errors argument defaults to strict.
  1559. self.assertRaises(UnicodeDecodeError, str, utf8_cent, encoding='ascii')
  1560. def test_codecs_utf7(self):
  1561. utfTests = [
  1562. ('A\u2262\u0391.', b'A+ImIDkQ.'), # RFC2152 example
  1563. ('Hi Mom -\u263a-!', b'Hi Mom -+Jjo--!'), # RFC2152 example
  1564. ('\u65E5\u672C\u8A9E', b'+ZeVnLIqe-'), # RFC2152 example
  1565. ('Item 3 is \u00a31.', b'Item 3 is +AKM-1.'), # RFC2152 example
  1566. ('+', b'+-'),
  1567. ('+-', b'+--'),
  1568. ('+?', b'+-?'),
  1569. (r'\?', b'+AFw?'),
  1570. ('+?', b'+-?'),
  1571. (r'\\?', b'+AFwAXA?'),
  1572. (r'\\\?', b'+AFwAXABc?'),
  1573. (r'++--', b'+-+---'),
  1574. ('\U000abcde', b'+2m/c3g-'), # surrogate pairs
  1575. ('/', b'/'),
  1576. ]
  1577. for (x, y) in utfTests:
  1578. self.assertEqual(x.encode('utf-7'), y)
  1579. # Unpaired surrogates are passed through
  1580. self.assertEqual('\uD801'.encode('utf-7'), b'+2AE-')
  1581. self.assertEqual('\uD801x'.encode('utf-7'), b'+2AE-x')
  1582. self.assertEqual('\uDC01'.encode('utf-7'), b'+3AE-')
  1583. self.assertEqual('\uDC01x'.encode('utf-7'), b'+3AE-x')
  1584. self.assertEqual(b'+2AE-'.decode('utf-7'), '\uD801')
  1585. self.assertEqual(b'+2AE-x'.decode('utf-7'), '\uD801x')
  1586. self.assertEqual(b'+3AE-'.decode('utf-7'), '\uDC01')
  1587. self.assertEqual(b'+3AE-x'.decode('utf-7'), '\uDC01x')
  1588. self.assertEqual('\uD801\U000abcde'.encode('utf-7'), b'+2AHab9ze-')
  1589. self.assertEqual(b'+2AHab9ze-'.decode('utf-7'), '\uD801\U000abcde')
  1590. # Issue #2242: crash on some Windows/MSVC versions
  1591. self.assertEqual(b'+\xc1'.decode('utf-7', 'ignore'), '')
  1592. # Direct encoded characters
  1593. set_d = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'(),-./:?"
  1594. # Optional direct characters
  1595. set_o = '!"#$%&*;<=>@[]^_`{|}'
  1596. for c in set_d:
  1597. self.assertEqual(c.encode('utf7'), c.encode('ascii'))
  1598. self.assertEqual(c.encode('ascii').decode('utf7'), c)
  1599. for c in set_o:
  1600. self.assertEqual(c.encode('ascii').decode('utf7'), c)
  1601. with self.assertRaisesRegex(UnicodeDecodeError,
  1602. 'ill-formed sequence'):
  1603. b'+@'.decode('utf-7')
  1604. def test_codecs_utf8(self):
  1605. self.assertEqual(''.encode('utf-8'), b'')
  1606. self.assertEqual('\u20ac'.encode('utf-8'), b'\xe2\x82\xac')
  1607. self.assertEqual('\U00010002'.encode('utf-8'), b'\xf0\x90\x80\x82')
  1608. self.assertEqual('\U00023456'.encode('utf-8'), b'\xf0\xa3\x91\x96')
  1609. self.assertEqual('\ud800'.encode('utf-8', 'surrogatepass'), b'\xed\xa0\x80')
  1610. self.assertEqual('\udc00'.encode('utf-8', 'surrogatepass'), b'\xed\xb0\x80')
  1611. self.assertEqual(('\U00010002'*10).encode('utf-8'),
  1612. b'\xf0\x90\x80\x82'*10)
  1613. self.assertEqual(
  1614. '\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f'
  1615. '\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00'
  1616. '\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c'
  1617. '\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067'
  1618. '\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das'
  1619. ' Nunstuck git und'.encode('utf-8'),
  1620. b'\xe6\xad\xa3\xe7\xa2\xba\xe3\x81\xab\xe8\xa8\x80\xe3\x81'
  1621. b'\x86\xe3\x81\xa8\xe7\xbf\xbb\xe8\xa8\xb3\xe3\x81\xaf\xe3'
  1622. b'\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x81\xbe'
  1623. b'\xe3\x81\x9b\xe3\x82\x93\xe3\x80\x82\xe4\xb8\x80\xe9\x83'
  1624. b'\xa8\xe3\x81\xaf\xe3\x83\x89\xe3\x82\xa4\xe3\x83\x84\xe8'
  1625. b'\xaa\x9e\xe3\x81\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81'
  1626. b'\xe3\x81\x82\xe3\x81\xa8\xe3\x81\xaf\xe3\x81\xa7\xe3\x81'
  1627. b'\x9f\xe3\x82\x89\xe3\x82\x81\xe3\x81\xa7\xe3\x81\x99\xe3'
  1628. b'\x80\x82\xe5\xae\x9f\xe9\x9a\x9b\xe3\x81\xab\xe3\x81\xaf'
  1629. b'\xe3\x80\x8cWenn ist das Nunstuck git und'
  1630. )
  1631. # UTF-8 specific decoding tests
  1632. self.assertEqual(str(b'\xf0\xa3\x91\x96', 'utf-8'), '\U00023456' )
  1633. self.assertEqual(str(b'\xf0\x90\x80\x82', 'utf-8'), '\U00010002' )
  1634. self.assertEqual(str(b'\xe2\x82\xac', 'utf-8'), '\u20ac' )
  1635. # Other possible utf-8 test cases:
  1636. # * strict decoding testing for all of the
  1637. # UTF8_ERROR cases in PyUnicode_DecodeUTF8
  1638. def test_utf8_decode_valid_sequences(self):
  1639. sequences = [
  1640. # single byte
  1641. (b'\x00', '\x00'), (b'a', 'a'), (b'\x7f', '\x7f'),
  1642. # 2 bytes
  1643. (b'\xc2\x80', '\x80'), (b'\xdf\xbf', '\u07ff'),
  1644. # 3 bytes
  1645. (b'\xe0\xa0\x80', '\u0800'), (b'\xed\x9f\xbf', '\ud7ff'),
  1646. (b'\xee\x80\x80', '\uE000'), (b'\xef\xbf\xbf', '\uffff'),
  1647. # 4 bytes
  1648. (b'\xF0\x90\x80\x80', '\U00010000'),
  1649. (b'\xf4\x8f\xbf\xbf', '\U0010FFFF')
  1650. ]
  1651. for seq, res in sequences:
  1652. self.assertEqual(seq.decode('utf-8'), res)
  1653. def test_utf8_decode_invalid_sequences(self):
  1654. # continuation bytes in a sequence of 2, 3, or 4 bytes
  1655. continuation_bytes = [bytes([x]) for x in range(0x80, 0xC0)]
  1656. # start bytes of a 2-byte sequence equivalent to code points < 0x7F
  1657. invalid_2B_seq_start_bytes = [bytes([x]) for x in range(0xC0, 0xC2)]
  1658. # start bytes of a 4-byte sequence equivalent to code points > 0x10FFFF
  1659. invalid_4B_seq_start_bytes = [bytes([x]) for x in range(0xF5, 0xF8)]
  1660. invalid_start_bytes = (
  1661. continuation_bytes + invalid_2B_seq_start_bytes +
  1662. invalid_4B_seq_start_bytes + [bytes([x]) for x in range(0xF7, 0x100)]
  1663. )
  1664. for byte in invalid_start_bytes:
  1665. self.assertRaises(UnicodeDecodeError, byte.decode, 'utf-8')
  1666. for sb in invalid_2B_seq_start_bytes:
  1667. for cb in continuation_bytes:
  1668. self.assertRaises(UnicodeDecodeError, (sb+cb).decode, 'utf-8')
  1669. for sb in invalid_4B_seq_start_bytes:
  1670. for cb1 in continuation_bytes[:3]:
  1671. for cb3 in continuation_bytes[:3]:
  1672. self.assertRaises(UnicodeDecodeError,
  1673. (sb+cb1+b'\x80'+cb3).decode, 'utf-8')
  1674. for cb in [bytes([x]) for x in range(0x80, 0xA0)]:
  1675. self.assertRaises(UnicodeDecodeError,
  1676. (b'\xE0'+cb+b'\x80').decode, 'utf-8')
  1677. self.assertRaises(UnicodeDecodeError,
  1678. (b'\xE0'+cb+b'\xBF').decode, 'utf-8')
  1679. # surrogates
  1680. for cb in [bytes([x]) for x in range(0xA0, 0xC0)]:
  1681. self.assertRaises(UnicodeDecodeError,
  1682. (b'\xED'+cb+b'\x80').decode, 'utf-8')
  1683. self.assertRaises(UnicodeDecodeError,
  1684. (b'\xED'+cb+b'\xBF').decode, 'utf-8')
  1685. for cb in [bytes([x]) for x in range(0x80, 0x90)]:
  1686. self.assertRaises(UnicodeDecodeError,
  1687. (b'\xF0'+cb+b'\x80\x80').decode, 'utf-8')
  1688. self.assertRaises(UnicodeDecodeError,
  1689. (b'\xF0'+cb+b'\xBF\xBF').decode, 'utf-8')
  1690. for cb in [bytes([x]) for x in range(0x90, 0xC0)]:
  1691. self.assertRaises(UnicodeDecodeError,
  1692. (b'\xF4'+cb+b'\x80\x80').decode, 'utf-8')
  1693. self.assertRaises(UnicodeDecodeError,
  1694. (b'\xF4'+cb+b'\xBF\xBF').decode, 'utf-8')
  1695. def test_issue8271(self):
  1696. # Issue #8271: during the decoding of an invalid UTF-8 byte sequence,
  1697. # only the start byte and the continuation byte(s) are now considered
  1698. # invalid, instead of the number of bytes specified by the start byte.
  1699. # See https://www.unicode.org/versions/Unicode5.2.0/ch03.pdf (page 95,
  1700. # table 3-8, Row 2) for more information about the algorithm used.
  1701. FFFD = '\ufffd'
  1702. sequences = [
  1703. # invalid start bytes
  1704. (b'\x80', FFFD), # continuation byte
  1705. (b'\x80\x80', FFFD*2), # 2 continuation bytes
  1706. (b'\xc0', FFFD),
  1707. (b'\xc0\xc0', FFFD*2),
  1708. (b'\xc1', FFFD),
  1709. (b'\xc1\xc0', FFFD*2),
  1710. (b'\xc0\xc1', FFFD*2),
  1711. # with start byte of a 2-byte sequence
  1712. (b'\xc2', FFFD), # only the start byte
  1713. (b'\xc2\xc2', FFFD*2), # 2 start bytes
  1714. (b'\xc2\xc2\xc2', FFFD*3), # 3 start bytes
  1715. (b'\xc2\x41', FFFD+'A'), # invalid continuation byte
  1716. # with start byte of a 3-byte sequence
  1717. (b'\xe1', FFFD), # only the start byte
  1718. (b'\xe1\xe1', FFFD*2), # 2 start bytes
  1719. (b'\xe1\xe1\xe1', FFFD*3), # 3 start bytes
  1720. (b'\xe1\xe1\xe1\xe1', FFFD*4), # 4 start bytes
  1721. (b'\xe1\x80', FFFD), # only 1 continuation byte
  1722. (b'\xe1\x41', FFFD+'A'), # invalid continuation byte
  1723. (b'\xe1\x41\x80', FFFD+'A'+FFFD), # invalid cb followed by valid cb
  1724. (b'\xe1\x41\x41', FFFD+'AA'), # 2 invalid continuation bytes
  1725. (b'\xe1\x80\x41', FFFD+'A'), # only 1 valid continuation byte
  1726. (b'\xe1\x80\xe1\x41', FFFD*2+'A'), # 1 valid and the other invalid
  1727. (b'\xe1\x41\xe1\x80', FFFD+'A'+FFFD), # 1 invalid and the other valid
  1728. # with start byte of a 4-byte sequence
  1729. (b'\xf1', FFFD), # only the start byte
  1730. (b'\xf1\xf1', FFFD*2), # 2 start bytes
  1731. (b'\xf1\xf1\xf1', FFFD*3), # 3 start bytes
  1732. (b'\xf1\xf1\xf1\xf1', FFFD*4), # 4 start bytes
  1733. (b'\xf1\xf1\xf1\xf1\xf1', FFFD*5), # 5 start bytes
  1734. (b'\xf1\x80', FFFD), # only 1 continuation bytes
  1735. (b'\xf1\x80\x80', FFFD), # only 2 continuation bytes
  1736. (b'\xf1\x80\x41', FFFD+'A'), # 1 valid cb and 1 invalid
  1737. (b'\xf1\x80\x41\x41', FFFD+'AA'), # 1 valid cb and 1 invalid
  1738. (b'\xf1\x80\x80\x41', FFFD+'A'), # 2 valid cb and 1 invalid
  1739. (b'\xf1\x41\x80', FFFD+'A'+FFFD), # 1 invalid cv and 1 valid
  1740. (b'\xf1\x41\x80\x80', FFFD+'A'+FFFD*2), # 1 invalid cb and 2 invalid
  1741. (b'\xf1\x41\x80\x41', FFFD+'A'+FFFD+'A'), # 2 invalid cb and 1 invalid
  1742. (b'\xf1\x41\x41\x80', FFFD+'AA'+FFFD), # 1 valid cb and 1 invalid
  1743. (b'\xf1\x41\xf1\x80', FFFD+'A'+FFFD),
  1744. (b'\xf1\x41\x80\xf1', FFFD+'A'+FFFD*2),
  1745. (b'\xf1\xf1\x80\x41', FFFD*2+'A'),
  1746. (b'\xf1\x41\xf1\xf1', FFFD+'A'+FFFD*2),
  1747. # with invalid start byte of a 4-byte sequence (rfc2279)
  1748. (b'\xf5', FFFD), # only the start byte
  1749. (b'\xf5\xf5', FFFD*2), # 2 start bytes
  1750. (b'\xf5\x80', FFFD*2), # only 1 continuation byte
  1751. (b'\xf5\x80\x80', FFFD*3), # only 2 continuation byte
  1752. (b'\xf5\x80\x80\x80', FFFD*4), # 3 continuation bytes
  1753. (b'\xf5\x80\x41', FFFD*2+'A'), # 1 valid cb and 1 invalid
  1754. (b'\xf5\x80\x41\xf5', FFFD*2+'A'+FFFD),
  1755. (b'\xf5\x41\x80\x80\x41', FFFD+'A'+FFFD*2+'A'),
  1756. # with invalid start byte of a 5-byte sequence (rfc2279)
  1757. (b'\xf8', FFFD), # only the start byte
  1758. (b'\xf8\xf8', FFFD*2), # 2 start bytes
  1759. (b'\xf8\x80', FFFD*2), # only one continuation byte
  1760. (b'\xf8\x80\x41', FFFD*2 + 'A'), # 1 valid cb and 1 invalid
  1761. (b'\xf8\x80\x80\x80\x80', FFFD*5), # invalid 5 bytes seq with 5 bytes
  1762. # with invalid start byte of a 6-byte sequence (rfc2279)
  1763. (b'\xfc', FFFD), # only the start byte
  1764. (b'\xfc\xfc', FFFD*2), # 2 start bytes
  1765. (b'\xfc\x80\x80', FFFD*3), # only 2 continuation bytes
  1766. (b'\xfc\x80\x80\x80\x80\x80', FFFD*6), # 6 continuation bytes
  1767. # invalid start byte
  1768. (b'\xfe', FFFD),
  1769. (b'\xfe\x80\x80', FFFD*3),
  1770. # other sequences
  1771. (b'\xf1\x80\x41\x42\x43', '\ufffd\x41\x42\x43'),
  1772. (b'\xf1\x80\xff\x42\x43', '\ufffd\ufffd\x42\x43'),
  1773. (b'\xf1\x80\xc2\x81\x43', '\ufffd\x81\x43'),
  1774. (b'\x61\xF1\x80\x80\xE1\x80\xC2\x62\x80\x63\x80\xBF\x64',
  1775. '\x61\uFFFD\uFFFD\uFFFD\x62\uFFFD\x63\uFFFD\uFFFD\x64'),
  1776. ]
  1777. for n, (seq, res) in enumerate(sequences):
  1778. self.assertRaises(UnicodeDecodeError, seq.decode, 'utf-8', 'strict')
  1779. self.assertEqual(seq.decode('utf-8', 'replace'), res)
  1780. self.assertEqual((seq+b'b').decode('utf-8', 'replace'), res+'b')
  1781. self.assertEqual(seq.decode('utf-8', 'ignore'),
  1782. res.replace('\uFFFD', ''))
  1783. def assertCorrectUTF8Decoding(self, seq, res, err):
  1784. """
  1785. Check that an invalid UTF-8 sequence raises a UnicodeDecodeError when
  1786. 'strict' is used, returns res when 'replace' is used, and that doesn't
  1787. return anything when 'ignore' is used.
  1788. """
  1789. with self.assertRaises(UnicodeDecodeError) as cm:
  1790. seq.decode('utf-8')
  1791. exc = cm.exception
  1792. self.assertIn(err, str(exc))
  1793. self.assertEqual(seq.decode('utf-8', 'replace'), res)
  1794. self.assertEqual((b'aaaa' + seq + b'bbbb').decode('utf-8', 'replace'),
  1795. 'aaaa' + res + 'bbbb')
  1796. res = res.replace('\ufffd', '')
  1797. self.assertEqual(seq.decode('utf-8', 'ignore'), res)
  1798. self.assertEqual((b'aaaa' + seq + b'bbbb').decode('utf-8', 'ignore'),
  1799. 'aaaa' + res + 'bbbb')
  1800. def test_invalid_start_byte(self):
  1801. """
  1802. Test that an 'invalid start byte' error is raised when the first byte
  1803. is not in the ASCII range or is not a valid start byte of a 2-, 3-, or
  1804. 4-bytes sequence. The invalid start byte is replaced with a single
  1805. U+FFFD when errors='replace'.
  1806. E.g. <80> is a continuation byte and can appear only after a start byte.
  1807. """
  1808. FFFD = '\ufffd'
  1809. for byte in b'\x80\xA0\x9F\xBF\xC0\xC1\xF5\xFF':
  1810. self.assertCorrectUTF8Decoding(bytes([byte]), '\ufffd',
  1811. 'invalid start byte')
  1812. def test_unexpected_end_of_data(self):
  1813. """
  1814. Test that an 'unexpected end of data' error is raised when the string
  1815. ends after a start byte of a 2-, 3-, or 4-bytes sequence without having
  1816. enough continuation bytes. The incomplete sequence is replaced with a
  1817. single U+FFFD when errors='replace'.
  1818. E.g. in the sequence <F3 80 80>, F3 is the start byte of a 4-bytes
  1819. sequence, but it's followed by only 2 valid continuation bytes and the
  1820. last continuation bytes is missing.
  1821. Note: the continuation bytes must be all valid, if one of them is
  1822. invalid another error will be raised.
  1823. """
  1824. sequences = [
  1825. 'C2', 'DF',
  1826. 'E0 A0', 'E0 BF', 'E1 80', 'E1 BF', 'EC 80', 'EC BF',
  1827. 'ED 80', 'ED 9F', 'EE 80', 'EE BF', 'EF 80', 'EF BF',
  1828. 'F0 90', 'F0 BF', 'F0 90 80', 'F0 90 BF', 'F0 BF 80', 'F0 BF BF',
  1829. 'F1 80', 'F1 BF', 'F1 80 80', 'F1 80 BF', 'F1 BF 80', 'F1 BF BF',
  1830. 'F3 80', 'F3 BF', 'F3 80 80', 'F3 80 BF', 'F3 BF 80', 'F3 BF BF',
  1831. 'F4 80', 'F4 8F', 'F4 80 80', 'F4 80 BF', 'F4 8F 80', 'F4 8F BF'
  1832. ]
  1833. FFFD = '\ufffd'
  1834. for seq in sequences:
  1835. self.assertCorrectUTF8Decoding(bytes.fromhex(seq), '\ufffd',
  1836. 'unexpected end of data')
  1837. def test_invalid_cb_for_2bytes_seq(self):
  1838. """
  1839. Test that an 'invalid continuation byte' error is raised when the
  1840. continuation byte of a 2-bytes sequence is invalid. The start byte
  1841. is replaced by a single U+FFFD and the second byte is handled
  1842. separately when errors='replace'.
  1843. E.g. in the sequence <C2 41>, C2 is the start byte of a 2-bytes
  1844. sequence, but 41 is not a valid continuation byte because it's the
  1845. ASCII letter 'A'.
  1846. """
  1847. FFFD = '\ufffd'
  1848. FFFDx2 = FFFD * 2
  1849. sequences = [
  1850. ('C2 00', FFFD+'\x00'), ('C2 7F', FFFD+'\x7f'),
  1851. ('C2 C0', FFFDx2), ('C2 FF', FFFDx2),
  1852. ('DF 00', FFFD+'\x00'), ('DF 7F', FFFD+'\x7f'),
  1853. ('DF C0', FFFDx2), ('DF FF', FFFDx2),
  1854. ]
  1855. for seq, res in sequences:
  1856. self.assertCorrectUTF8Decoding(bytes.fromhex(seq), res,
  1857. 'invalid continuation byte')
  1858. def test_invalid_cb_for_3bytes_seq(self):
  1859. """
  1860. Test that an 'invalid continuation byte' error is raised when the
  1861. continuation byte(s) of a 3-bytes sequence are invalid. When
  1862. errors='replace', if the first continuation byte is valid, the first
  1863. two bytes (start byte + 1st cb) are replaced by a single U+FFFD and the
  1864. third byte is handled separately, otherwise only the start byte is
  1865. replaced with a U+FFFD and the other continuation bytes are handled
  1866. separately.
  1867. E.g. in the sequence <E1 80 41>, E1 is the start byte of a 3-bytes
  1868. sequence, 80 is a valid continuation byte, but 41 is not a valid cb
  1869. because it's the ASCII letter 'A'.
  1870. Note: when the start byte is E0 or ED, the valid ranges for the first
  1871. continuation byte are limited to A0..BF and 80..9F respectively.
  1872. Python 2 used to consider all the bytes in range 80..BF valid when the
  1873. start byte was ED. This is fixed in Python 3.
  1874. """
  1875. FFFD = '\ufffd'
  1876. FFFDx2 = FFFD * 2
  1877. sequences = [
  1878. ('E0 00', FFFD+'\x00'), ('E0 7F', FFFD+'\x7f'), ('E0 80', FFFDx2),
  1879. ('E0 9F', FFFDx2), ('E0 C0', FFFDx2), ('E0 FF', FFFDx2),
  1880. ('E0 A0 00', FFFD+'\x00'), ('E0 A0 7F', FFFD+'\x7f'),
  1881. ('E0 A0 C0', FFFDx2), ('E0 A0 FF', FFFDx2),
  1882. ('E0 BF 00', FFFD+'\x00'), ('E0 BF 7F', FFFD+'\x7f'),
  1883. ('E0 BF C0', FFFDx2), ('E0 BF FF', FFFDx2), ('E1 00', FFFD+'\x00'),
  1884. ('E1 7F', FFFD+'\x7f'), ('E1 C0', FFFDx2), ('E1 FF', FFFDx2),
  1885. ('E1 80 00', FFFD+'\x00'), ('E1 80 7F', FFFD+'\x7f'),
  1886. ('E1 80 C0', FFFDx2), ('E1 80 FF', FFFDx2),
  1887. ('E1 BF 00', FFFD+'\x00'), ('E1 BF 7F', FFFD+'\x7f'),
  1888. ('E1 BF C0', FFFDx2), ('E1 BF FF', FFFDx2), ('EC 00', FFFD+'\x00'),
  1889. ('EC 7F', FFFD+'\x7f'), ('EC C0', FFFDx2), ('EC FF', FFFDx2),
  1890. ('EC 80 00', FFFD+'\x00'), ('EC 80 7F', FFFD+'\x7f'),
  1891. ('EC 80 C0', FFFDx2), ('EC 80 FF', FFFDx2),
  1892. ('EC BF 00', FFFD+'\x00'), ('EC BF 7F', FFFD+'\x7f'),
  1893. ('EC BF C0', FFFDx2), ('EC BF FF', FFFDx2), ('ED 00', FFFD+'\x00'),
  1894. ('ED 7F', FFFD+'\x7f'),
  1895. ('ED A0', FFFDx2), ('ED BF', FFFDx2), # see note ^
  1896. ('ED C0', FFFDx2), ('ED FF', FFFDx2), ('ED 80 00', FFFD+'\x00'),
  1897. ('ED 80 7F', FFFD+'\x7f'), ('ED 80 C0', FFFDx2),
  1898. ('ED 80 FF', FFFDx2), ('ED 9F 00', FFFD+'\x00'),
  1899. ('ED 9F 7F', FFFD+'\x7f'), ('ED 9F C0', FFFDx2),
  1900. ('ED 9F FF', FFFDx2), ('EE 00', FFFD+'\x00'),
  1901. ('EE 7F', FFFD+'\x7f'), ('EE C0', FFFDx2), ('EE FF', FFFDx2),
  1902. ('EE 80 00', FFFD+'\x00'), ('EE 80 7F', FFFD+'\x7f'),
  1903. ('EE 80 C0', FFFDx2), ('EE 80 FF', FFFDx2),
  1904. ('EE BF 00', FFFD+'\x00'), ('EE BF 7F', FFFD+'\x7f'),
  1905. ('EE BF C0', FFFDx2), ('EE BF FF', FFFDx2), ('EF 00', FFFD+'\x00'),
  1906. ('EF 7F', FFFD+'\x7f'), ('EF C0', FFFDx2), ('EF FF', FFFDx2),
  1907. ('EF 80 00', FFFD+'\x00'), ('EF 80 7F', FFFD+'\x7f'),
  1908. ('EF 80 C0', FFFDx2), ('EF 80 FF', FFFDx2),
  1909. ('EF BF 00', FFFD+'\x00'), ('EF BF 7F', FFFD+'\x7f'),
  1910. ('EF BF C0', FFFDx2), ('EF BF FF', FFFDx2),
  1911. ]
  1912. for seq, res in sequences:
  1913. self.assertCorrectUTF8Decoding(bytes.fromhex(seq), res,
  1914. 'invalid continuation byte')
  1915. def test_invalid_cb_for_4bytes_seq(self):
  1916. """
  1917. Test that an 'invalid continuation byte' error is raised when the
  1918. continuation byte(s) of a 4-bytes sequence are invalid. When
  1919. errors='replace',the start byte and all the following valid
  1920. continuation bytes are replaced with a single U+FFFD, and all the bytes
  1921. starting from the first invalid continuation bytes (included) are
  1922. handled separately.
  1923. E.g. in the sequence <E1 80 41>, E1 is the start byte of a 3-bytes
  1924. sequence, 80 is a valid continuation byte, but 41 is not a valid cb
  1925. because it's the ASCII letter 'A'.
  1926. Note: when the start byte is E0 or ED, the valid ranges for the first
  1927. continuation byte are limited to A0..BF and 80..9F respectively.
  1928. However, when the start byte is ED, Python 2 considers all the bytes
  1929. in range 80..BF valid. This is fixed in Python 3.
  1930. """
  1931. FFFD = '\ufffd'
  1932. FFFDx2 = FFFD * 2
  1933. sequences = [
  1934. ('F0 00', FFFD+'\x00'), ('F0 7F', FFFD+'\x7f'), ('F0 80', FFFDx2),
  1935. ('F0 8F', FFFDx2), ('F0 C0', FFFDx2), ('F0 FF', FFFDx2),
  1936. ('F0 90 00', FFFD+'\x00'), ('F0 90 7F', FFFD+'\x7f'),
  1937. ('F0 90 C0', FFFDx2), ('F0 90 FF', FFFDx2),
  1938. ('F0 BF 00', FFFD+'\x00'), ('F0 BF 7F', FFFD+'\x7f'),
  1939. ('F0 BF C0', FFFDx2), ('F0 BF FF', FFFDx2),
  1940. ('F0 90 80 00', FFFD+'\x00'), ('F0 90 80 7F', FFFD+'\x7f'),
  1941. ('F0 90 80 C0', FFFDx2), ('F0 90 80 FF', FFFDx2),
  1942. ('F0 90 BF 00', FFFD+'\x00'), ('F0 90 BF 7F', FFFD+'\x7f'),
  1943. ('F0 90 BF C0', FFFDx2), ('F0 90 BF FF', FFFDx2),
  1944. ('F0 BF 80 00', FFFD+'\x00'), ('F0 BF 80 7F', FFFD+'\x7f'),
  1945. ('F0 BF 80 C0', FFFDx2), ('F0 BF 80 FF', FFFDx2),
  1946. ('F0 BF BF 00', FFFD+'\x00'), ('F0 BF BF 7F', FFFD+'\x7f'),
  1947. ('F0 BF BF C0', FFFDx2), ('F0 BF BF FF', FFFDx2),
  1948. ('F1 00', FFFD+'\x00'), ('F1 7F', FFFD+'\x7f'), ('F1 C0', FFFDx2),
  1949. ('F1 FF', FFFDx2), ('F1 80 00', FFFD+'\x00'),
  1950. ('F1 80 7F', FFFD+'\x7f'), ('F1 80 C0', FFFDx2),
  1951. ('F1 80 FF', FFFDx2), ('F1 BF 00', FFFD+'\x00'),
  1952. ('F1 BF 7F', FFFD+'\x7f'), ('F1 BF C0', FFFDx2),
  1953. ('F1 BF FF', FFFDx2), ('F1 80 80 00', FFFD+'\x00'),
  1954. ('F1 80 80 7F', FFFD+'\x7f'), ('F1 80 80 C0', FFFDx2),
  1955. ('F1 80 80 FF', FFFDx2), ('F1 80 BF 00', FFFD+'\x00'),
  1956. ('F1 80 BF 7F', FFFD+'\x7f'), ('F1 80 BF C0', FFFDx2),
  1957. ('F1 80 BF FF', FFFDx2), ('F1 BF 80 00', FFFD+'\x00'),
  1958. ('F1 BF 80 7F', FFFD+'\x7f'), ('F1 BF 80 C0', FFFDx2),
  1959. ('F1 BF 80 FF', FFFDx2), ('F1 BF BF 00', FFFD+'\x00'),
  1960. ('F1 BF BF 7F', FFFD+'\x7f'), ('F1 BF BF C0', FFFDx2),
  1961. ('F1 BF BF FF', FFFDx2), ('F3 00', FFFD+'\x00'),
  1962. ('F3 7F', FFFD+'\x7f'), ('F3 C0', FFFDx2), ('F3 FF', FFFDx2),
  1963. ('F3 80 00', FFFD+'\x00'), ('F3 80 7F', FFFD+'\x7f'),
  1964. ('F3 80 C0', FFFDx2), ('F3 80 FF', FFFDx2),
  1965. ('F3 BF 00', FFFD+'\x00'), ('F3 BF 7F', FFFD+'\x7f'),
  1966. ('F3 BF C0', FFFDx2), ('F3 BF FF', FFFDx2),
  1967. ('F3 80 80 00', FFFD+'\x00'), ('F3 80 80 7F', FFFD+'\x7f'),
  1968. ('F3 80 80 C0', FFFDx2), ('F3 80 80 FF', FFFDx2),
  1969. ('F3 80 BF 00', FFFD+'\x00'), ('F3 80 BF 7F', FFFD+'\x7f'),
  1970. ('F3 80 BF C0', FFFDx2), ('F3 80 BF FF', FFFDx2),
  1971. ('F3 BF 80 00', FFFD+'\x00'), ('F3 BF 80 7F', FFFD+'\x7f'),
  1972. ('F3 BF 80 C0', FFFDx2), ('F3 BF 80 FF', FFFDx2),
  1973. ('F3 BF BF 00', FFFD+'\x00'), ('F3 BF BF 7F', FFFD+'\x7f'),
  1974. ('F3 BF BF C0', FFFDx2), ('F3 BF BF FF', FFFDx2),
  1975. ('F4 00', FFFD+'\x00'), ('F4 7F', FFFD+'\x7f'), ('F4 90', FFFDx2),
  1976. ('F4 BF', FFFDx2), ('F4 C0', FFFDx2), ('F4 FF', FFFDx2),
  1977. ('F4 80 00', FFFD+'\x00'), ('F4 80 7F', FFFD+'\x7f'),
  1978. ('F4 80 C0', FFFDx2), ('F4 80 FF', FFFDx2),
  1979. ('F4 8F 00', FFFD+'\x00'), ('F4 8F 7F', FFFD+'\x7f'),
  1980. ('F4 8F C0', FFFDx2), ('F4 8F FF', FFFDx2),
  1981. ('F4 80 80 00', FFFD+'\x00'), ('F4 80 80 7F', FFFD+'\x7f'),
  1982. ('F4 80 80 C0', FFFDx2), ('F4 80 80 FF', FFFDx2),
  1983. ('F4 80 BF 00', FFFD+'\x00'), ('F4 80 BF 7F', FFFD+'\x7f'),
  1984. ('F4 80 BF C0', FFFDx2), ('F4 80 BF FF', FFFDx2),
  1985. ('F4 8F 80 00', FFFD+'\x00'), ('F4 8F 80 7F', FFFD+'\x7f'),
  1986. ('F4 8F 80 C0', FFFDx2), ('F4 8F 80 FF', FFFDx2),
  1987. ('F4 8F BF 00', FFFD+'\x00'), ('F4 8F BF 7F', FFFD+'\x7f'),
  1988. ('F4 8F BF C0', FFFDx2), ('F4 8F BF FF', FFFDx2)
  1989. ]
  1990. for seq, res in sequences:
  1991. self.assertCorrectUTF8Decoding(bytes.fromhex(seq), res,
  1992. 'invalid continuation byte')
  1993. def test_codecs_idna(self):
  1994. # Test whether trailing dot is preserved
  1995. self.assertEqual("www.python.org.".encode("idna"), b"www.python.org.")
  1996. def test_codecs_errors(self):
  1997. # Error handling (encoding)
  1998. self.assertRaises(UnicodeError, 'Andr\202 x'.encode, 'ascii')
  1999. self.assertRaises(UnicodeError, 'Andr\202 x'.encode, 'ascii','strict')
  2000. self.assertEqual('Andr\202 x'.encode('ascii','ignore'), b"Andr x")
  2001. self.assertEqual('Andr\202 x'.encode('ascii','replace'), b"Andr? x")
  2002. self.assertEqual('Andr\202 x'.encode('ascii', 'replace'),
  2003. 'Andr\202 x'.encode('ascii', errors='replace'))
  2004. self.assertEqual('Andr\202 x'.encode('ascii', 'ignore'),
  2005. 'Andr\202 x'.encode(encoding='ascii', errors='ignore'))
  2006. # Error handling (decoding)
  2007. self.assertRaises(UnicodeError, str, b'Andr\202 x', 'ascii')
  2008. self.assertRaises(UnicodeError, str, b'Andr\202 x', 'ascii', 'strict')
  2009. self.assertEqual(str(b'Andr\202 x', 'ascii', 'ignore'), "Andr x")
  2010. self.assertEqual(str(b'Andr\202 x', 'ascii', 'replace'), 'Andr\uFFFD x')
  2011. self.assertEqual(str(b'\202 x', 'ascii', 'replace'), '\uFFFD x')
  2012. # Error handling (unknown character names)
  2013. self.assertEqual(b"\\N{foo}xx".decode("unicode-escape", "ignore"), "xx")
  2014. # Error handling (truncated escape sequence)
  2015. self.assertRaises(UnicodeError, b"\\".decode, "unicode-escape")
  2016. self.assertRaises(TypeError, b"hello".decode, "test.unicode1")
  2017. self.assertRaises(TypeError, str, b"hello", "test.unicode2")
  2018. self.assertRaises(TypeError, "hello".encode, "test.unicode1")
  2019. self.assertRaises(TypeError, "hello".encode, "test.unicode2")
  2020. # Error handling (wrong arguments)
  2021. self.assertRaises(TypeError, "hello".encode, 42, 42, 42)
  2022. # Error handling (lone surrogate in
  2023. # _PyUnicode_TransformDecimalAndSpaceToASCII())
  2024. self.assertRaises(ValueError, int, "\ud800")
  2025. self.assertRaises(ValueError, int, "\udf00")
  2026. self.assertRaises(ValueError, float, "\ud800")
  2027. self.assertRaises(ValueError, float, "\udf00")
  2028. self.assertRaises(ValueError, complex, "\ud800")
  2029. self.assertRaises(ValueError, complex, "\udf00")
  2030. def test_codecs(self):
  2031. # Encoding
  2032. self.assertEqual('hello'.encode('ascii'), b'hello')
  2033. self.assertEqual('hello'.encode('utf-7'), b'hello')
  2034. self.assertEqual('hello'.encode('utf-8'), b'hello')
  2035. self.assertEqual('hello'.encode('utf-8'), b'hello')
  2036. self.assertEqual('hello'.encode('utf-16-le'), b'h\000e\000l\000l\000o\000')
  2037. self.assertEqual('hello'.encode('utf-16-be'), b'\000h\000e\000l\000l\000o')
  2038. self.assertEqual('hello'.encode('latin-1'), b'hello')
  2039. # Default encoding is utf-8
  2040. self.assertEqual('\u2603'.encode(), b'\xe2\x98\x83')
  2041. # Roundtrip safety for BMP (just the first 1024 chars)
  2042. for c in range(1024):
  2043. u = chr(c)
  2044. for encoding in ('utf-7', 'utf-8', 'utf-16', 'utf-16-le',
  2045. 'utf-16-be', 'raw_unicode_escape',
  2046. 'unicode_escape'):
  2047. self.assertEqual(str(u.encode(encoding),encoding), u)
  2048. # Roundtrip safety for BMP (just the first 256 chars)
  2049. for c in range(256):
  2050. u = chr(c)
  2051. for encoding in ('latin-1',):
  2052. self.assertEqual(str(u.encode(encoding),encoding), u)
  2053. # Roundtrip safety for BMP (just the first 128 chars)
  2054. for c in range(128):
  2055. u = chr(c)
  2056. for encoding in ('ascii',):
  2057. self.assertEqual(str(u.encode(encoding),encoding), u)
  2058. # Roundtrip safety for non-BMP (just a few chars)
  2059. with warnings.catch_warnings():
  2060. u = '\U00010001\U00020002\U00030003\U00040004\U00050005'
  2061. for encoding in ('utf-8', 'utf-16', 'utf-16-le', 'utf-16-be',
  2062. 'raw_unicode_escape', 'unicode_escape'):
  2063. self.assertEqual(str(u.encode(encoding),encoding), u)
  2064. # UTF-8 must be roundtrip safe for all code points
  2065. # (except surrogates, which are forbidden).
  2066. u = ''.join(map(chr, list(range(0, 0xd800)) +
  2067. list(range(0xe000, 0x110000))))
  2068. for encoding in ('utf-8',):
  2069. self.assertEqual(str(u.encode(encoding),encoding), u)
  2070. def test_codecs_charmap(self):
  2071. # 0-127
  2072. s = bytes(range(128))
  2073. for encoding in (
  2074. 'cp037', 'cp1026', 'cp273',
  2075. 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850',
  2076. 'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862',
  2077. 'cp863', 'cp865', 'cp866', 'cp1125',
  2078. 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
  2079. 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6',
  2080. 'iso8859_7', 'iso8859_9',
  2081. 'koi8_r', 'koi8_t', 'koi8_u', 'kz1048', 'latin_1',
  2082. 'mac_cyrillic', 'mac_latin2',
  2083. 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255',
  2084. 'cp1256', 'cp1257', 'cp1258',
  2085. 'cp856', 'cp857', 'cp864', 'cp869', 'cp874',
  2086. 'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish',
  2087. 'cp1006', 'iso8859_8',
  2088. ### These have undefined mappings:
  2089. #'cp424',
  2090. ### These fail the round-trip:
  2091. #'cp875'
  2092. ):
  2093. self.assertEqual(str(s, encoding).encode(encoding), s)
  2094. # 128-255
  2095. s = bytes(range(128, 256))
  2096. for encoding in (
  2097. 'cp037', 'cp1026', 'cp273',
  2098. 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850',
  2099. 'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862',
  2100. 'cp863', 'cp865', 'cp866', 'cp1125',
  2101. 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
  2102. 'iso8859_2', 'iso8859_4', 'iso8859_5',
  2103. 'iso8859_9', 'koi8_r', 'koi8_u', 'latin_1',
  2104. 'mac_cyrillic', 'mac_latin2',
  2105. ### These have undefined mappings:
  2106. #'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255',
  2107. #'cp1256', 'cp1257', 'cp1258',
  2108. #'cp424', 'cp856', 'cp857', 'cp864', 'cp869', 'cp874',
  2109. #'iso8859_3', 'iso8859_6', 'iso8859_7', 'koi8_t', 'kz1048',
  2110. #'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish',
  2111. ### These fail the round-trip:
  2112. #'cp1006', 'cp875', 'iso8859_8',
  2113. ):
  2114. self.assertEqual(str(s, encoding).encode(encoding), s)
  2115. def test_concatenation(self):
  2116. self.assertEqual(("abc" "def"), "abcdef")
  2117. self.assertEqual(("abc" "def"), "abcdef")
  2118. self.assertEqual(("abc" "def"), "abcdef")
  2119. self.assertEqual(("abc" "def" "ghi"), "abcdefghi")
  2120. self.assertEqual(("abc" "def" "ghi"), "abcdefghi")
  2121. def test_ucs4(self):
  2122. x = '\U00100000'
  2123. y = x.encode("raw-unicode-escape").decode("raw-unicode-escape")
  2124. self.assertEqual(x, y)
  2125. y = br'\U00100000'
  2126. x = y.decode("raw-unicode-escape").encode("raw-unicode-escape")
  2127. self.assertEqual(x, y)
  2128. y = br'\U00010000'
  2129. x = y.decode("raw-unicode-escape").encode("raw-unicode-escape")
  2130. self.assertEqual(x, y)
  2131. try:
  2132. br'\U11111111'.decode("raw-unicode-escape")
  2133. except UnicodeDecodeError as e:
  2134. self.assertEqual(e.start, 0)
  2135. self.assertEqual(e.end, 10)
  2136. else:
  2137. self.fail("Should have raised UnicodeDecodeError")
  2138. def test_conversion(self):
  2139. # Make sure __str__() works properly
  2140. class ObjectToStr:
  2141. def __str__(self):
  2142. return "foo"
  2143. class StrSubclassToStr(str):
  2144. def __str__(self):
  2145. return "foo"
  2146. class StrSubclassToStrSubclass(str):
  2147. def __new__(cls, content=""):
  2148. return str.__new__(cls, 2*content)
  2149. def __str__(self):
  2150. return self
  2151. self.assertEqual(str(ObjectToStr()), "foo")
  2152. self.assertEqual(str(StrSubclassToStr("bar")), "foo")
  2153. s = str(StrSubclassToStrSubclass("foo"))
  2154. self.assertEqual(s, "foofoo")
  2155. self.assertIs(type(s), StrSubclassToStrSubclass)
  2156. s = StrSubclass(StrSubclassToStrSubclass("foo"))
  2157. self.assertEqual(s, "foofoo")
  2158. self.assertIs(type(s), StrSubclass)
  2159. def test_unicode_repr(self):
  2160. class s1:
  2161. def __repr__(self):
  2162. return '\\n'
  2163. class s2:
  2164. def __repr__(self):
  2165. return '\\n'
  2166. self.assertEqual(repr(s1()), '\\n')
  2167. self.assertEqual(repr(s2()), '\\n')
  2168. def test_printable_repr(self):
  2169. self.assertEqual(repr('\U00010000'), "'%c'" % (0x10000,)) # printable
  2170. self.assertEqual(repr('\U00014000'), "'\\U00014000'") # nonprintable
  2171. # This test only affects 32-bit platforms because expandtabs can only take
  2172. # an int as the max value, not a 64-bit C long. If expandtabs is changed
  2173. # to take a 64-bit long, this test should apply to all platforms.
  2174. @unittest.skipIf(sys.maxsize > (1 << 32) or struct.calcsize('P') != 4,
  2175. 'only applies to 32-bit platforms')
  2176. def test_expandtabs_overflows_gracefully(self):
  2177. self.assertRaises(OverflowError, 't\tt\t'.expandtabs, sys.maxsize)
  2178. @support.cpython_only
  2179. def test_expandtabs_optimization(self):
  2180. s = 'abc'
  2181. self.assertIs(s.expandtabs(), s)
  2182. def test_raiseMemError(self):
  2183. asciifields = "nnbP"
  2184. compactfields = asciifields + "nPn"
  2185. ascii_struct_size = support.calcobjsize(asciifields)
  2186. compact_struct_size = support.calcobjsize(compactfields)
  2187. for char in ('a', '\xe9', '\u20ac', '\U0010ffff'):
  2188. code = ord(char)
  2189. if code < 0x80:
  2190. char_size = 1 # sizeof(Py_UCS1)
  2191. struct_size = ascii_struct_size
  2192. elif code < 0x100:
  2193. char_size = 1 # sizeof(Py_UCS1)
  2194. struct_size = compact_struct_size
  2195. elif code < 0x10000:
  2196. char_size = 2 # sizeof(Py_UCS2)
  2197. struct_size = compact_struct_size
  2198. else:
  2199. char_size = 4 # sizeof(Py_UCS4)
  2200. struct_size = compact_struct_size
  2201. # Note: sys.maxsize is half of the actual max allocation because of
  2202. # the signedness of Py_ssize_t. Strings of maxlen-1 should in principle
  2203. # be allocatable, given enough memory.
  2204. maxlen = ((sys.maxsize - struct_size) // char_size)
  2205. alloc = lambda: char * maxlen
  2206. with self.subTest(
  2207. char=char,
  2208. struct_size=struct_size,
  2209. char_size=char_size
  2210. ):
  2211. # self-check
  2212. self.assertEqual(
  2213. sys.getsizeof(char * 42),
  2214. struct_size + (char_size * (42 + 1))
  2215. )
  2216. self.assertRaises(MemoryError, alloc)
  2217. self.assertRaises(MemoryError, alloc)
  2218. def test_format_subclass(self):
  2219. class S(str):
  2220. def __str__(self):
  2221. return '__str__ overridden'
  2222. s = S('xxx')
  2223. self.assertEqual("%s" % s, '__str__ overridden')
  2224. self.assertEqual("{}".format(s), '__str__ overridden')
  2225. def test_subclass_add(self):
  2226. class S(str):
  2227. def __add__(self, o):
  2228. return "3"
  2229. self.assertEqual(S("4") + S("5"), "3")
  2230. class S(str):
  2231. def __iadd__(self, o):
  2232. return "3"
  2233. s = S("1")
  2234. s += "4"
  2235. self.assertEqual(s, "3")
  2236. def test_getnewargs(self):
  2237. text = 'abc'
  2238. args = text.__getnewargs__()
  2239. self.assertIsNot(args[0], text)
  2240. self.assertEqual(args[0], text)
  2241. self.assertEqual(len(args), 1)
  2242. @support.cpython_only
  2243. @support.requires_legacy_unicode_capi
  2244. @unittest.skipIf(_testcapi is None, 'need _testcapi module')
  2245. def test_resize(self):
  2246. for length in range(1, 100, 7):
  2247. # generate a fresh string (refcount=1)
  2248. text = 'a' * length + 'b'
  2249. # fill wstr internal field
  2250. with self.assertWarns(DeprecationWarning):
  2251. abc = _testcapi.getargs_u(text)
  2252. self.assertEqual(abc, text)
  2253. # resize text: wstr field must be cleared and then recomputed
  2254. text += 'c'
  2255. with self.assertWarns(DeprecationWarning):
  2256. abcdef = _testcapi.getargs_u(text)
  2257. self.assertNotEqual(abc, abcdef)
  2258. self.assertEqual(abcdef, text)
  2259. def test_compare(self):
  2260. # Issue #17615
  2261. N = 10
  2262. ascii = 'a' * N
  2263. ascii2 = 'z' * N
  2264. latin = '\x80' * N
  2265. latin2 = '\xff' * N
  2266. bmp = '\u0100' * N
  2267. bmp2 = '\uffff' * N
  2268. astral = '\U00100000' * N
  2269. astral2 = '\U0010ffff' * N
  2270. strings = (
  2271. ascii, ascii2,
  2272. latin, latin2,
  2273. bmp, bmp2,
  2274. astral, astral2)
  2275. for text1, text2 in itertools.combinations(strings, 2):
  2276. equal = (text1 is text2)
  2277. self.assertEqual(text1 == text2, equal)
  2278. self.assertEqual(text1 != text2, not equal)
  2279. if equal:
  2280. self.assertTrue(text1 <= text2)
  2281. self.assertTrue(text1 >= text2)
  2282. # text1 is text2: duplicate strings to skip the "str1 == str2"
  2283. # optimization in unicode_compare_eq() and really compare
  2284. # character per character
  2285. copy1 = duplicate_string(text1)
  2286. copy2 = duplicate_string(text2)
  2287. self.assertIsNot(copy1, copy2)
  2288. self.assertTrue(copy1 == copy2)
  2289. self.assertFalse(copy1 != copy2)
  2290. self.assertTrue(copy1 <= copy2)
  2291. self.assertTrue(copy2 >= copy2)
  2292. self.assertTrue(ascii < ascii2)
  2293. self.assertTrue(ascii < latin)
  2294. self.assertTrue(ascii < bmp)
  2295. self.assertTrue(ascii < astral)
  2296. self.assertFalse(ascii >= ascii2)
  2297. self.assertFalse(ascii >= latin)
  2298. self.assertFalse(ascii >= bmp)
  2299. self.assertFalse(ascii >= astral)
  2300. self.assertFalse(latin < ascii)
  2301. self.assertTrue(latin < latin2)
  2302. self.assertTrue(latin < bmp)
  2303. self.assertTrue(latin < astral)
  2304. self.assertTrue(latin >= ascii)
  2305. self.assertFalse(latin >= latin2)
  2306. self.assertFalse(latin >= bmp)
  2307. self.assertFalse(latin >= astral)
  2308. self.assertFalse(bmp < ascii)
  2309. self.assertFalse(bmp < latin)
  2310. self.assertTrue(bmp < bmp2)
  2311. self.assertTrue(bmp < astral)
  2312. self.assertTrue(bmp >= ascii)
  2313. self.assertTrue(bmp >= latin)
  2314. self.assertFalse(bmp >= bmp2)
  2315. self.assertFalse(bmp >= astral)
  2316. self.assertFalse(astral < ascii)
  2317. self.assertFalse(astral < latin)
  2318. self.assertFalse(astral < bmp2)
  2319. self.assertTrue(astral < astral2)
  2320. self.assertTrue(astral >= ascii)
  2321. self.assertTrue(astral >= latin)
  2322. self.assertTrue(astral >= bmp2)
  2323. self.assertFalse(astral >= astral2)
  2324. def test_free_after_iterating(self):
  2325. support.check_free_after_iterating(self, iter, str)
  2326. support.check_free_after_iterating(self, reversed, str)
  2327. def test_check_encoding_errors(self):
  2328. # bpo-37388: str(bytes) and str.decode() must check encoding and errors
  2329. # arguments in dev mode
  2330. encodings = ('ascii', 'utf8', 'latin1')
  2331. invalid = 'Boom, Shaka Laka, Boom!'
  2332. code = textwrap.dedent(f'''
  2333. import sys
  2334. encodings = {encodings!r}
  2335. for data in (b'', b'short string'):
  2336. try:
  2337. str(data, encoding={invalid!r})
  2338. except LookupError:
  2339. pass
  2340. else:
  2341. sys.exit(21)
  2342. try:
  2343. str(data, errors={invalid!r})
  2344. except LookupError:
  2345. pass
  2346. else:
  2347. sys.exit(22)
  2348. for encoding in encodings:
  2349. try:
  2350. str(data, encoding, errors={invalid!r})
  2351. except LookupError:
  2352. pass
  2353. else:
  2354. sys.exit(22)
  2355. for data in ('', 'short string'):
  2356. try:
  2357. data.encode(encoding={invalid!r})
  2358. except LookupError:
  2359. pass
  2360. else:
  2361. sys.exit(23)
  2362. try:
  2363. data.encode(errors={invalid!r})
  2364. except LookupError:
  2365. pass
  2366. else:
  2367. sys.exit(24)
  2368. for encoding in encodings:
  2369. try:
  2370. data.encode(encoding, errors={invalid!r})
  2371. except LookupError:
  2372. pass
  2373. else:
  2374. sys.exit(24)
  2375. sys.exit(10)
  2376. ''')
  2377. proc = assert_python_failure('-X', 'dev', '-c', code)
  2378. self.assertEqual(proc.rc, 10, proc)
  2379. class StringModuleTest(unittest.TestCase):
  2380. def test_formatter_parser(self):
  2381. def parse(format):
  2382. return list(_string.formatter_parser(format))
  2383. formatter = parse("prefix {2!s}xxx{0:^+10.3f}{obj.attr!s} {z[0]!s:10}")
  2384. self.assertEqual(formatter, [
  2385. ('prefix ', '2', '', 's'),
  2386. ('xxx', '0', '^+10.3f', None),
  2387. ('', 'obj.attr', '', 's'),
  2388. (' ', 'z[0]', '10', 's'),
  2389. ])
  2390. formatter = parse("prefix {} suffix")
  2391. self.assertEqual(formatter, [
  2392. ('prefix ', '', '', None),
  2393. (' suffix', None, None, None),
  2394. ])
  2395. formatter = parse("str")
  2396. self.assertEqual(formatter, [
  2397. ('str', None, None, None),
  2398. ])
  2399. formatter = parse("")
  2400. self.assertEqual(formatter, [])
  2401. formatter = parse("{0}")
  2402. self.assertEqual(formatter, [
  2403. ('', '0', '', None),
  2404. ])
  2405. self.assertRaises(TypeError, _string.formatter_parser, 1)
  2406. def test_formatter_field_name_split(self):
  2407. def split(name):
  2408. items = list(_string.formatter_field_name_split(name))
  2409. items[1] = list(items[1])
  2410. return items
  2411. self.assertEqual(split("obj"), ["obj", []])
  2412. self.assertEqual(split("obj.arg"), ["obj", [(True, 'arg')]])
  2413. self.assertEqual(split("obj[key]"), ["obj", [(False, 'key')]])
  2414. self.assertEqual(split("obj.arg[key1][key2]"), [
  2415. "obj",
  2416. [(True, 'arg'),
  2417. (False, 'key1'),
  2418. (False, 'key2'),
  2419. ]])
  2420. self.assertRaises(TypeError, _string.formatter_field_name_split, 1)
  2421. def test_str_subclass_attr(self):
  2422. name = StrSubclass("name")
  2423. name2 = StrSubclass("name2")
  2424. class Bag:
  2425. pass
  2426. o = Bag()
  2427. with self.assertRaises(AttributeError):
  2428. delattr(o, name)
  2429. setattr(o, name, 1)
  2430. self.assertEqual(o.name, 1)
  2431. o.name = 2
  2432. self.assertEqual(list(o.__dict__), [name])
  2433. with self.assertRaises(AttributeError):
  2434. delattr(o, name2)
  2435. with self.assertRaises(AttributeError):
  2436. del o.name2
  2437. setattr(o, name2, 3)
  2438. self.assertEqual(o.name2, 3)
  2439. o.name2 = 4
  2440. self.assertEqual(list(o.__dict__), [name, name2])
  2441. if __name__ == "__main__":
  2442. unittest.main()