string_tests.py 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489
  1. """
  2. Common tests shared by test_unicode, test_userstring and test_bytes.
  3. """
  4. import unittest, string, sys, struct
  5. from test import support
  6. from test.support import import_helper
  7. from collections import UserList
  8. import random
  9. class Sequence:
  10. def __init__(self, seq='wxyz'): self.seq = seq
  11. def __len__(self): return len(self.seq)
  12. def __getitem__(self, i): return self.seq[i]
  13. class BadSeq1(Sequence):
  14. def __init__(self): self.seq = [7, 'hello', 123]
  15. def __str__(self): return '{0} {1} {2}'.format(*self.seq)
  16. class BadSeq2(Sequence):
  17. def __init__(self): self.seq = ['a', 'b', 'c']
  18. def __len__(self): return 8
  19. class BaseTest:
  20. # These tests are for buffers of values (bytes) and not
  21. # specific to character interpretation, used for bytes objects
  22. # and various string implementations
  23. # The type to be tested
  24. # Change in subclasses to change the behaviour of fixtesttype()
  25. type2test = None
  26. # Whether the "contained items" of the container are integers in
  27. # range(0, 256) (i.e. bytes, bytearray) or strings of length 1
  28. # (str)
  29. contains_bytes = False
  30. # All tests pass their arguments to the testing methods
  31. # as str objects. fixtesttype() can be used to propagate
  32. # these arguments to the appropriate type
  33. def fixtype(self, obj):
  34. if isinstance(obj, str):
  35. return self.__class__.type2test(obj)
  36. elif isinstance(obj, list):
  37. return [self.fixtype(x) for x in obj]
  38. elif isinstance(obj, tuple):
  39. return tuple([self.fixtype(x) for x in obj])
  40. elif isinstance(obj, dict):
  41. return dict([
  42. (self.fixtype(key), self.fixtype(value))
  43. for (key, value) in obj.items()
  44. ])
  45. else:
  46. return obj
  47. def test_fixtype(self):
  48. self.assertIs(type(self.fixtype("123")), self.type2test)
  49. # check that obj.method(*args) returns result
  50. def checkequal(self, result, obj, methodname, *args, **kwargs):
  51. result = self.fixtype(result)
  52. obj = self.fixtype(obj)
  53. args = self.fixtype(args)
  54. kwargs = {k: self.fixtype(v) for k,v in kwargs.items()}
  55. realresult = getattr(obj, methodname)(*args, **kwargs)
  56. self.assertEqual(
  57. result,
  58. realresult
  59. )
  60. # if the original is returned make sure that
  61. # this doesn't happen with subclasses
  62. if obj is realresult:
  63. try:
  64. class subtype(self.__class__.type2test):
  65. pass
  66. except TypeError:
  67. pass # Skip this if we can't subclass
  68. else:
  69. obj = subtype(obj)
  70. realresult = getattr(obj, methodname)(*args)
  71. self.assertIsNot(obj, realresult)
  72. # check that obj.method(*args) raises exc
  73. def checkraises(self, exc, obj, methodname, *args, expected_msg=None):
  74. obj = self.fixtype(obj)
  75. args = self.fixtype(args)
  76. with self.assertRaises(exc) as cm:
  77. getattr(obj, methodname)(*args)
  78. self.assertNotEqual(str(cm.exception), '')
  79. if expected_msg is not None:
  80. self.assertEqual(str(cm.exception), expected_msg)
  81. # call obj.method(*args) without any checks
  82. def checkcall(self, obj, methodname, *args):
  83. obj = self.fixtype(obj)
  84. args = self.fixtype(args)
  85. getattr(obj, methodname)(*args)
  86. def test_count(self):
  87. self.checkequal(3, 'aaa', 'count', 'a')
  88. self.checkequal(0, 'aaa', 'count', 'b')
  89. self.checkequal(3, 'aaa', 'count', 'a')
  90. self.checkequal(0, 'aaa', 'count', 'b')
  91. self.checkequal(3, 'aaa', 'count', 'a')
  92. self.checkequal(0, 'aaa', 'count', 'b')
  93. self.checkequal(0, 'aaa', 'count', 'b')
  94. self.checkequal(2, 'aaa', 'count', 'a', 1)
  95. self.checkequal(0, 'aaa', 'count', 'a', 10)
  96. self.checkequal(1, 'aaa', 'count', 'a', -1)
  97. self.checkequal(3, 'aaa', 'count', 'a', -10)
  98. self.checkequal(1, 'aaa', 'count', 'a', 0, 1)
  99. self.checkequal(3, 'aaa', 'count', 'a', 0, 10)
  100. self.checkequal(2, 'aaa', 'count', 'a', 0, -1)
  101. self.checkequal(0, 'aaa', 'count', 'a', 0, -10)
  102. self.checkequal(3, 'aaa', 'count', '', 1)
  103. self.checkequal(1, 'aaa', 'count', '', 3)
  104. self.checkequal(0, 'aaa', 'count', '', 10)
  105. self.checkequal(2, 'aaa', 'count', '', -1)
  106. self.checkequal(4, 'aaa', 'count', '', -10)
  107. self.checkequal(1, '', 'count', '')
  108. self.checkequal(0, '', 'count', '', 1, 1)
  109. self.checkequal(0, '', 'count', '', sys.maxsize, 0)
  110. self.checkequal(0, '', 'count', 'xx')
  111. self.checkequal(0, '', 'count', 'xx', 1, 1)
  112. self.checkequal(0, '', 'count', 'xx', sys.maxsize, 0)
  113. self.checkraises(TypeError, 'hello', 'count')
  114. if self.contains_bytes:
  115. self.checkequal(0, 'hello', 'count', 42)
  116. else:
  117. self.checkraises(TypeError, 'hello', 'count', 42)
  118. # For a variety of combinations,
  119. # verify that str.count() matches an equivalent function
  120. # replacing all occurrences and then differencing the string lengths
  121. charset = ['', 'a', 'b']
  122. digits = 7
  123. base = len(charset)
  124. teststrings = set()
  125. for i in range(base ** digits):
  126. entry = []
  127. for j in range(digits):
  128. i, m = divmod(i, base)
  129. entry.append(charset[m])
  130. teststrings.add(''.join(entry))
  131. teststrings = [self.fixtype(ts) for ts in teststrings]
  132. for i in teststrings:
  133. n = len(i)
  134. for j in teststrings:
  135. r1 = i.count(j)
  136. if j:
  137. r2, rem = divmod(n - len(i.replace(j, self.fixtype(''))),
  138. len(j))
  139. else:
  140. r2, rem = len(i)+1, 0
  141. if rem or r1 != r2:
  142. self.assertEqual(rem, 0, '%s != 0 for %s' % (rem, i))
  143. self.assertEqual(r1, r2, '%s != %s for %s' % (r1, r2, i))
  144. def test_find(self):
  145. self.checkequal(0, 'abcdefghiabc', 'find', 'abc')
  146. self.checkequal(9, 'abcdefghiabc', 'find', 'abc', 1)
  147. self.checkequal(-1, 'abcdefghiabc', 'find', 'def', 4)
  148. self.checkequal(0, 'abc', 'find', '', 0)
  149. self.checkequal(3, 'abc', 'find', '', 3)
  150. self.checkequal(-1, 'abc', 'find', '', 4)
  151. # to check the ability to pass None as defaults
  152. self.checkequal( 2, 'rrarrrrrrrrra', 'find', 'a')
  153. self.checkequal(12, 'rrarrrrrrrrra', 'find', 'a', 4)
  154. self.checkequal(-1, 'rrarrrrrrrrra', 'find', 'a', 4, 6)
  155. self.checkequal(12, 'rrarrrrrrrrra', 'find', 'a', 4, None)
  156. self.checkequal( 2, 'rrarrrrrrrrra', 'find', 'a', None, 6)
  157. self.checkraises(TypeError, 'hello', 'find')
  158. if self.contains_bytes:
  159. self.checkequal(-1, 'hello', 'find', 42)
  160. else:
  161. self.checkraises(TypeError, 'hello', 'find', 42)
  162. self.checkequal(0, '', 'find', '')
  163. self.checkequal(-1, '', 'find', '', 1, 1)
  164. self.checkequal(-1, '', 'find', '', sys.maxsize, 0)
  165. self.checkequal(-1, '', 'find', 'xx')
  166. self.checkequal(-1, '', 'find', 'xx', 1, 1)
  167. self.checkequal(-1, '', 'find', 'xx', sys.maxsize, 0)
  168. # issue 7458
  169. self.checkequal(-1, 'ab', 'find', 'xxx', sys.maxsize + 1, 0)
  170. # For a variety of combinations,
  171. # verify that str.find() matches __contains__
  172. # and that the found substring is really at that location
  173. charset = ['', 'a', 'b', 'c']
  174. digits = 5
  175. base = len(charset)
  176. teststrings = set()
  177. for i in range(base ** digits):
  178. entry = []
  179. for j in range(digits):
  180. i, m = divmod(i, base)
  181. entry.append(charset[m])
  182. teststrings.add(''.join(entry))
  183. teststrings = [self.fixtype(ts) for ts in teststrings]
  184. for i in teststrings:
  185. for j in teststrings:
  186. loc = i.find(j)
  187. r1 = (loc != -1)
  188. r2 = j in i
  189. self.assertEqual(r1, r2)
  190. if loc != -1:
  191. self.assertEqual(i[loc:loc+len(j)], j)
  192. def test_rfind(self):
  193. self.checkequal(9, 'abcdefghiabc', 'rfind', 'abc')
  194. self.checkequal(12, 'abcdefghiabc', 'rfind', '')
  195. self.checkequal(0, 'abcdefghiabc', 'rfind', 'abcd')
  196. self.checkequal(-1, 'abcdefghiabc', 'rfind', 'abcz')
  197. self.checkequal(3, 'abc', 'rfind', '', 0)
  198. self.checkequal(3, 'abc', 'rfind', '', 3)
  199. self.checkequal(-1, 'abc', 'rfind', '', 4)
  200. # to check the ability to pass None as defaults
  201. self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a')
  202. self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a', 4)
  203. self.checkequal(-1, 'rrarrrrrrrrra', 'rfind', 'a', 4, 6)
  204. self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a', 4, None)
  205. self.checkequal( 2, 'rrarrrrrrrrra', 'rfind', 'a', None, 6)
  206. self.checkraises(TypeError, 'hello', 'rfind')
  207. if self.contains_bytes:
  208. self.checkequal(-1, 'hello', 'rfind', 42)
  209. else:
  210. self.checkraises(TypeError, 'hello', 'rfind', 42)
  211. # For a variety of combinations,
  212. # verify that str.rfind() matches __contains__
  213. # and that the found substring is really at that location
  214. charset = ['', 'a', 'b', 'c']
  215. digits = 5
  216. base = len(charset)
  217. teststrings = set()
  218. for i in range(base ** digits):
  219. entry = []
  220. for j in range(digits):
  221. i, m = divmod(i, base)
  222. entry.append(charset[m])
  223. teststrings.add(''.join(entry))
  224. teststrings = [self.fixtype(ts) for ts in teststrings]
  225. for i in teststrings:
  226. for j in teststrings:
  227. loc = i.rfind(j)
  228. r1 = (loc != -1)
  229. r2 = j in i
  230. self.assertEqual(r1, r2)
  231. if loc != -1:
  232. self.assertEqual(i[loc:loc+len(j)], j)
  233. # issue 7458
  234. self.checkequal(-1, 'ab', 'rfind', 'xxx', sys.maxsize + 1, 0)
  235. # issue #15534
  236. self.checkequal(0, '<......\u043c...', "rfind", "<")
  237. def test_index(self):
  238. self.checkequal(0, 'abcdefghiabc', 'index', '')
  239. self.checkequal(3, 'abcdefghiabc', 'index', 'def')
  240. self.checkequal(0, 'abcdefghiabc', 'index', 'abc')
  241. self.checkequal(9, 'abcdefghiabc', 'index', 'abc', 1)
  242. self.checkraises(ValueError, 'abcdefghiabc', 'index', 'hib')
  243. self.checkraises(ValueError, 'abcdefghiab', 'index', 'abc', 1)
  244. self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', 8)
  245. self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', -1)
  246. # to check the ability to pass None as defaults
  247. self.checkequal( 2, 'rrarrrrrrrrra', 'index', 'a')
  248. self.checkequal(12, 'rrarrrrrrrrra', 'index', 'a', 4)
  249. self.checkraises(ValueError, 'rrarrrrrrrrra', 'index', 'a', 4, 6)
  250. self.checkequal(12, 'rrarrrrrrrrra', 'index', 'a', 4, None)
  251. self.checkequal( 2, 'rrarrrrrrrrra', 'index', 'a', None, 6)
  252. self.checkraises(TypeError, 'hello', 'index')
  253. if self.contains_bytes:
  254. self.checkraises(ValueError, 'hello', 'index', 42)
  255. else:
  256. self.checkraises(TypeError, 'hello', 'index', 42)
  257. def test_rindex(self):
  258. self.checkequal(12, 'abcdefghiabc', 'rindex', '')
  259. self.checkequal(3, 'abcdefghiabc', 'rindex', 'def')
  260. self.checkequal(9, 'abcdefghiabc', 'rindex', 'abc')
  261. self.checkequal(0, 'abcdefghiabc', 'rindex', 'abc', 0, -1)
  262. self.checkraises(ValueError, 'abcdefghiabc', 'rindex', 'hib')
  263. self.checkraises(ValueError, 'defghiabc', 'rindex', 'def', 1)
  264. self.checkraises(ValueError, 'defghiabc', 'rindex', 'abc', 0, -1)
  265. self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, 8)
  266. self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, -1)
  267. # to check the ability to pass None as defaults
  268. self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a')
  269. self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a', 4)
  270. self.checkraises(ValueError, 'rrarrrrrrrrra', 'rindex', 'a', 4, 6)
  271. self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a', 4, None)
  272. self.checkequal( 2, 'rrarrrrrrrrra', 'rindex', 'a', None, 6)
  273. self.checkraises(TypeError, 'hello', 'rindex')
  274. if self.contains_bytes:
  275. self.checkraises(ValueError, 'hello', 'rindex', 42)
  276. else:
  277. self.checkraises(TypeError, 'hello', 'rindex', 42)
  278. def test_find_periodic_pattern(self):
  279. """Cover the special path for periodic patterns."""
  280. def reference_find(p, s):
  281. for i in range(len(s)):
  282. if s.startswith(p, i):
  283. return i
  284. return -1
  285. rr = random.randrange
  286. choices = random.choices
  287. for _ in range(1000):
  288. p0 = ''.join(choices('abcde', k=rr(10))) * rr(10, 20)
  289. p = p0[:len(p0) - rr(10)] # pop off some characters
  290. left = ''.join(choices('abcdef', k=rr(2000)))
  291. right = ''.join(choices('abcdef', k=rr(2000)))
  292. text = left + p + right
  293. with self.subTest(p=p, text=text):
  294. self.checkequal(reference_find(p, text),
  295. text, 'find', p)
  296. def test_find_shift_table_overflow(self):
  297. """When the table of 8-bit shifts overflows."""
  298. N = 2**8 + 100
  299. # first check the periodic case
  300. # here, the shift for 'b' is N + 1.
  301. pattern1 = 'a' * N + 'b' + 'a' * N
  302. text1 = 'babbaa' * N + pattern1
  303. self.checkequal(len(text1)-len(pattern1),
  304. text1, 'find', pattern1)
  305. # now check the non-periodic case
  306. # here, the shift for 'd' is 3*(N+1)+1
  307. pattern2 = 'ddd' + 'abc' * N + "eee"
  308. text2 = pattern2[:-1] + "ddeede" * 2 * N + pattern2 + "de" * N
  309. self.checkequal(len(text2) - N*len("de") - len(pattern2),
  310. text2, 'find', pattern2)
  311. def test_lower(self):
  312. self.checkequal('hello', 'HeLLo', 'lower')
  313. self.checkequal('hello', 'hello', 'lower')
  314. self.checkraises(TypeError, 'hello', 'lower', 42)
  315. def test_upper(self):
  316. self.checkequal('HELLO', 'HeLLo', 'upper')
  317. self.checkequal('HELLO', 'HELLO', 'upper')
  318. self.checkraises(TypeError, 'hello', 'upper', 42)
  319. def test_expandtabs(self):
  320. self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi',
  321. 'expandtabs')
  322. self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi',
  323. 'expandtabs', 8)
  324. self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi',
  325. 'expandtabs', 4)
  326. self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi',
  327. 'expandtabs')
  328. self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi',
  329. 'expandtabs', 8)
  330. self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi',
  331. 'expandtabs', 4)
  332. self.checkequal('abc\r\nab\r\ndef\ng\r\nhi', 'abc\r\nab\r\ndef\ng\r\nhi',
  333. 'expandtabs', 4)
  334. # check keyword args
  335. self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi',
  336. 'expandtabs', tabsize=8)
  337. self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi',
  338. 'expandtabs', tabsize=4)
  339. self.checkequal(' a\n b', ' \ta\n\tb', 'expandtabs', 1)
  340. self.checkraises(TypeError, 'hello', 'expandtabs', 42, 42)
  341. # This test is only valid when sizeof(int) == sizeof(void*) == 4.
  342. if sys.maxsize < (1 << 32) and struct.calcsize('P') == 4:
  343. self.checkraises(OverflowError,
  344. '\ta\n\tb', 'expandtabs', sys.maxsize)
  345. def test_split(self):
  346. # by a char
  347. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|')
  348. self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
  349. self.checkequal(['a', 'b|c|d'], 'a|b|c|d', 'split', '|', 1)
  350. self.checkequal(['a', 'b', 'c|d'], 'a|b|c|d', 'split', '|', 2)
  351. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 3)
  352. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 4)
  353. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|',
  354. sys.maxsize-2)
  355. self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
  356. self.checkequal(['a', '', 'b||c||d'], 'a||b||c||d', 'split', '|', 2)
  357. self.checkequal(['abcd'], 'abcd', 'split', '|')
  358. self.checkequal([''], '', 'split', '|')
  359. self.checkequal(['endcase ', ''], 'endcase |', 'split', '|')
  360. self.checkequal(['', ' startcase'], '| startcase', 'split', '|')
  361. self.checkequal(['', 'bothcase', ''], '|bothcase|', 'split', '|')
  362. self.checkequal(['a', '', 'b\x00c\x00d'], 'a\x00\x00b\x00c\x00d', 'split', '\x00', 2)
  363. self.checkequal(['a']*20, ('a|'*20)[:-1], 'split', '|')
  364. self.checkequal(['a']*15 +['a|a|a|a|a'],
  365. ('a|'*20)[:-1], 'split', '|', 15)
  366. # by string
  367. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//')
  368. self.checkequal(['a', 'b//c//d'], 'a//b//c//d', 'split', '//', 1)
  369. self.checkequal(['a', 'b', 'c//d'], 'a//b//c//d', 'split', '//', 2)
  370. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 3)
  371. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 4)
  372. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//',
  373. sys.maxsize-10)
  374. self.checkequal(['a//b//c//d'], 'a//b//c//d', 'split', '//', 0)
  375. self.checkequal(['a', '', 'b////c////d'], 'a////b////c////d', 'split', '//', 2)
  376. self.checkequal(['endcase ', ''], 'endcase test', 'split', 'test')
  377. self.checkequal(['', ' begincase'], 'test begincase', 'split', 'test')
  378. self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
  379. 'split', 'test')
  380. self.checkequal(['a', 'bc'], 'abbbc', 'split', 'bb')
  381. self.checkequal(['', ''], 'aaa', 'split', 'aaa')
  382. self.checkequal(['aaa'], 'aaa', 'split', 'aaa', 0)
  383. self.checkequal(['ab', 'ab'], 'abbaab', 'split', 'ba')
  384. self.checkequal(['aaaa'], 'aaaa', 'split', 'aab')
  385. self.checkequal([''], '', 'split', 'aaa')
  386. self.checkequal(['aa'], 'aa', 'split', 'aaa')
  387. self.checkequal(['A', 'bobb'], 'Abbobbbobb', 'split', 'bbobb')
  388. self.checkequal(['A', 'B', ''], 'AbbobbBbbobb', 'split', 'bbobb')
  389. self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH')
  390. self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH', 19)
  391. self.checkequal(['a']*18 + ['aBLAHa'], ('aBLAH'*20)[:-4],
  392. 'split', 'BLAH', 18)
  393. # with keyword args
  394. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', sep='|')
  395. self.checkequal(['a', 'b|c|d'],
  396. 'a|b|c|d', 'split', '|', maxsplit=1)
  397. self.checkequal(['a', 'b|c|d'],
  398. 'a|b|c|d', 'split', sep='|', maxsplit=1)
  399. self.checkequal(['a', 'b|c|d'],
  400. 'a|b|c|d', 'split', maxsplit=1, sep='|')
  401. self.checkequal(['a', 'b c d'],
  402. 'a b c d', 'split', maxsplit=1)
  403. # argument type
  404. self.checkraises(TypeError, 'hello', 'split', 42, 42, 42)
  405. # null case
  406. self.checkraises(ValueError, 'hello', 'split', '')
  407. self.checkraises(ValueError, 'hello', 'split', '', 0)
  408. def test_rsplit(self):
  409. # without arg
  410. self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit')
  411. self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit')
  412. self.checkequal([], '', 'rsplit')
  413. # by a char
  414. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|')
  415. self.checkequal(['a|b|c', 'd'], 'a|b|c|d', 'rsplit', '|', 1)
  416. self.checkequal(['a|b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 2)
  417. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 3)
  418. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 4)
  419. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|',
  420. sys.maxsize-100)
  421. self.checkequal(['a|b|c|d'], 'a|b|c|d', 'rsplit', '|', 0)
  422. self.checkequal(['a||b||c', '', 'd'], 'a||b||c||d', 'rsplit', '|', 2)
  423. self.checkequal(['abcd'], 'abcd', 'rsplit', '|')
  424. self.checkequal([''], '', 'rsplit', '|')
  425. self.checkequal(['', ' begincase'], '| begincase', 'rsplit', '|')
  426. self.checkequal(['endcase ', ''], 'endcase |', 'rsplit', '|')
  427. self.checkequal(['', 'bothcase', ''], '|bothcase|', 'rsplit', '|')
  428. self.checkequal(['a\x00\x00b', 'c', 'd'], 'a\x00\x00b\x00c\x00d', 'rsplit', '\x00', 2)
  429. self.checkequal(['a']*20, ('a|'*20)[:-1], 'rsplit', '|')
  430. self.checkequal(['a|a|a|a|a']+['a']*15,
  431. ('a|'*20)[:-1], 'rsplit', '|', 15)
  432. # by string
  433. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//')
  434. self.checkequal(['a//b//c', 'd'], 'a//b//c//d', 'rsplit', '//', 1)
  435. self.checkequal(['a//b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 2)
  436. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 3)
  437. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 4)
  438. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//',
  439. sys.maxsize-5)
  440. self.checkequal(['a//b//c//d'], 'a//b//c//d', 'rsplit', '//', 0)
  441. self.checkequal(['a////b////c', '', 'd'], 'a////b////c////d', 'rsplit', '//', 2)
  442. self.checkequal(['', ' begincase'], 'test begincase', 'rsplit', 'test')
  443. self.checkequal(['endcase ', ''], 'endcase test', 'rsplit', 'test')
  444. self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
  445. 'rsplit', 'test')
  446. self.checkequal(['ab', 'c'], 'abbbc', 'rsplit', 'bb')
  447. self.checkequal(['', ''], 'aaa', 'rsplit', 'aaa')
  448. self.checkequal(['aaa'], 'aaa', 'rsplit', 'aaa', 0)
  449. self.checkequal(['ab', 'ab'], 'abbaab', 'rsplit', 'ba')
  450. self.checkequal(['aaaa'], 'aaaa', 'rsplit', 'aab')
  451. self.checkequal([''], '', 'rsplit', 'aaa')
  452. self.checkequal(['aa'], 'aa', 'rsplit', 'aaa')
  453. self.checkequal(['bbob', 'A'], 'bbobbbobbA', 'rsplit', 'bbobb')
  454. self.checkequal(['', 'B', 'A'], 'bbobbBbbobbA', 'rsplit', 'bbobb')
  455. self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH')
  456. self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH', 19)
  457. self.checkequal(['aBLAHa'] + ['a']*18, ('aBLAH'*20)[:-4],
  458. 'rsplit', 'BLAH', 18)
  459. # with keyword args
  460. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', sep='|')
  461. self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', sep=None)
  462. self.checkequal(['a b c', 'd'],
  463. 'a b c d', 'rsplit', sep=None, maxsplit=1)
  464. self.checkequal(['a|b|c', 'd'],
  465. 'a|b|c|d', 'rsplit', '|', maxsplit=1)
  466. self.checkequal(['a|b|c', 'd'],
  467. 'a|b|c|d', 'rsplit', sep='|', maxsplit=1)
  468. self.checkequal(['a|b|c', 'd'],
  469. 'a|b|c|d', 'rsplit', maxsplit=1, sep='|')
  470. self.checkequal(['a b c', 'd'],
  471. 'a b c d', 'rsplit', maxsplit=1)
  472. # argument type
  473. self.checkraises(TypeError, 'hello', 'rsplit', 42, 42, 42)
  474. # null case
  475. self.checkraises(ValueError, 'hello', 'rsplit', '')
  476. self.checkraises(ValueError, 'hello', 'rsplit', '', 0)
  477. def test_replace(self):
  478. EQ = self.checkequal
  479. # Operations on the empty string
  480. EQ("", "", "replace", "", "")
  481. EQ("A", "", "replace", "", "A")
  482. EQ("", "", "replace", "A", "")
  483. EQ("", "", "replace", "A", "A")
  484. EQ("", "", "replace", "", "", 100)
  485. EQ("A", "", "replace", "", "A", 100)
  486. EQ("", "", "replace", "", "", sys.maxsize)
  487. # interleave (from=="", 'to' gets inserted everywhere)
  488. EQ("A", "A", "replace", "", "")
  489. EQ("*A*", "A", "replace", "", "*")
  490. EQ("*1A*1", "A", "replace", "", "*1")
  491. EQ("*-#A*-#", "A", "replace", "", "*-#")
  492. EQ("*-A*-A*-", "AA", "replace", "", "*-")
  493. EQ("*-A*-A*-", "AA", "replace", "", "*-", -1)
  494. EQ("*-A*-A*-", "AA", "replace", "", "*-", sys.maxsize)
  495. EQ("*-A*-A*-", "AA", "replace", "", "*-", 4)
  496. EQ("*-A*-A*-", "AA", "replace", "", "*-", 3)
  497. EQ("*-A*-A", "AA", "replace", "", "*-", 2)
  498. EQ("*-AA", "AA", "replace", "", "*-", 1)
  499. EQ("AA", "AA", "replace", "", "*-", 0)
  500. # single character deletion (from=="A", to=="")
  501. EQ("", "A", "replace", "A", "")
  502. EQ("", "AAA", "replace", "A", "")
  503. EQ("", "AAA", "replace", "A", "", -1)
  504. EQ("", "AAA", "replace", "A", "", sys.maxsize)
  505. EQ("", "AAA", "replace", "A", "", 4)
  506. EQ("", "AAA", "replace", "A", "", 3)
  507. EQ("A", "AAA", "replace", "A", "", 2)
  508. EQ("AA", "AAA", "replace", "A", "", 1)
  509. EQ("AAA", "AAA", "replace", "A", "", 0)
  510. EQ("", "AAAAAAAAAA", "replace", "A", "")
  511. EQ("BCD", "ABACADA", "replace", "A", "")
  512. EQ("BCD", "ABACADA", "replace", "A", "", -1)
  513. EQ("BCD", "ABACADA", "replace", "A", "", sys.maxsize)
  514. EQ("BCD", "ABACADA", "replace", "A", "", 5)
  515. EQ("BCD", "ABACADA", "replace", "A", "", 4)
  516. EQ("BCDA", "ABACADA", "replace", "A", "", 3)
  517. EQ("BCADA", "ABACADA", "replace", "A", "", 2)
  518. EQ("BACADA", "ABACADA", "replace", "A", "", 1)
  519. EQ("ABACADA", "ABACADA", "replace", "A", "", 0)
  520. EQ("BCD", "ABCAD", "replace", "A", "")
  521. EQ("BCD", "ABCADAA", "replace", "A", "")
  522. EQ("BCD", "BCD", "replace", "A", "")
  523. EQ("*************", "*************", "replace", "A", "")
  524. EQ("^A^", "^"+"A"*1000+"^", "replace", "A", "", 999)
  525. # substring deletion (from=="the", to=="")
  526. EQ("", "the", "replace", "the", "")
  527. EQ("ater", "theater", "replace", "the", "")
  528. EQ("", "thethe", "replace", "the", "")
  529. EQ("", "thethethethe", "replace", "the", "")
  530. EQ("aaaa", "theatheatheathea", "replace", "the", "")
  531. EQ("that", "that", "replace", "the", "")
  532. EQ("thaet", "thaet", "replace", "the", "")
  533. EQ("here and re", "here and there", "replace", "the", "")
  534. EQ("here and re and re", "here and there and there",
  535. "replace", "the", "", sys.maxsize)
  536. EQ("here and re and re", "here and there and there",
  537. "replace", "the", "", -1)
  538. EQ("here and re and re", "here and there and there",
  539. "replace", "the", "", 3)
  540. EQ("here and re and re", "here and there and there",
  541. "replace", "the", "", 2)
  542. EQ("here and re and there", "here and there and there",
  543. "replace", "the", "", 1)
  544. EQ("here and there and there", "here and there and there",
  545. "replace", "the", "", 0)
  546. EQ("here and re and re", "here and there and there", "replace", "the", "")
  547. EQ("abc", "abc", "replace", "the", "")
  548. EQ("abcdefg", "abcdefg", "replace", "the", "")
  549. # substring deletion (from=="bob", to=="")
  550. EQ("bob", "bbobob", "replace", "bob", "")
  551. EQ("bobXbob", "bbobobXbbobob", "replace", "bob", "")
  552. EQ("aaaaaaa", "aaaaaaabob", "replace", "bob", "")
  553. EQ("aaaaaaa", "aaaaaaa", "replace", "bob", "")
  554. # single character replace in place (len(from)==len(to)==1)
  555. EQ("Who goes there?", "Who goes there?", "replace", "o", "o")
  556. EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O")
  557. EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", sys.maxsize)
  558. EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", -1)
  559. EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 3)
  560. EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 2)
  561. EQ("WhO goes there?", "Who goes there?", "replace", "o", "O", 1)
  562. EQ("Who goes there?", "Who goes there?", "replace", "o", "O", 0)
  563. EQ("Who goes there?", "Who goes there?", "replace", "a", "q")
  564. EQ("who goes there?", "Who goes there?", "replace", "W", "w")
  565. EQ("wwho goes there?ww", "WWho goes there?WW", "replace", "W", "w")
  566. EQ("Who goes there!", "Who goes there?", "replace", "?", "!")
  567. EQ("Who goes there!!", "Who goes there??", "replace", "?", "!")
  568. EQ("Who goes there?", "Who goes there?", "replace", ".", "!")
  569. # substring replace in place (len(from)==len(to) > 1)
  570. EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**")
  571. EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", sys.maxsize)
  572. EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", -1)
  573. EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 4)
  574. EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 3)
  575. EQ("Th** ** a tissue", "This is a tissue", "replace", "is", "**", 2)
  576. EQ("Th** is a tissue", "This is a tissue", "replace", "is", "**", 1)
  577. EQ("This is a tissue", "This is a tissue", "replace", "is", "**", 0)
  578. EQ("cobob", "bobob", "replace", "bob", "cob")
  579. EQ("cobobXcobocob", "bobobXbobobob", "replace", "bob", "cob")
  580. EQ("bobob", "bobob", "replace", "bot", "bot")
  581. # replace single character (len(from)==1, len(to)>1)
  582. EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK")
  583. EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", -1)
  584. EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", sys.maxsize)
  585. EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", 2)
  586. EQ("ReyKKjavik", "Reykjavik", "replace", "k", "KK", 1)
  587. EQ("Reykjavik", "Reykjavik", "replace", "k", "KK", 0)
  588. EQ("A----B----C----", "A.B.C.", "replace", ".", "----")
  589. # issue #15534
  590. EQ('...\u043c......&lt;', '...\u043c......<', "replace", "<", "&lt;")
  591. EQ("Reykjavik", "Reykjavik", "replace", "q", "KK")
  592. # replace substring (len(from)>1, len(to)!=len(from))
  593. EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
  594. "replace", "spam", "ham")
  595. EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
  596. "replace", "spam", "ham", sys.maxsize)
  597. EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
  598. "replace", "spam", "ham", -1)
  599. EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
  600. "replace", "spam", "ham", 4)
  601. EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
  602. "replace", "spam", "ham", 3)
  603. EQ("ham, ham, eggs and spam", "spam, spam, eggs and spam",
  604. "replace", "spam", "ham", 2)
  605. EQ("ham, spam, eggs and spam", "spam, spam, eggs and spam",
  606. "replace", "spam", "ham", 1)
  607. EQ("spam, spam, eggs and spam", "spam, spam, eggs and spam",
  608. "replace", "spam", "ham", 0)
  609. EQ("bobob", "bobobob", "replace", "bobob", "bob")
  610. EQ("bobobXbobob", "bobobobXbobobob", "replace", "bobob", "bob")
  611. EQ("BOBOBOB", "BOBOBOB", "replace", "bob", "bobby")
  612. self.checkequal('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1)
  613. self.checkequal('onetwothree', 'one!two!three!', 'replace', '!', '')
  614. self.checkequal('one@two@three!', 'one!two!three!', 'replace', '!', '@', 2)
  615. self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 3)
  616. self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 4)
  617. self.checkequal('one!two!three!', 'one!two!three!', 'replace', '!', '@', 0)
  618. self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@')
  619. self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@')
  620. self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@', 2)
  621. self.checkequal('-a-b-c-', 'abc', 'replace', '', '-')
  622. self.checkequal('-a-b-c', 'abc', 'replace', '', '-', 3)
  623. self.checkequal('abc', 'abc', 'replace', '', '-', 0)
  624. self.checkequal('', '', 'replace', '', '')
  625. self.checkequal('abc', 'abc', 'replace', 'ab', '--', 0)
  626. self.checkequal('abc', 'abc', 'replace', 'xy', '--')
  627. # Next three for SF bug 422088: [OSF1 alpha] string.replace(); died with
  628. # MemoryError due to empty result (platform malloc issue when requesting
  629. # 0 bytes).
  630. self.checkequal('', '123', 'replace', '123', '')
  631. self.checkequal('', '123123', 'replace', '123', '')
  632. self.checkequal('x', '123x123', 'replace', '123', '')
  633. self.checkraises(TypeError, 'hello', 'replace')
  634. self.checkraises(TypeError, 'hello', 'replace', 42)
  635. self.checkraises(TypeError, 'hello', 'replace', 42, 'h')
  636. self.checkraises(TypeError, 'hello', 'replace', 'h', 42)
  637. @unittest.skipIf(sys.maxsize > (1 << 32) or struct.calcsize('P') != 4,
  638. 'only applies to 32-bit platforms')
  639. def test_replace_overflow(self):
  640. # Check for overflow checking on 32 bit machines
  641. A2_16 = "A" * (2**16)
  642. self.checkraises(OverflowError, A2_16, "replace", "", A2_16)
  643. self.checkraises(OverflowError, A2_16, "replace", "A", A2_16)
  644. self.checkraises(OverflowError, A2_16, "replace", "AA", A2_16+A2_16)
  645. def test_removeprefix(self):
  646. self.checkequal('am', 'spam', 'removeprefix', 'sp')
  647. self.checkequal('spamspam', 'spamspamspam', 'removeprefix', 'spam')
  648. self.checkequal('spam', 'spam', 'removeprefix', 'python')
  649. self.checkequal('spam', 'spam', 'removeprefix', 'spider')
  650. self.checkequal('spam', 'spam', 'removeprefix', 'spam and eggs')
  651. self.checkequal('', '', 'removeprefix', '')
  652. self.checkequal('', '', 'removeprefix', 'abcde')
  653. self.checkequal('abcde', 'abcde', 'removeprefix', '')
  654. self.checkequal('', 'abcde', 'removeprefix', 'abcde')
  655. self.checkraises(TypeError, 'hello', 'removeprefix')
  656. self.checkraises(TypeError, 'hello', 'removeprefix', 42)
  657. self.checkraises(TypeError, 'hello', 'removeprefix', 42, 'h')
  658. self.checkraises(TypeError, 'hello', 'removeprefix', 'h', 42)
  659. self.checkraises(TypeError, 'hello', 'removeprefix', ("he", "l"))
  660. def test_removesuffix(self):
  661. self.checkequal('sp', 'spam', 'removesuffix', 'am')
  662. self.checkequal('spamspam', 'spamspamspam', 'removesuffix', 'spam')
  663. self.checkequal('spam', 'spam', 'removesuffix', 'python')
  664. self.checkequal('spam', 'spam', 'removesuffix', 'blam')
  665. self.checkequal('spam', 'spam', 'removesuffix', 'eggs and spam')
  666. self.checkequal('', '', 'removesuffix', '')
  667. self.checkequal('', '', 'removesuffix', 'abcde')
  668. self.checkequal('abcde', 'abcde', 'removesuffix', '')
  669. self.checkequal('', 'abcde', 'removesuffix', 'abcde')
  670. self.checkraises(TypeError, 'hello', 'removesuffix')
  671. self.checkraises(TypeError, 'hello', 'removesuffix', 42)
  672. self.checkraises(TypeError, 'hello', 'removesuffix', 42, 'h')
  673. self.checkraises(TypeError, 'hello', 'removesuffix', 'h', 42)
  674. self.checkraises(TypeError, 'hello', 'removesuffix', ("lo", "l"))
  675. def test_capitalize(self):
  676. self.checkequal(' hello ', ' hello ', 'capitalize')
  677. self.checkequal('Hello ', 'Hello ','capitalize')
  678. self.checkequal('Hello ', 'hello ','capitalize')
  679. self.checkequal('Aaaa', 'aaaa', 'capitalize')
  680. self.checkequal('Aaaa', 'AaAa', 'capitalize')
  681. self.checkraises(TypeError, 'hello', 'capitalize', 42)
  682. def test_additional_split(self):
  683. self.checkequal(['this', 'is', 'the', 'split', 'function'],
  684. 'this is the split function', 'split')
  685. # by whitespace
  686. self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'split')
  687. self.checkequal(['a', 'b c d'], 'a b c d', 'split', None, 1)
  688. self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
  689. self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 3)
  690. self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 4)
  691. self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None,
  692. sys.maxsize-1)
  693. self.checkequal(['a b c d'], 'a b c d', 'split', None, 0)
  694. self.checkequal(['a b c d'], ' a b c d', 'split', None, 0)
  695. self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
  696. self.checkequal([], ' ', 'split')
  697. self.checkequal(['a'], ' a ', 'split')
  698. self.checkequal(['a', 'b'], ' a b ', 'split')
  699. self.checkequal(['a', 'b '], ' a b ', 'split', None, 1)
  700. self.checkequal(['a b c '], ' a b c ', 'split', None, 0)
  701. self.checkequal(['a', 'b c '], ' a b c ', 'split', None, 1)
  702. self.checkequal(['a', 'b', 'c '], ' a b c ', 'split', None, 2)
  703. self.checkequal(['a', 'b', 'c'], ' a b c ', 'split', None, 3)
  704. self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'split')
  705. aaa = ' a '*20
  706. self.checkequal(['a']*20, aaa, 'split')
  707. self.checkequal(['a'] + [aaa[4:]], aaa, 'split', None, 1)
  708. self.checkequal(['a']*19 + ['a '], aaa, 'split', None, 19)
  709. for b in ('arf\tbarf', 'arf\nbarf', 'arf\rbarf',
  710. 'arf\fbarf', 'arf\vbarf'):
  711. self.checkequal(['arf', 'barf'], b, 'split')
  712. self.checkequal(['arf', 'barf'], b, 'split', None)
  713. self.checkequal(['arf', 'barf'], b, 'split', None, 2)
  714. def test_additional_rsplit(self):
  715. self.checkequal(['this', 'is', 'the', 'rsplit', 'function'],
  716. 'this is the rsplit function', 'rsplit')
  717. # by whitespace
  718. self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'rsplit')
  719. self.checkequal(['a b c', 'd'], 'a b c d', 'rsplit', None, 1)
  720. self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
  721. self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 3)
  722. self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 4)
  723. self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None,
  724. sys.maxsize-20)
  725. self.checkequal(['a b c d'], 'a b c d', 'rsplit', None, 0)
  726. self.checkequal(['a b c d'], 'a b c d ', 'rsplit', None, 0)
  727. self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
  728. self.checkequal([], ' ', 'rsplit')
  729. self.checkequal(['a'], ' a ', 'rsplit')
  730. self.checkequal(['a', 'b'], ' a b ', 'rsplit')
  731. self.checkequal([' a', 'b'], ' a b ', 'rsplit', None, 1)
  732. self.checkequal([' a b c'], ' a b c ', 'rsplit',
  733. None, 0)
  734. self.checkequal([' a b','c'], ' a b c ', 'rsplit',
  735. None, 1)
  736. self.checkequal([' a', 'b', 'c'], ' a b c ', 'rsplit',
  737. None, 2)
  738. self.checkequal(['a', 'b', 'c'], ' a b c ', 'rsplit',
  739. None, 3)
  740. self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'rsplit', None, 88)
  741. aaa = ' a '*20
  742. self.checkequal(['a']*20, aaa, 'rsplit')
  743. self.checkequal([aaa[:-4]] + ['a'], aaa, 'rsplit', None, 1)
  744. self.checkequal([' a a'] + ['a']*18, aaa, 'rsplit', None, 18)
  745. for b in ('arf\tbarf', 'arf\nbarf', 'arf\rbarf',
  746. 'arf\fbarf', 'arf\vbarf'):
  747. self.checkequal(['arf', 'barf'], b, 'rsplit')
  748. self.checkequal(['arf', 'barf'], b, 'rsplit', None)
  749. self.checkequal(['arf', 'barf'], b, 'rsplit', None, 2)
  750. def test_strip_whitespace(self):
  751. self.checkequal('hello', ' hello ', 'strip')
  752. self.checkequal('hello ', ' hello ', 'lstrip')
  753. self.checkequal(' hello', ' hello ', 'rstrip')
  754. self.checkequal('hello', 'hello', 'strip')
  755. b = ' \t\n\r\f\vabc \t\n\r\f\v'
  756. self.checkequal('abc', b, 'strip')
  757. self.checkequal('abc \t\n\r\f\v', b, 'lstrip')
  758. self.checkequal(' \t\n\r\f\vabc', b, 'rstrip')
  759. # strip/lstrip/rstrip with None arg
  760. self.checkequal('hello', ' hello ', 'strip', None)
  761. self.checkequal('hello ', ' hello ', 'lstrip', None)
  762. self.checkequal(' hello', ' hello ', 'rstrip', None)
  763. self.checkequal('hello', 'hello', 'strip', None)
  764. def test_strip(self):
  765. # strip/lstrip/rstrip with str arg
  766. self.checkequal('hello', 'xyzzyhelloxyzzy', 'strip', 'xyz')
  767. self.checkequal('helloxyzzy', 'xyzzyhelloxyzzy', 'lstrip', 'xyz')
  768. self.checkequal('xyzzyhello', 'xyzzyhelloxyzzy', 'rstrip', 'xyz')
  769. self.checkequal('hello', 'hello', 'strip', 'xyz')
  770. self.checkequal('', 'mississippi', 'strip', 'mississippi')
  771. # only trim the start and end; does not strip internal characters
  772. self.checkequal('mississipp', 'mississippi', 'strip', 'i')
  773. self.checkraises(TypeError, 'hello', 'strip', 42, 42)
  774. self.checkraises(TypeError, 'hello', 'lstrip', 42, 42)
  775. self.checkraises(TypeError, 'hello', 'rstrip', 42, 42)
  776. def test_ljust(self):
  777. self.checkequal('abc ', 'abc', 'ljust', 10)
  778. self.checkequal('abc ', 'abc', 'ljust', 6)
  779. self.checkequal('abc', 'abc', 'ljust', 3)
  780. self.checkequal('abc', 'abc', 'ljust', 2)
  781. self.checkequal('abc*******', 'abc', 'ljust', 10, '*')
  782. self.checkraises(TypeError, 'abc', 'ljust')
  783. def test_rjust(self):
  784. self.checkequal(' abc', 'abc', 'rjust', 10)
  785. self.checkequal(' abc', 'abc', 'rjust', 6)
  786. self.checkequal('abc', 'abc', 'rjust', 3)
  787. self.checkequal('abc', 'abc', 'rjust', 2)
  788. self.checkequal('*******abc', 'abc', 'rjust', 10, '*')
  789. self.checkraises(TypeError, 'abc', 'rjust')
  790. def test_center(self):
  791. self.checkequal(' abc ', 'abc', 'center', 10)
  792. self.checkequal(' abc ', 'abc', 'center', 6)
  793. self.checkequal('abc', 'abc', 'center', 3)
  794. self.checkequal('abc', 'abc', 'center', 2)
  795. self.checkequal('***abc****', 'abc', 'center', 10, '*')
  796. self.checkraises(TypeError, 'abc', 'center')
  797. def test_swapcase(self):
  798. self.checkequal('hEllO CoMPuTErS', 'HeLLo cOmpUteRs', 'swapcase')
  799. self.checkraises(TypeError, 'hello', 'swapcase', 42)
  800. def test_zfill(self):
  801. self.checkequal('123', '123', 'zfill', 2)
  802. self.checkequal('123', '123', 'zfill', 3)
  803. self.checkequal('0123', '123', 'zfill', 4)
  804. self.checkequal('+123', '+123', 'zfill', 3)
  805. self.checkequal('+123', '+123', 'zfill', 4)
  806. self.checkequal('+0123', '+123', 'zfill', 5)
  807. self.checkequal('-123', '-123', 'zfill', 3)
  808. self.checkequal('-123', '-123', 'zfill', 4)
  809. self.checkequal('-0123', '-123', 'zfill', 5)
  810. self.checkequal('000', '', 'zfill', 3)
  811. self.checkequal('34', '34', 'zfill', 1)
  812. self.checkequal('0034', '34', 'zfill', 4)
  813. self.checkraises(TypeError, '123', 'zfill')
  814. def test_islower(self):
  815. self.checkequal(False, '', 'islower')
  816. self.checkequal(True, 'a', 'islower')
  817. self.checkequal(False, 'A', 'islower')
  818. self.checkequal(False, '\n', 'islower')
  819. self.checkequal(True, 'abc', 'islower')
  820. self.checkequal(False, 'aBc', 'islower')
  821. self.checkequal(True, 'abc\n', 'islower')
  822. self.checkraises(TypeError, 'abc', 'islower', 42)
  823. def test_isupper(self):
  824. self.checkequal(False, '', 'isupper')
  825. self.checkequal(False, 'a', 'isupper')
  826. self.checkequal(True, 'A', 'isupper')
  827. self.checkequal(False, '\n', 'isupper')
  828. self.checkequal(True, 'ABC', 'isupper')
  829. self.checkequal(False, 'AbC', 'isupper')
  830. self.checkequal(True, 'ABC\n', 'isupper')
  831. self.checkraises(TypeError, 'abc', 'isupper', 42)
  832. def test_istitle(self):
  833. self.checkequal(False, '', 'istitle')
  834. self.checkequal(False, 'a', 'istitle')
  835. self.checkequal(True, 'A', 'istitle')
  836. self.checkequal(False, '\n', 'istitle')
  837. self.checkequal(True, 'A Titlecased Line', 'istitle')
  838. self.checkequal(True, 'A\nTitlecased Line', 'istitle')
  839. self.checkequal(True, 'A Titlecased, Line', 'istitle')
  840. self.checkequal(False, 'Not a capitalized String', 'istitle')
  841. self.checkequal(False, 'Not\ta Titlecase String', 'istitle')
  842. self.checkequal(False, 'Not--a Titlecase String', 'istitle')
  843. self.checkequal(False, 'NOT', 'istitle')
  844. self.checkraises(TypeError, 'abc', 'istitle', 42)
  845. def test_isspace(self):
  846. self.checkequal(False, '', 'isspace')
  847. self.checkequal(False, 'a', 'isspace')
  848. self.checkequal(True, ' ', 'isspace')
  849. self.checkequal(True, '\t', 'isspace')
  850. self.checkequal(True, '\r', 'isspace')
  851. self.checkequal(True, '\n', 'isspace')
  852. self.checkequal(True, ' \t\r\n', 'isspace')
  853. self.checkequal(False, ' \t\r\na', 'isspace')
  854. self.checkraises(TypeError, 'abc', 'isspace', 42)
  855. def test_isalpha(self):
  856. self.checkequal(False, '', 'isalpha')
  857. self.checkequal(True, 'a', 'isalpha')
  858. self.checkequal(True, 'A', 'isalpha')
  859. self.checkequal(False, '\n', 'isalpha')
  860. self.checkequal(True, 'abc', 'isalpha')
  861. self.checkequal(False, 'aBc123', 'isalpha')
  862. self.checkequal(False, 'abc\n', 'isalpha')
  863. self.checkraises(TypeError, 'abc', 'isalpha', 42)
  864. def test_isalnum(self):
  865. self.checkequal(False, '', 'isalnum')
  866. self.checkequal(True, 'a', 'isalnum')
  867. self.checkequal(True, 'A', 'isalnum')
  868. self.checkequal(False, '\n', 'isalnum')
  869. self.checkequal(True, '123abc456', 'isalnum')
  870. self.checkequal(True, 'a1b3c', 'isalnum')
  871. self.checkequal(False, 'aBc000 ', 'isalnum')
  872. self.checkequal(False, 'abc\n', 'isalnum')
  873. self.checkraises(TypeError, 'abc', 'isalnum', 42)
  874. def test_isascii(self):
  875. self.checkequal(True, '', 'isascii')
  876. self.checkequal(True, '\x00', 'isascii')
  877. self.checkequal(True, '\x7f', 'isascii')
  878. self.checkequal(True, '\x00\x7f', 'isascii')
  879. self.checkequal(False, '\x80', 'isascii')
  880. self.checkequal(False, '\xe9', 'isascii')
  881. # bytes.isascii() and bytearray.isascii() has optimization which
  882. # check 4 or 8 bytes at once. So check some alignments.
  883. for p in range(8):
  884. self.checkequal(True, ' '*p + '\x7f', 'isascii')
  885. self.checkequal(False, ' '*p + '\x80', 'isascii')
  886. self.checkequal(True, ' '*p + '\x7f' + ' '*8, 'isascii')
  887. self.checkequal(False, ' '*p + '\x80' + ' '*8, 'isascii')
  888. def test_isdigit(self):
  889. self.checkequal(False, '', 'isdigit')
  890. self.checkequal(False, 'a', 'isdigit')
  891. self.checkequal(True, '0', 'isdigit')
  892. self.checkequal(True, '0123456789', 'isdigit')
  893. self.checkequal(False, '0123456789a', 'isdigit')
  894. self.checkraises(TypeError, 'abc', 'isdigit', 42)
  895. def test_title(self):
  896. self.checkequal(' Hello ', ' hello ', 'title')
  897. self.checkequal('Hello ', 'hello ', 'title')
  898. self.checkequal('Hello ', 'Hello ', 'title')
  899. self.checkequal('Format This As Title String', "fOrMaT thIs aS titLe String", 'title')
  900. self.checkequal('Format,This-As*Title;String', "fOrMaT,thIs-aS*titLe;String", 'title', )
  901. self.checkequal('Getint', "getInt", 'title')
  902. self.checkraises(TypeError, 'hello', 'title', 42)
  903. def test_splitlines(self):
  904. self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\rghi", 'splitlines')
  905. self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\r\nghi", 'splitlines')
  906. self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi", 'splitlines')
  907. self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi\n", 'splitlines')
  908. self.checkequal(['abc', 'def', 'ghi', ''], "abc\ndef\r\nghi\n\r", 'splitlines')
  909. self.checkequal(['', 'abc', 'def', 'ghi', ''], "\nabc\ndef\r\nghi\n\r", 'splitlines')
  910. self.checkequal(['', 'abc', 'def', 'ghi', ''],
  911. "\nabc\ndef\r\nghi\n\r", 'splitlines', False)
  912. self.checkequal(['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'],
  913. "\nabc\ndef\r\nghi\n\r", 'splitlines', True)
  914. self.checkequal(['', 'abc', 'def', 'ghi', ''], "\nabc\ndef\r\nghi\n\r",
  915. 'splitlines', keepends=False)
  916. self.checkequal(['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'],
  917. "\nabc\ndef\r\nghi\n\r", 'splitlines', keepends=True)
  918. self.checkraises(TypeError, 'abc', 'splitlines', 42, 42)
  919. class CommonTest(BaseTest):
  920. # This testcase contains tests that can be used in all
  921. # stringlike classes. Currently this is str and UserString.
  922. def test_hash(self):
  923. # SF bug 1054139: += optimization was not invalidating cached hash value
  924. a = self.type2test('DNSSEC')
  925. b = self.type2test('')
  926. for c in a:
  927. b += c
  928. hash(b)
  929. self.assertEqual(hash(a), hash(b))
  930. def test_capitalize_nonascii(self):
  931. # check that titlecased chars are lowered correctly
  932. # \u1ffc is the titlecased char
  933. self.checkequal('\u1ffc\u1ff3\u1ff3\u1ff3',
  934. '\u1ff3\u1ff3\u1ffc\u1ffc', 'capitalize')
  935. # check with cased non-letter chars
  936. self.checkequal('\u24c5\u24e8\u24e3\u24d7\u24de\u24dd',
  937. '\u24c5\u24ce\u24c9\u24bd\u24c4\u24c3', 'capitalize')
  938. self.checkequal('\u24c5\u24e8\u24e3\u24d7\u24de\u24dd',
  939. '\u24df\u24e8\u24e3\u24d7\u24de\u24dd', 'capitalize')
  940. self.checkequal('\u2160\u2171\u2172',
  941. '\u2160\u2161\u2162', 'capitalize')
  942. self.checkequal('\u2160\u2171\u2172',
  943. '\u2170\u2171\u2172', 'capitalize')
  944. # check with Ll chars with no upper - nothing changes here
  945. self.checkequal('\u019b\u1d00\u1d86\u0221\u1fb7',
  946. '\u019b\u1d00\u1d86\u0221\u1fb7', 'capitalize')
  947. class MixinStrUnicodeUserStringTest:
  948. # additional tests that only work for
  949. # stringlike objects, i.e. str, UserString
  950. def test_startswith(self):
  951. self.checkequal(True, 'hello', 'startswith', 'he')
  952. self.checkequal(True, 'hello', 'startswith', 'hello')
  953. self.checkequal(False, 'hello', 'startswith', 'hello world')
  954. self.checkequal(True, 'hello', 'startswith', '')
  955. self.checkequal(False, 'hello', 'startswith', 'ello')
  956. self.checkequal(True, 'hello', 'startswith', 'ello', 1)
  957. self.checkequal(True, 'hello', 'startswith', 'o', 4)
  958. self.checkequal(False, 'hello', 'startswith', 'o', 5)
  959. self.checkequal(True, 'hello', 'startswith', '', 5)
  960. self.checkequal(False, 'hello', 'startswith', 'lo', 6)
  961. self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3)
  962. self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3, 7)
  963. self.checkequal(False, 'helloworld', 'startswith', 'lowo', 3, 6)
  964. self.checkequal(True, '', 'startswith', '', 0, 1)
  965. self.checkequal(True, '', 'startswith', '', 0, 0)
  966. self.checkequal(False, '', 'startswith', '', 1, 0)
  967. # test negative indices
  968. self.checkequal(True, 'hello', 'startswith', 'he', 0, -1)
  969. self.checkequal(True, 'hello', 'startswith', 'he', -53, -1)
  970. self.checkequal(False, 'hello', 'startswith', 'hello', 0, -1)
  971. self.checkequal(False, 'hello', 'startswith', 'hello world', -1, -10)
  972. self.checkequal(False, 'hello', 'startswith', 'ello', -5)
  973. self.checkequal(True, 'hello', 'startswith', 'ello', -4)
  974. self.checkequal(False, 'hello', 'startswith', 'o', -2)
  975. self.checkequal(True, 'hello', 'startswith', 'o', -1)
  976. self.checkequal(True, 'hello', 'startswith', '', -3, -3)
  977. self.checkequal(False, 'hello', 'startswith', 'lo', -9)
  978. self.checkraises(TypeError, 'hello', 'startswith')
  979. self.checkraises(TypeError, 'hello', 'startswith', 42)
  980. # test tuple arguments
  981. self.checkequal(True, 'hello', 'startswith', ('he', 'ha'))
  982. self.checkequal(False, 'hello', 'startswith', ('lo', 'llo'))
  983. self.checkequal(True, 'hello', 'startswith', ('hellox', 'hello'))
  984. self.checkequal(False, 'hello', 'startswith', ())
  985. self.checkequal(True, 'helloworld', 'startswith', ('hellowo',
  986. 'rld', 'lowo'), 3)
  987. self.checkequal(False, 'helloworld', 'startswith', ('hellowo', 'ello',
  988. 'rld'), 3)
  989. self.checkequal(True, 'hello', 'startswith', ('lo', 'he'), 0, -1)
  990. self.checkequal(False, 'hello', 'startswith', ('he', 'hel'), 0, 1)
  991. self.checkequal(True, 'hello', 'startswith', ('he', 'hel'), 0, 2)
  992. self.checkraises(TypeError, 'hello', 'startswith', (42,))
  993. def test_endswith(self):
  994. self.checkequal(True, 'hello', 'endswith', 'lo')
  995. self.checkequal(False, 'hello', 'endswith', 'he')
  996. self.checkequal(True, 'hello', 'endswith', '')
  997. self.checkequal(False, 'hello', 'endswith', 'hello world')
  998. self.checkequal(False, 'helloworld', 'endswith', 'worl')
  999. self.checkequal(True, 'helloworld', 'endswith', 'worl', 3, 9)
  1000. self.checkequal(True, 'helloworld', 'endswith', 'world', 3, 12)
  1001. self.checkequal(True, 'helloworld', 'endswith', 'lowo', 1, 7)
  1002. self.checkequal(True, 'helloworld', 'endswith', 'lowo', 2, 7)
  1003. self.checkequal(True, 'helloworld', 'endswith', 'lowo', 3, 7)
  1004. self.checkequal(False, 'helloworld', 'endswith', 'lowo', 4, 7)
  1005. self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, 8)
  1006. self.checkequal(False, 'ab', 'endswith', 'ab', 0, 1)
  1007. self.checkequal(False, 'ab', 'endswith', 'ab', 0, 0)
  1008. self.checkequal(True, '', 'endswith', '', 0, 1)
  1009. self.checkequal(True, '', 'endswith', '', 0, 0)
  1010. self.checkequal(False, '', 'endswith', '', 1, 0)
  1011. # test negative indices
  1012. self.checkequal(True, 'hello', 'endswith', 'lo', -2)
  1013. self.checkequal(False, 'hello', 'endswith', 'he', -2)
  1014. self.checkequal(True, 'hello', 'endswith', '', -3, -3)
  1015. self.checkequal(False, 'hello', 'endswith', 'hello world', -10, -2)
  1016. self.checkequal(False, 'helloworld', 'endswith', 'worl', -6)
  1017. self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, -1)
  1018. self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, 9)
  1019. self.checkequal(True, 'helloworld', 'endswith', 'world', -7, 12)
  1020. self.checkequal(True, 'helloworld', 'endswith', 'lowo', -99, -3)
  1021. self.checkequal(True, 'helloworld', 'endswith', 'lowo', -8, -3)
  1022. self.checkequal(True, 'helloworld', 'endswith', 'lowo', -7, -3)
  1023. self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, -4)
  1024. self.checkequal(False, 'helloworld', 'endswith', 'lowo', -8, -2)
  1025. self.checkraises(TypeError, 'hello', 'endswith')
  1026. self.checkraises(TypeError, 'hello', 'endswith', 42)
  1027. # test tuple arguments
  1028. self.checkequal(False, 'hello', 'endswith', ('he', 'ha'))
  1029. self.checkequal(True, 'hello', 'endswith', ('lo', 'llo'))
  1030. self.checkequal(True, 'hello', 'endswith', ('hellox', 'hello'))
  1031. self.checkequal(False, 'hello', 'endswith', ())
  1032. self.checkequal(True, 'helloworld', 'endswith', ('hellowo',
  1033. 'rld', 'lowo'), 3)
  1034. self.checkequal(False, 'helloworld', 'endswith', ('hellowo', 'ello',
  1035. 'rld'), 3, -1)
  1036. self.checkequal(True, 'hello', 'endswith', ('hell', 'ell'), 0, -1)
  1037. self.checkequal(False, 'hello', 'endswith', ('he', 'hel'), 0, 1)
  1038. self.checkequal(True, 'hello', 'endswith', ('he', 'hell'), 0, 4)
  1039. self.checkraises(TypeError, 'hello', 'endswith', (42,))
  1040. def test___contains__(self):
  1041. self.checkequal(True, '', '__contains__', '')
  1042. self.checkequal(True, 'abc', '__contains__', '')
  1043. self.checkequal(False, 'abc', '__contains__', '\0')
  1044. self.checkequal(True, '\0abc', '__contains__', '\0')
  1045. self.checkequal(True, 'abc\0', '__contains__', '\0')
  1046. self.checkequal(True, '\0abc', '__contains__', 'a')
  1047. self.checkequal(True, 'asdf', '__contains__', 'asdf')
  1048. self.checkequal(False, 'asd', '__contains__', 'asdf')
  1049. self.checkequal(False, '', '__contains__', 'asdf')
  1050. def test_subscript(self):
  1051. self.checkequal('a', 'abc', '__getitem__', 0)
  1052. self.checkequal('c', 'abc', '__getitem__', -1)
  1053. self.checkequal('a', 'abc', '__getitem__', 0)
  1054. self.checkequal('abc', 'abc', '__getitem__', slice(0, 3))
  1055. self.checkequal('abc', 'abc', '__getitem__', slice(0, 1000))
  1056. self.checkequal('a', 'abc', '__getitem__', slice(0, 1))
  1057. self.checkequal('', 'abc', '__getitem__', slice(0, 0))
  1058. self.checkraises(TypeError, 'abc', '__getitem__', 'def')
  1059. for idx_type in ('def', object()):
  1060. expected_msg = "string indices must be integers, not '{}'".format(type(idx_type).__name__)
  1061. self.checkraises(TypeError, 'abc', '__getitem__', idx_type, expected_msg=expected_msg)
  1062. def test_slice(self):
  1063. self.checkequal('abc', 'abc', '__getitem__', slice(0, 1000))
  1064. self.checkequal('abc', 'abc', '__getitem__', slice(0, 3))
  1065. self.checkequal('ab', 'abc', '__getitem__', slice(0, 2))
  1066. self.checkequal('bc', 'abc', '__getitem__', slice(1, 3))
  1067. self.checkequal('b', 'abc', '__getitem__', slice(1, 2))
  1068. self.checkequal('', 'abc', '__getitem__', slice(2, 2))
  1069. self.checkequal('', 'abc', '__getitem__', slice(1000, 1000))
  1070. self.checkequal('', 'abc', '__getitem__', slice(2000, 1000))
  1071. self.checkequal('', 'abc', '__getitem__', slice(2, 1))
  1072. self.checkraises(TypeError, 'abc', '__getitem__', 'def')
  1073. def test_extended_getslice(self):
  1074. # Test extended slicing by comparing with list slicing.
  1075. s = string.ascii_letters + string.digits
  1076. indices = (0, None, 1, 3, 41, sys.maxsize, -1, -2, -37)
  1077. for start in indices:
  1078. for stop in indices:
  1079. # Skip step 0 (invalid)
  1080. for step in indices[1:]:
  1081. L = list(s)[start:stop:step]
  1082. self.checkequal("".join(L), s, '__getitem__',
  1083. slice(start, stop, step))
  1084. def test_mul(self):
  1085. self.checkequal('', 'abc', '__mul__', -1)
  1086. self.checkequal('', 'abc', '__mul__', 0)
  1087. self.checkequal('abc', 'abc', '__mul__', 1)
  1088. self.checkequal('abcabcabc', 'abc', '__mul__', 3)
  1089. self.checkraises(TypeError, 'abc', '__mul__')
  1090. self.checkraises(TypeError, 'abc', '__mul__', '')
  1091. # XXX: on a 64-bit system, this doesn't raise an overflow error,
  1092. # but either raises a MemoryError, or succeeds (if you have 54TiB)
  1093. #self.checkraises(OverflowError, 10000*'abc', '__mul__', 2000000000)
  1094. def test_join(self):
  1095. # join now works with any sequence type
  1096. # moved here, because the argument order is
  1097. # different in string.join
  1098. self.checkequal('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
  1099. self.checkequal('abcd', '', 'join', ('a', 'b', 'c', 'd'))
  1100. self.checkequal('bd', '', 'join', ('', 'b', '', 'd'))
  1101. self.checkequal('ac', '', 'join', ('a', '', 'c', ''))
  1102. self.checkequal('w x y z', ' ', 'join', Sequence())
  1103. self.checkequal('abc', 'a', 'join', ('abc',))
  1104. self.checkequal('z', 'a', 'join', UserList(['z']))
  1105. self.checkequal('a.b.c', '.', 'join', ['a', 'b', 'c'])
  1106. self.assertRaises(TypeError, '.'.join, ['a', 'b', 3])
  1107. for i in [5, 25, 125]:
  1108. self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
  1109. ['a' * i] * i)
  1110. self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
  1111. ('a' * i,) * i)
  1112. #self.checkequal(str(BadSeq1()), ' ', 'join', BadSeq1())
  1113. self.checkequal('a b c', ' ', 'join', BadSeq2())
  1114. self.checkraises(TypeError, ' ', 'join')
  1115. self.checkraises(TypeError, ' ', 'join', None)
  1116. self.checkraises(TypeError, ' ', 'join', 7)
  1117. self.checkraises(TypeError, ' ', 'join', [1, 2, bytes()])
  1118. try:
  1119. def f():
  1120. yield 4 + ""
  1121. self.fixtype(' ').join(f())
  1122. except TypeError as e:
  1123. if '+' not in str(e):
  1124. self.fail('join() ate exception message')
  1125. else:
  1126. self.fail('exception not raised')
  1127. def test_formatting(self):
  1128. self.checkequal('+hello+', '+%s+', '__mod__', 'hello')
  1129. self.checkequal('+10+', '+%d+', '__mod__', 10)
  1130. self.checkequal('a', "%c", '__mod__', "a")
  1131. self.checkequal('a', "%c", '__mod__', "a")
  1132. self.checkequal('"', "%c", '__mod__', 34)
  1133. self.checkequal('$', "%c", '__mod__', 36)
  1134. self.checkequal('10', "%d", '__mod__', 10)
  1135. self.checkequal('\x7f', "%c", '__mod__', 0x7f)
  1136. for ordinal in (-100, 0x200000):
  1137. # unicode raises ValueError, str raises OverflowError
  1138. self.checkraises((ValueError, OverflowError), '%c', '__mod__', ordinal)
  1139. longvalue = sys.maxsize + 10
  1140. slongvalue = str(longvalue)
  1141. self.checkequal(' 42', '%3ld', '__mod__', 42)
  1142. self.checkequal('42', '%d', '__mod__', 42.0)
  1143. self.checkequal(slongvalue, '%d', '__mod__', longvalue)
  1144. self.checkcall('%d', '__mod__', float(longvalue))
  1145. self.checkequal('0042.00', '%07.2f', '__mod__', 42)
  1146. self.checkequal('0042.00', '%07.2F', '__mod__', 42)
  1147. self.checkraises(TypeError, 'abc', '__mod__')
  1148. self.checkraises(TypeError, '%(foo)s', '__mod__', 42)
  1149. self.checkraises(TypeError, '%s%s', '__mod__', (42,))
  1150. self.checkraises(TypeError, '%c', '__mod__', (None,))
  1151. self.checkraises(ValueError, '%(foo', '__mod__', {})
  1152. self.checkraises(TypeError, '%(foo)s %(bar)s', '__mod__', ('foo', 42))
  1153. self.checkraises(TypeError, '%d', '__mod__', "42") # not numeric
  1154. self.checkraises(TypeError, '%d', '__mod__', (42+0j)) # no int conversion provided
  1155. # argument names with properly nested brackets are supported
  1156. self.checkequal('bar', '%((foo))s', '__mod__', {'(foo)': 'bar'})
  1157. # 100 is a magic number in PyUnicode_Format, this forces a resize
  1158. self.checkequal(103*'a'+'x', '%sx', '__mod__', 103*'a')
  1159. self.checkraises(TypeError, '%*s', '__mod__', ('foo', 'bar'))
  1160. self.checkraises(TypeError, '%10.*f', '__mod__', ('foo', 42.))
  1161. self.checkraises(ValueError, '%10', '__mod__', (42,))
  1162. # Outrageously large width or precision should raise ValueError.
  1163. self.checkraises(ValueError, '%%%df' % (2**64), '__mod__', (3.2))
  1164. self.checkraises(ValueError, '%%.%df' % (2**64), '__mod__', (3.2))
  1165. self.checkraises(OverflowError, '%*s', '__mod__',
  1166. (sys.maxsize + 1, ''))
  1167. self.checkraises(OverflowError, '%.*f', '__mod__',
  1168. (sys.maxsize + 1, 1. / 7))
  1169. class X(object): pass
  1170. self.checkraises(TypeError, 'abc', '__mod__', X())
  1171. @support.cpython_only
  1172. def test_formatting_c_limits(self):
  1173. _testcapi = import_helper.import_module('_testcapi')
  1174. SIZE_MAX = (1 << (_testcapi.PY_SSIZE_T_MAX.bit_length() + 1)) - 1
  1175. self.checkraises(OverflowError, '%*s', '__mod__',
  1176. (_testcapi.PY_SSIZE_T_MAX + 1, ''))
  1177. self.checkraises(OverflowError, '%.*f', '__mod__',
  1178. (_testcapi.INT_MAX + 1, 1. / 7))
  1179. # Issue 15989
  1180. self.checkraises(OverflowError, '%*s', '__mod__',
  1181. (SIZE_MAX + 1, ''))
  1182. self.checkraises(OverflowError, '%.*f', '__mod__',
  1183. (_testcapi.UINT_MAX + 1, 1. / 7))
  1184. def test_floatformatting(self):
  1185. # float formatting
  1186. for prec in range(100):
  1187. format = '%%.%if' % prec
  1188. value = 0.01
  1189. for x in range(60):
  1190. value = value * 3.14159265359 / 3.0 * 10.0
  1191. self.checkcall(format, "__mod__", value)
  1192. def test_inplace_rewrites(self):
  1193. # Check that strings don't copy and modify cached single-character strings
  1194. self.checkequal('a', 'A', 'lower')
  1195. self.checkequal(True, 'A', 'isupper')
  1196. self.checkequal('A', 'a', 'upper')
  1197. self.checkequal(True, 'a', 'islower')
  1198. self.checkequal('a', 'A', 'replace', 'A', 'a')
  1199. self.checkequal(True, 'A', 'isupper')
  1200. self.checkequal('A', 'a', 'capitalize')
  1201. self.checkequal(True, 'a', 'islower')
  1202. self.checkequal('A', 'a', 'swapcase')
  1203. self.checkequal(True, 'a', 'islower')
  1204. self.checkequal('A', 'a', 'title')
  1205. self.checkequal(True, 'a', 'islower')
  1206. def test_partition(self):
  1207. self.checkequal(('this is the par', 'ti', 'tion method'),
  1208. 'this is the partition method', 'partition', 'ti')
  1209. # from raymond's original specification
  1210. S = 'http://www.python.org'
  1211. self.checkequal(('http', '://', 'www.python.org'), S, 'partition', '://')
  1212. self.checkequal(('http://www.python.org', '', ''), S, 'partition', '?')
  1213. self.checkequal(('', 'http://', 'www.python.org'), S, 'partition', 'http://')
  1214. self.checkequal(('http://www.python.', 'org', ''), S, 'partition', 'org')
  1215. self.checkraises(ValueError, S, 'partition', '')
  1216. self.checkraises(TypeError, S, 'partition', None)
  1217. def test_rpartition(self):
  1218. self.checkequal(('this is the rparti', 'ti', 'on method'),
  1219. 'this is the rpartition method', 'rpartition', 'ti')
  1220. # from raymond's original specification
  1221. S = 'http://www.python.org'
  1222. self.checkequal(('http', '://', 'www.python.org'), S, 'rpartition', '://')
  1223. self.checkequal(('', '', 'http://www.python.org'), S, 'rpartition', '?')
  1224. self.checkequal(('', 'http://', 'www.python.org'), S, 'rpartition', 'http://')
  1225. self.checkequal(('http://www.python.', 'org', ''), S, 'rpartition', 'org')
  1226. self.checkraises(ValueError, S, 'rpartition', '')
  1227. self.checkraises(TypeError, S, 'rpartition', None)
  1228. def test_none_arguments(self):
  1229. # issue 11828
  1230. s = 'hello'
  1231. self.checkequal(2, s, 'find', 'l', None)
  1232. self.checkequal(3, s, 'find', 'l', -2, None)
  1233. self.checkequal(2, s, 'find', 'l', None, -2)
  1234. self.checkequal(0, s, 'find', 'h', None, None)
  1235. self.checkequal(3, s, 'rfind', 'l', None)
  1236. self.checkequal(3, s, 'rfind', 'l', -2, None)
  1237. self.checkequal(2, s, 'rfind', 'l', None, -2)
  1238. self.checkequal(0, s, 'rfind', 'h', None, None)
  1239. self.checkequal(2, s, 'index', 'l', None)
  1240. self.checkequal(3, s, 'index', 'l', -2, None)
  1241. self.checkequal(2, s, 'index', 'l', None, -2)
  1242. self.checkequal(0, s, 'index', 'h', None, None)
  1243. self.checkequal(3, s, 'rindex', 'l', None)
  1244. self.checkequal(3, s, 'rindex', 'l', -2, None)
  1245. self.checkequal(2, s, 'rindex', 'l', None, -2)
  1246. self.checkequal(0, s, 'rindex', 'h', None, None)
  1247. self.checkequal(2, s, 'count', 'l', None)
  1248. self.checkequal(1, s, 'count', 'l', -2, None)
  1249. self.checkequal(1, s, 'count', 'l', None, -2)
  1250. self.checkequal(0, s, 'count', 'x', None, None)
  1251. self.checkequal(True, s, 'endswith', 'o', None)
  1252. self.checkequal(True, s, 'endswith', 'lo', -2, None)
  1253. self.checkequal(True, s, 'endswith', 'l', None, -2)
  1254. self.checkequal(False, s, 'endswith', 'x', None, None)
  1255. self.checkequal(True, s, 'startswith', 'h', None)
  1256. self.checkequal(True, s, 'startswith', 'l', -2, None)
  1257. self.checkequal(True, s, 'startswith', 'h', None, -2)
  1258. self.checkequal(False, s, 'startswith', 'x', None, None)
  1259. def test_find_etc_raise_correct_error_messages(self):
  1260. # issue 11828
  1261. s = 'hello'
  1262. x = 'x'
  1263. self.assertRaisesRegex(TypeError, r'^find\(', s.find,
  1264. x, None, None, None)
  1265. self.assertRaisesRegex(TypeError, r'^rfind\(', s.rfind,
  1266. x, None, None, None)
  1267. self.assertRaisesRegex(TypeError, r'^index\(', s.index,
  1268. x, None, None, None)
  1269. self.assertRaisesRegex(TypeError, r'^rindex\(', s.rindex,
  1270. x, None, None, None)
  1271. self.assertRaisesRegex(TypeError, r'^count\(', s.count,
  1272. x, None, None, None)
  1273. self.assertRaisesRegex(TypeError, r'^startswith\(', s.startswith,
  1274. x, None, None, None)
  1275. self.assertRaisesRegex(TypeError, r'^endswith\(', s.endswith,
  1276. x, None, None, None)
  1277. # issue #15534
  1278. self.checkequal(10, "...\u043c......<", "find", "<")
  1279. class MixinStrUnicodeTest:
  1280. # Additional tests that only work with str.
  1281. def test_bug1001011(self):
  1282. # Make sure join returns a NEW object for single item sequences
  1283. # involving a subclass.
  1284. # Make sure that it is of the appropriate type.
  1285. # Check the optimisation still occurs for standard objects.
  1286. t = self.type2test
  1287. class subclass(t):
  1288. pass
  1289. s1 = subclass("abcd")
  1290. s2 = t().join([s1])
  1291. self.assertIsNot(s1, s2)
  1292. self.assertIs(type(s2), t)
  1293. s1 = t("abcd")
  1294. s2 = t().join([s1])
  1295. self.assertIs(s1, s2)