test_builtin.py 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493
  1. # Python test set -- built-in functions
  2. import ast
  3. import asyncio
  4. import builtins
  5. import collections
  6. import decimal
  7. import fractions
  8. import gc
  9. import io
  10. import locale
  11. import os
  12. import pickle
  13. import platform
  14. import random
  15. import re
  16. import sys
  17. import traceback
  18. import types
  19. import unittest
  20. import warnings
  21. from contextlib import ExitStack
  22. from functools import partial
  23. from inspect import CO_COROUTINE
  24. from itertools import product
  25. from textwrap import dedent
  26. from types import AsyncGeneratorType, FunctionType, CellType
  27. from operator import neg
  28. from test import support
  29. from test.support import (swap_attr, maybe_get_event_loop_policy)
  30. from test.support.os_helper import (EnvironmentVarGuard, TESTFN, unlink)
  31. from test.support.script_helper import assert_python_ok
  32. from test.support.warnings_helper import check_warnings
  33. from unittest.mock import MagicMock, patch
  34. try:
  35. import pty, signal
  36. except ImportError:
  37. pty = signal = None
  38. class Squares:
  39. def __init__(self, max):
  40. self.max = max
  41. self.sofar = []
  42. def __len__(self): return len(self.sofar)
  43. def __getitem__(self, i):
  44. if not 0 <= i < self.max: raise IndexError
  45. n = len(self.sofar)
  46. while n <= i:
  47. self.sofar.append(n*n)
  48. n += 1
  49. return self.sofar[i]
  50. class StrSquares:
  51. def __init__(self, max):
  52. self.max = max
  53. self.sofar = []
  54. def __len__(self):
  55. return len(self.sofar)
  56. def __getitem__(self, i):
  57. if not 0 <= i < self.max:
  58. raise IndexError
  59. n = len(self.sofar)
  60. while n <= i:
  61. self.sofar.append(str(n*n))
  62. n += 1
  63. return self.sofar[i]
  64. class BitBucket:
  65. def write(self, line):
  66. pass
  67. test_conv_no_sign = [
  68. ('0', 0),
  69. ('1', 1),
  70. ('9', 9),
  71. ('10', 10),
  72. ('99', 99),
  73. ('100', 100),
  74. ('314', 314),
  75. (' 314', 314),
  76. ('314 ', 314),
  77. (' \t\t 314 \t\t ', 314),
  78. (repr(sys.maxsize), sys.maxsize),
  79. (' 1x', ValueError),
  80. (' 1 ', 1),
  81. (' 1\02 ', ValueError),
  82. ('', ValueError),
  83. (' ', ValueError),
  84. (' \t\t ', ValueError),
  85. (str(br'\u0663\u0661\u0664 ','raw-unicode-escape'), 314),
  86. (chr(0x200), ValueError),
  87. ]
  88. test_conv_sign = [
  89. ('0', 0),
  90. ('1', 1),
  91. ('9', 9),
  92. ('10', 10),
  93. ('99', 99),
  94. ('100', 100),
  95. ('314', 314),
  96. (' 314', ValueError),
  97. ('314 ', 314),
  98. (' \t\t 314 \t\t ', ValueError),
  99. (repr(sys.maxsize), sys.maxsize),
  100. (' 1x', ValueError),
  101. (' 1 ', ValueError),
  102. (' 1\02 ', ValueError),
  103. ('', ValueError),
  104. (' ', ValueError),
  105. (' \t\t ', ValueError),
  106. (str(br'\u0663\u0661\u0664 ','raw-unicode-escape'), 314),
  107. (chr(0x200), ValueError),
  108. ]
  109. class TestFailingBool:
  110. def __bool__(self):
  111. raise RuntimeError
  112. class TestFailingIter:
  113. def __iter__(self):
  114. raise RuntimeError
  115. def filter_char(arg):
  116. return ord(arg) > ord("d")
  117. def map_char(arg):
  118. return chr(ord(arg)+1)
  119. class BuiltinTest(unittest.TestCase):
  120. # Helper to check picklability
  121. def check_iter_pickle(self, it, seq, proto):
  122. itorg = it
  123. d = pickle.dumps(it, proto)
  124. it = pickle.loads(d)
  125. self.assertEqual(type(itorg), type(it))
  126. self.assertEqual(list(it), seq)
  127. #test the iterator after dropping one from it
  128. it = pickle.loads(d)
  129. try:
  130. next(it)
  131. except StopIteration:
  132. return
  133. d = pickle.dumps(it, proto)
  134. it = pickle.loads(d)
  135. self.assertEqual(list(it), seq[1:])
  136. def test_import(self):
  137. __import__('sys')
  138. __import__('time')
  139. __import__('string')
  140. __import__(name='sys')
  141. __import__(name='time', level=0)
  142. self.assertRaises(ModuleNotFoundError, __import__, 'spamspam')
  143. self.assertRaises(TypeError, __import__, 1, 2, 3, 4)
  144. self.assertRaises(ValueError, __import__, '')
  145. self.assertRaises(TypeError, __import__, 'sys', name='sys')
  146. # Relative import outside of a package with no __package__ or __spec__ (bpo-37409).
  147. with self.assertWarns(ImportWarning):
  148. self.assertRaises(ImportError, __import__, '',
  149. {'__package__': None, '__spec__': None, '__name__': '__main__'},
  150. locals={}, fromlist=('foo',), level=1)
  151. # embedded null character
  152. self.assertRaises(ModuleNotFoundError, __import__, 'string\x00')
  153. def test_abs(self):
  154. # int
  155. self.assertEqual(abs(0), 0)
  156. self.assertEqual(abs(1234), 1234)
  157. self.assertEqual(abs(-1234), 1234)
  158. self.assertTrue(abs(-sys.maxsize-1) > 0)
  159. # float
  160. self.assertEqual(abs(0.0), 0.0)
  161. self.assertEqual(abs(3.14), 3.14)
  162. self.assertEqual(abs(-3.14), 3.14)
  163. # str
  164. self.assertRaises(TypeError, abs, 'a')
  165. # bool
  166. self.assertEqual(abs(True), 1)
  167. self.assertEqual(abs(False), 0)
  168. # other
  169. self.assertRaises(TypeError, abs)
  170. self.assertRaises(TypeError, abs, None)
  171. class AbsClass(object):
  172. def __abs__(self):
  173. return -5
  174. self.assertEqual(abs(AbsClass()), -5)
  175. def test_all(self):
  176. self.assertEqual(all([2, 4, 6]), True)
  177. self.assertEqual(all([2, None, 6]), False)
  178. self.assertRaises(RuntimeError, all, [2, TestFailingBool(), 6])
  179. self.assertRaises(RuntimeError, all, TestFailingIter())
  180. self.assertRaises(TypeError, all, 10) # Non-iterable
  181. self.assertRaises(TypeError, all) # No args
  182. self.assertRaises(TypeError, all, [2, 4, 6], []) # Too many args
  183. self.assertEqual(all([]), True) # Empty iterator
  184. self.assertEqual(all([0, TestFailingBool()]), False)# Short-circuit
  185. S = [50, 60]
  186. self.assertEqual(all(x > 42 for x in S), True)
  187. S = [50, 40, 60]
  188. self.assertEqual(all(x > 42 for x in S), False)
  189. def test_any(self):
  190. self.assertEqual(any([None, None, None]), False)
  191. self.assertEqual(any([None, 4, None]), True)
  192. self.assertRaises(RuntimeError, any, [None, TestFailingBool(), 6])
  193. self.assertRaises(RuntimeError, any, TestFailingIter())
  194. self.assertRaises(TypeError, any, 10) # Non-iterable
  195. self.assertRaises(TypeError, any) # No args
  196. self.assertRaises(TypeError, any, [2, 4, 6], []) # Too many args
  197. self.assertEqual(any([]), False) # Empty iterator
  198. self.assertEqual(any([1, TestFailingBool()]), True) # Short-circuit
  199. S = [40, 60, 30]
  200. self.assertEqual(any(x > 42 for x in S), True)
  201. S = [10, 20, 30]
  202. self.assertEqual(any(x > 42 for x in S), False)
  203. def test_ascii(self):
  204. self.assertEqual(ascii(''), '\'\'')
  205. self.assertEqual(ascii(0), '0')
  206. self.assertEqual(ascii(()), '()')
  207. self.assertEqual(ascii([]), '[]')
  208. self.assertEqual(ascii({}), '{}')
  209. a = []
  210. a.append(a)
  211. self.assertEqual(ascii(a), '[[...]]')
  212. a = {}
  213. a[0] = a
  214. self.assertEqual(ascii(a), '{0: {...}}')
  215. # Advanced checks for unicode strings
  216. def _check_uni(s):
  217. self.assertEqual(ascii(s), repr(s))
  218. _check_uni("'")
  219. _check_uni('"')
  220. _check_uni('"\'')
  221. _check_uni('\0')
  222. _check_uni('\r\n\t .')
  223. # Unprintable non-ASCII characters
  224. _check_uni('\x85')
  225. _check_uni('\u1fff')
  226. _check_uni('\U00012fff')
  227. # Lone surrogates
  228. _check_uni('\ud800')
  229. _check_uni('\udfff')
  230. # Issue #9804: surrogates should be joined even for printable
  231. # wide characters (UCS-2 builds).
  232. self.assertEqual(ascii('\U0001d121'), "'\\U0001d121'")
  233. # All together
  234. s = "'\0\"\n\r\t abcd\x85é\U00012fff\uD800\U0001D121xxx."
  235. self.assertEqual(ascii(s),
  236. r"""'\'\x00"\n\r\t abcd\x85\xe9\U00012fff\ud800\U0001d121xxx.'""")
  237. def test_neg(self):
  238. x = -sys.maxsize-1
  239. self.assertTrue(isinstance(x, int))
  240. self.assertEqual(-x, sys.maxsize+1)
  241. def test_callable(self):
  242. self.assertTrue(callable(len))
  243. self.assertFalse(callable("a"))
  244. self.assertTrue(callable(callable))
  245. self.assertTrue(callable(lambda x, y: x + y))
  246. self.assertFalse(callable(__builtins__))
  247. def f(): pass
  248. self.assertTrue(callable(f))
  249. class C1:
  250. def meth(self): pass
  251. self.assertTrue(callable(C1))
  252. c = C1()
  253. self.assertTrue(callable(c.meth))
  254. self.assertFalse(callable(c))
  255. # __call__ is looked up on the class, not the instance
  256. c.__call__ = None
  257. self.assertFalse(callable(c))
  258. c.__call__ = lambda self: 0
  259. self.assertFalse(callable(c))
  260. del c.__call__
  261. self.assertFalse(callable(c))
  262. class C2(object):
  263. def __call__(self): pass
  264. c2 = C2()
  265. self.assertTrue(callable(c2))
  266. c2.__call__ = None
  267. self.assertTrue(callable(c2))
  268. class C3(C2): pass
  269. c3 = C3()
  270. self.assertTrue(callable(c3))
  271. def test_chr(self):
  272. self.assertEqual(chr(32), ' ')
  273. self.assertEqual(chr(65), 'A')
  274. self.assertEqual(chr(97), 'a')
  275. self.assertEqual(chr(0xff), '\xff')
  276. self.assertRaises(ValueError, chr, 1<<24)
  277. self.assertEqual(chr(sys.maxunicode),
  278. str('\\U0010ffff'.encode("ascii"), 'unicode-escape'))
  279. self.assertRaises(TypeError, chr)
  280. self.assertEqual(chr(0x0000FFFF), "\U0000FFFF")
  281. self.assertEqual(chr(0x00010000), "\U00010000")
  282. self.assertEqual(chr(0x00010001), "\U00010001")
  283. self.assertEqual(chr(0x000FFFFE), "\U000FFFFE")
  284. self.assertEqual(chr(0x000FFFFF), "\U000FFFFF")
  285. self.assertEqual(chr(0x00100000), "\U00100000")
  286. self.assertEqual(chr(0x00100001), "\U00100001")
  287. self.assertEqual(chr(0x0010FFFE), "\U0010FFFE")
  288. self.assertEqual(chr(0x0010FFFF), "\U0010FFFF")
  289. self.assertRaises(ValueError, chr, -1)
  290. self.assertRaises(ValueError, chr, 0x00110000)
  291. self.assertRaises((OverflowError, ValueError), chr, 2**32)
  292. def test_cmp(self):
  293. self.assertTrue(not hasattr(builtins, "cmp"))
  294. def test_compile(self):
  295. compile('print(1)\n', '', 'exec')
  296. bom = b'\xef\xbb\xbf'
  297. compile(bom + b'print(1)\n', '', 'exec')
  298. compile(source='pass', filename='?', mode='exec')
  299. compile(dont_inherit=False, filename='tmp', source='0', mode='eval')
  300. compile('pass', '?', dont_inherit=True, mode='exec')
  301. compile(memoryview(b"text"), "name", "exec")
  302. self.assertRaises(TypeError, compile)
  303. self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'badmode')
  304. self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'single', 0xff)
  305. self.assertRaises(ValueError, compile, chr(0), 'f', 'exec')
  306. self.assertRaises(TypeError, compile, 'pass', '?', 'exec',
  307. mode='eval', source='0', filename='tmp')
  308. compile('print("\xe5")\n', '', 'exec')
  309. self.assertRaises(ValueError, compile, chr(0), 'f', 'exec')
  310. self.assertRaises(ValueError, compile, str('a = 1'), 'f', 'bad')
  311. # test the optimize argument
  312. codestr = '''def f():
  313. """doc"""
  314. debug_enabled = False
  315. if __debug__:
  316. debug_enabled = True
  317. try:
  318. assert False
  319. except AssertionError:
  320. return (True, f.__doc__, debug_enabled, __debug__)
  321. else:
  322. return (False, f.__doc__, debug_enabled, __debug__)
  323. '''
  324. def f(): """doc"""
  325. values = [(-1, __debug__, f.__doc__, __debug__, __debug__),
  326. (0, True, 'doc', True, True),
  327. (1, False, 'doc', False, False),
  328. (2, False, None, False, False)]
  329. for optval, *expected in values:
  330. # test both direct compilation and compilation via AST
  331. codeobjs = []
  332. codeobjs.append(compile(codestr, "<test>", "exec", optimize=optval))
  333. tree = ast.parse(codestr)
  334. codeobjs.append(compile(tree, "<test>", "exec", optimize=optval))
  335. for code in codeobjs:
  336. ns = {}
  337. exec(code, ns)
  338. rv = ns['f']()
  339. self.assertEqual(rv, tuple(expected))
  340. def test_compile_top_level_await_no_coro(self):
  341. """Make sure top level non-await codes get the correct coroutine flags"""
  342. modes = ('single', 'exec')
  343. code_samples = [
  344. '''def f():pass\n''',
  345. '''[x for x in l]''',
  346. '''{x for x in l}''',
  347. '''(x for x in l)''',
  348. '''{x:x for x in l}''',
  349. ]
  350. for mode, code_sample in product(modes, code_samples):
  351. source = dedent(code_sample)
  352. co = compile(source,
  353. '?',
  354. mode,
  355. flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT)
  356. self.assertNotEqual(co.co_flags & CO_COROUTINE, CO_COROUTINE,
  357. msg=f"source={source} mode={mode}")
  358. @unittest.skipIf(
  359. support.is_emscripten or support.is_wasi,
  360. "socket.accept is broken"
  361. )
  362. def test_compile_top_level_await(self):
  363. """Test whether code some top level await can be compiled.
  364. Make sure it compiles only with the PyCF_ALLOW_TOP_LEVEL_AWAIT flag
  365. set, and make sure the generated code object has the CO_COROUTINE flag
  366. set in order to execute it with `await eval(.....)` instead of exec,
  367. or via a FunctionType.
  368. """
  369. # helper function just to check we can run top=level async-for
  370. async def arange(n):
  371. for i in range(n):
  372. yield i
  373. modes = ('single', 'exec')
  374. code_samples = [
  375. '''a = await asyncio.sleep(0, result=1)''',
  376. '''async for i in arange(1):
  377. a = 1''',
  378. '''async with asyncio.Lock() as l:
  379. a = 1''',
  380. '''a = [x async for x in arange(2)][1]''',
  381. '''a = 1 in {x async for x in arange(2)}''',
  382. '''a = {x:1 async for x in arange(1)}[0]''',
  383. '''a = [x async for x in arange(2) async for x in arange(2)][1]''',
  384. '''a = [x async for x in (x async for x in arange(5))][1]''',
  385. '''a, = [1 for x in {x async for x in arange(1)}]''',
  386. '''a = [await asyncio.sleep(0, x) async for x in arange(2)][1]'''
  387. ]
  388. policy = maybe_get_event_loop_policy()
  389. try:
  390. for mode, code_sample in product(modes, code_samples):
  391. source = dedent(code_sample)
  392. with self.assertRaises(
  393. SyntaxError, msg=f"source={source} mode={mode}"):
  394. compile(source, '?', mode)
  395. co = compile(source,
  396. '?',
  397. mode,
  398. flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT)
  399. self.assertEqual(co.co_flags & CO_COROUTINE, CO_COROUTINE,
  400. msg=f"source={source} mode={mode}")
  401. # test we can create and advance a function type
  402. globals_ = {'asyncio': asyncio, 'a': 0, 'arange': arange}
  403. async_f = FunctionType(co, globals_)
  404. asyncio.run(async_f())
  405. self.assertEqual(globals_['a'], 1)
  406. # test we can await-eval,
  407. globals_ = {'asyncio': asyncio, 'a': 0, 'arange': arange}
  408. asyncio.run(eval(co, globals_))
  409. self.assertEqual(globals_['a'], 1)
  410. finally:
  411. asyncio.set_event_loop_policy(policy)
  412. def test_compile_top_level_await_invalid_cases(self):
  413. # helper function just to check we can run top=level async-for
  414. async def arange(n):
  415. for i in range(n):
  416. yield i
  417. modes = ('single', 'exec')
  418. code_samples = [
  419. '''def f(): await arange(10)\n''',
  420. '''def f(): [x async for x in arange(10)]\n''',
  421. '''def f(): [await x async for x in arange(10)]\n''',
  422. '''def f():
  423. async for i in arange(1):
  424. a = 1
  425. ''',
  426. '''def f():
  427. async with asyncio.Lock() as l:
  428. a = 1
  429. '''
  430. ]
  431. policy = maybe_get_event_loop_policy()
  432. try:
  433. for mode, code_sample in product(modes, code_samples):
  434. source = dedent(code_sample)
  435. with self.assertRaises(
  436. SyntaxError, msg=f"source={source} mode={mode}"):
  437. compile(source, '?', mode)
  438. with self.assertRaises(
  439. SyntaxError, msg=f"source={source} mode={mode}"):
  440. co = compile(source,
  441. '?',
  442. mode,
  443. flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT)
  444. finally:
  445. asyncio.set_event_loop_policy(policy)
  446. def test_compile_async_generator(self):
  447. """
  448. With the PyCF_ALLOW_TOP_LEVEL_AWAIT flag added in 3.8, we want to
  449. make sure AsyncGenerators are still properly not marked with the
  450. CO_COROUTINE flag.
  451. """
  452. code = dedent("""async def ticker():
  453. for i in range(10):
  454. yield i
  455. await asyncio.sleep(0)""")
  456. co = compile(code, '?', 'exec', flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT)
  457. glob = {}
  458. exec(co, glob)
  459. self.assertEqual(type(glob['ticker']()), AsyncGeneratorType)
  460. def test_delattr(self):
  461. sys.spam = 1
  462. delattr(sys, 'spam')
  463. self.assertRaises(TypeError, delattr)
  464. self.assertRaises(TypeError, delattr, sys)
  465. msg = r"^attribute name must be string, not 'int'$"
  466. self.assertRaisesRegex(TypeError, msg, delattr, sys, 1)
  467. def test_dir(self):
  468. # dir(wrong number of arguments)
  469. self.assertRaises(TypeError, dir, 42, 42)
  470. # dir() - local scope
  471. local_var = 1
  472. self.assertIn('local_var', dir())
  473. # dir(module)
  474. self.assertIn('exit', dir(sys))
  475. # dir(module_with_invalid__dict__)
  476. class Foo(types.ModuleType):
  477. __dict__ = 8
  478. f = Foo("foo")
  479. self.assertRaises(TypeError, dir, f)
  480. # dir(type)
  481. self.assertIn("strip", dir(str))
  482. self.assertNotIn("__mro__", dir(str))
  483. # dir(obj)
  484. class Foo(object):
  485. def __init__(self):
  486. self.x = 7
  487. self.y = 8
  488. self.z = 9
  489. f = Foo()
  490. self.assertIn("y", dir(f))
  491. # dir(obj_no__dict__)
  492. class Foo(object):
  493. __slots__ = []
  494. f = Foo()
  495. self.assertIn("__repr__", dir(f))
  496. # dir(obj_no__class__with__dict__)
  497. # (an ugly trick to cause getattr(f, "__class__") to fail)
  498. class Foo(object):
  499. __slots__ = ["__class__", "__dict__"]
  500. def __init__(self):
  501. self.bar = "wow"
  502. f = Foo()
  503. self.assertNotIn("__repr__", dir(f))
  504. self.assertIn("bar", dir(f))
  505. # dir(obj_using __dir__)
  506. class Foo(object):
  507. def __dir__(self):
  508. return ["kan", "ga", "roo"]
  509. f = Foo()
  510. self.assertTrue(dir(f) == ["ga", "kan", "roo"])
  511. # dir(obj__dir__tuple)
  512. class Foo(object):
  513. def __dir__(self):
  514. return ("b", "c", "a")
  515. res = dir(Foo())
  516. self.assertIsInstance(res, list)
  517. self.assertTrue(res == ["a", "b", "c"])
  518. # dir(obj__dir__not_sequence)
  519. class Foo(object):
  520. def __dir__(self):
  521. return 7
  522. f = Foo()
  523. self.assertRaises(TypeError, dir, f)
  524. # dir(traceback)
  525. try:
  526. raise IndexError
  527. except IndexError as e:
  528. self.assertEqual(len(dir(e.__traceback__)), 4)
  529. # test that object has a __dir__()
  530. self.assertEqual(sorted([].__dir__()), dir([]))
  531. def test_divmod(self):
  532. self.assertEqual(divmod(12, 7), (1, 5))
  533. self.assertEqual(divmod(-12, 7), (-2, 2))
  534. self.assertEqual(divmod(12, -7), (-2, -2))
  535. self.assertEqual(divmod(-12, -7), (1, -5))
  536. self.assertEqual(divmod(-sys.maxsize-1, -1), (sys.maxsize+1, 0))
  537. for num, denom, exp_result in [ (3.25, 1.0, (3.0, 0.25)),
  538. (-3.25, 1.0, (-4.0, 0.75)),
  539. (3.25, -1.0, (-4.0, -0.75)),
  540. (-3.25, -1.0, (3.0, -0.25))]:
  541. result = divmod(num, denom)
  542. self.assertAlmostEqual(result[0], exp_result[0])
  543. self.assertAlmostEqual(result[1], exp_result[1])
  544. self.assertRaises(TypeError, divmod)
  545. def test_eval(self):
  546. self.assertEqual(eval('1+1'), 2)
  547. self.assertEqual(eval(' 1+1\n'), 2)
  548. globals = {'a': 1, 'b': 2}
  549. locals = {'b': 200, 'c': 300}
  550. self.assertEqual(eval('a', globals) , 1)
  551. self.assertEqual(eval('a', globals, locals), 1)
  552. self.assertEqual(eval('b', globals, locals), 200)
  553. self.assertEqual(eval('c', globals, locals), 300)
  554. globals = {'a': 1, 'b': 2}
  555. locals = {'b': 200, 'c': 300}
  556. bom = b'\xef\xbb\xbf'
  557. self.assertEqual(eval(bom + b'a', globals, locals), 1)
  558. self.assertEqual(eval('"\xe5"', globals), "\xe5")
  559. self.assertRaises(TypeError, eval)
  560. self.assertRaises(TypeError, eval, ())
  561. self.assertRaises(SyntaxError, eval, bom[:2] + b'a')
  562. class X:
  563. def __getitem__(self, key):
  564. raise ValueError
  565. self.assertRaises(ValueError, eval, "foo", {}, X())
  566. def test_general_eval(self):
  567. # Tests that general mappings can be used for the locals argument
  568. class M:
  569. "Test mapping interface versus possible calls from eval()."
  570. def __getitem__(self, key):
  571. if key == 'a':
  572. return 12
  573. raise KeyError
  574. def keys(self):
  575. return list('xyz')
  576. m = M()
  577. g = globals()
  578. self.assertEqual(eval('a', g, m), 12)
  579. self.assertRaises(NameError, eval, 'b', g, m)
  580. self.assertEqual(eval('dir()', g, m), list('xyz'))
  581. self.assertEqual(eval('globals()', g, m), g)
  582. self.assertEqual(eval('locals()', g, m), m)
  583. self.assertRaises(TypeError, eval, 'a', m)
  584. class A:
  585. "Non-mapping"
  586. pass
  587. m = A()
  588. self.assertRaises(TypeError, eval, 'a', g, m)
  589. # Verify that dict subclasses work as well
  590. class D(dict):
  591. def __getitem__(self, key):
  592. if key == 'a':
  593. return 12
  594. return dict.__getitem__(self, key)
  595. def keys(self):
  596. return list('xyz')
  597. d = D()
  598. self.assertEqual(eval('a', g, d), 12)
  599. self.assertRaises(NameError, eval, 'b', g, d)
  600. self.assertEqual(eval('dir()', g, d), list('xyz'))
  601. self.assertEqual(eval('globals()', g, d), g)
  602. self.assertEqual(eval('locals()', g, d), d)
  603. # Verify locals stores (used by list comps)
  604. eval('[locals() for i in (2,3)]', g, d)
  605. eval('[locals() for i in (2,3)]', g, collections.UserDict())
  606. class SpreadSheet:
  607. "Sample application showing nested, calculated lookups."
  608. _cells = {}
  609. def __setitem__(self, key, formula):
  610. self._cells[key] = formula
  611. def __getitem__(self, key):
  612. return eval(self._cells[key], globals(), self)
  613. ss = SpreadSheet()
  614. ss['a1'] = '5'
  615. ss['a2'] = 'a1*6'
  616. ss['a3'] = 'a2*7'
  617. self.assertEqual(ss['a3'], 210)
  618. # Verify that dir() catches a non-list returned by eval
  619. # SF bug #1004669
  620. class C:
  621. def __getitem__(self, item):
  622. raise KeyError(item)
  623. def keys(self):
  624. return 1 # used to be 'a' but that's no longer an error
  625. self.assertRaises(TypeError, eval, 'dir()', globals(), C())
  626. def test_exec(self):
  627. g = {}
  628. exec('z = 1', g)
  629. if '__builtins__' in g:
  630. del g['__builtins__']
  631. self.assertEqual(g, {'z': 1})
  632. exec('z = 1+1', g)
  633. if '__builtins__' in g:
  634. del g['__builtins__']
  635. self.assertEqual(g, {'z': 2})
  636. g = {}
  637. l = {}
  638. with check_warnings():
  639. warnings.filterwarnings("ignore", "global statement",
  640. module="<string>")
  641. exec('global a; a = 1; b = 2', g, l)
  642. if '__builtins__' in g:
  643. del g['__builtins__']
  644. if '__builtins__' in l:
  645. del l['__builtins__']
  646. self.assertEqual((g, l), ({'a': 1}, {'b': 2}))
  647. def test_exec_globals(self):
  648. code = compile("print('Hello World!')", "", "exec")
  649. # no builtin function
  650. self.assertRaisesRegex(NameError, "name 'print' is not defined",
  651. exec, code, {'__builtins__': {}})
  652. # __builtins__ must be a mapping type
  653. self.assertRaises(TypeError,
  654. exec, code, {'__builtins__': 123})
  655. def test_exec_globals_frozen(self):
  656. class frozendict_error(Exception):
  657. pass
  658. class frozendict(dict):
  659. def __setitem__(self, key, value):
  660. raise frozendict_error("frozendict is readonly")
  661. # read-only builtins
  662. if isinstance(__builtins__, types.ModuleType):
  663. frozen_builtins = frozendict(__builtins__.__dict__)
  664. else:
  665. frozen_builtins = frozendict(__builtins__)
  666. code = compile("__builtins__['superglobal']=2; print(superglobal)", "test", "exec")
  667. self.assertRaises(frozendict_error,
  668. exec, code, {'__builtins__': frozen_builtins})
  669. # no __build_class__ function
  670. code = compile("class A: pass", "", "exec")
  671. self.assertRaisesRegex(NameError, "__build_class__ not found",
  672. exec, code, {'__builtins__': {}})
  673. # __build_class__ in a custom __builtins__
  674. exec(code, {'__builtins__': frozen_builtins})
  675. self.assertRaisesRegex(NameError, "__build_class__ not found",
  676. exec, code, {'__builtins__': frozendict()})
  677. # read-only globals
  678. namespace = frozendict({})
  679. code = compile("x=1", "test", "exec")
  680. self.assertRaises(frozendict_error,
  681. exec, code, namespace)
  682. def test_exec_globals_error_on_get(self):
  683. # custom `globals` or `builtins` can raise errors on item access
  684. class setonlyerror(Exception):
  685. pass
  686. class setonlydict(dict):
  687. def __getitem__(self, key):
  688. raise setonlyerror
  689. # globals' `__getitem__` raises
  690. code = compile("globalname", "test", "exec")
  691. self.assertRaises(setonlyerror,
  692. exec, code, setonlydict({'globalname': 1}))
  693. # builtins' `__getitem__` raises
  694. code = compile("superglobal", "test", "exec")
  695. self.assertRaises(setonlyerror, exec, code,
  696. {'__builtins__': setonlydict({'superglobal': 1})})
  697. def test_exec_globals_dict_subclass(self):
  698. class customdict(dict): # this one should not do anything fancy
  699. pass
  700. code = compile("superglobal", "test", "exec")
  701. # works correctly
  702. exec(code, {'__builtins__': customdict({'superglobal': 1})})
  703. # custom builtins dict subclass is missing key
  704. self.assertRaisesRegex(NameError, "name 'superglobal' is not defined",
  705. exec, code, {'__builtins__': customdict()})
  706. def test_exec_redirected(self):
  707. savestdout = sys.stdout
  708. sys.stdout = None # Whatever that cannot flush()
  709. try:
  710. # Used to raise SystemError('error return without exception set')
  711. exec('a')
  712. except NameError:
  713. pass
  714. finally:
  715. sys.stdout = savestdout
  716. def test_exec_closure(self):
  717. def function_without_closures():
  718. return 3 * 5
  719. result = 0
  720. def make_closure_functions():
  721. a = 2
  722. b = 3
  723. c = 5
  724. def three_freevars():
  725. nonlocal result
  726. nonlocal a
  727. nonlocal b
  728. result = a*b
  729. def four_freevars():
  730. nonlocal result
  731. nonlocal a
  732. nonlocal b
  733. nonlocal c
  734. result = a*b*c
  735. return three_freevars, four_freevars
  736. three_freevars, four_freevars = make_closure_functions()
  737. # "smoke" test
  738. result = 0
  739. exec(three_freevars.__code__,
  740. three_freevars.__globals__,
  741. closure=three_freevars.__closure__)
  742. self.assertEqual(result, 6)
  743. # should also work with a manually created closure
  744. result = 0
  745. my_closure = (CellType(35), CellType(72), three_freevars.__closure__[2])
  746. exec(three_freevars.__code__,
  747. three_freevars.__globals__,
  748. closure=my_closure)
  749. self.assertEqual(result, 2520)
  750. # should fail: closure isn't allowed
  751. # for functions without free vars
  752. self.assertRaises(TypeError,
  753. exec,
  754. function_without_closures.__code__,
  755. function_without_closures.__globals__,
  756. closure=my_closure)
  757. # should fail: closure required but wasn't specified
  758. self.assertRaises(TypeError,
  759. exec,
  760. three_freevars.__code__,
  761. three_freevars.__globals__,
  762. closure=None)
  763. # should fail: closure of wrong length
  764. self.assertRaises(TypeError,
  765. exec,
  766. three_freevars.__code__,
  767. three_freevars.__globals__,
  768. closure=four_freevars.__closure__)
  769. # should fail: closure using a list instead of a tuple
  770. my_closure = list(my_closure)
  771. self.assertRaises(TypeError,
  772. exec,
  773. three_freevars.__code__,
  774. three_freevars.__globals__,
  775. closure=my_closure)
  776. # should fail: closure tuple with one non-cell-var
  777. my_closure[0] = int
  778. my_closure = tuple(my_closure)
  779. self.assertRaises(TypeError,
  780. exec,
  781. three_freevars.__code__,
  782. three_freevars.__globals__,
  783. closure=my_closure)
  784. def test_filter(self):
  785. self.assertEqual(list(filter(lambda c: 'a' <= c <= 'z', 'Hello World')), list('elloorld'))
  786. self.assertEqual(list(filter(None, [1, 'hello', [], [3], '', None, 9, 0])), [1, 'hello', [3], 9])
  787. self.assertEqual(list(filter(lambda x: x > 0, [1, -3, 9, 0, 2])), [1, 9, 2])
  788. self.assertEqual(list(filter(None, Squares(10))), [1, 4, 9, 16, 25, 36, 49, 64, 81])
  789. self.assertEqual(list(filter(lambda x: x%2, Squares(10))), [1, 9, 25, 49, 81])
  790. def identity(item):
  791. return 1
  792. filter(identity, Squares(5))
  793. self.assertRaises(TypeError, filter)
  794. class BadSeq(object):
  795. def __getitem__(self, index):
  796. if index<4:
  797. return 42
  798. raise ValueError
  799. self.assertRaises(ValueError, list, filter(lambda x: x, BadSeq()))
  800. def badfunc():
  801. pass
  802. self.assertRaises(TypeError, list, filter(badfunc, range(5)))
  803. # test bltinmodule.c::filtertuple()
  804. self.assertEqual(list(filter(None, (1, 2))), [1, 2])
  805. self.assertEqual(list(filter(lambda x: x>=3, (1, 2, 3, 4))), [3, 4])
  806. self.assertRaises(TypeError, list, filter(42, (1, 2)))
  807. def test_filter_pickle(self):
  808. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  809. f1 = filter(filter_char, "abcdeabcde")
  810. f2 = filter(filter_char, "abcdeabcde")
  811. self.check_iter_pickle(f1, list(f2), proto)
  812. def test_getattr(self):
  813. self.assertTrue(getattr(sys, 'stdout') is sys.stdout)
  814. self.assertRaises(TypeError, getattr)
  815. self.assertRaises(TypeError, getattr, sys)
  816. msg = r"^attribute name must be string, not 'int'$"
  817. self.assertRaisesRegex(TypeError, msg, getattr, sys, 1)
  818. self.assertRaisesRegex(TypeError, msg, getattr, sys, 1, 'spam')
  819. self.assertRaises(AttributeError, getattr, sys, chr(sys.maxunicode))
  820. # unicode surrogates are not encodable to the default encoding (utf8)
  821. self.assertRaises(AttributeError, getattr, 1, "\uDAD1\uD51E")
  822. def test_hasattr(self):
  823. self.assertTrue(hasattr(sys, 'stdout'))
  824. self.assertRaises(TypeError, hasattr)
  825. self.assertRaises(TypeError, hasattr, sys)
  826. msg = r"^attribute name must be string, not 'int'$"
  827. self.assertRaisesRegex(TypeError, msg, hasattr, sys, 1)
  828. self.assertEqual(False, hasattr(sys, chr(sys.maxunicode)))
  829. # Check that hasattr propagates all exceptions outside of
  830. # AttributeError.
  831. class A:
  832. def __getattr__(self, what):
  833. raise SystemExit
  834. self.assertRaises(SystemExit, hasattr, A(), "b")
  835. class B:
  836. def __getattr__(self, what):
  837. raise ValueError
  838. self.assertRaises(ValueError, hasattr, B(), "b")
  839. def test_hash(self):
  840. hash(None)
  841. self.assertEqual(hash(1), hash(1))
  842. self.assertEqual(hash(1), hash(1.0))
  843. hash('spam')
  844. self.assertEqual(hash('spam'), hash(b'spam'))
  845. hash((0,1,2,3))
  846. def f(): pass
  847. hash(f)
  848. self.assertRaises(TypeError, hash, [])
  849. self.assertRaises(TypeError, hash, {})
  850. # Bug 1536021: Allow hash to return long objects
  851. class X:
  852. def __hash__(self):
  853. return 2**100
  854. self.assertEqual(type(hash(X())), int)
  855. class Z(int):
  856. def __hash__(self):
  857. return self
  858. self.assertEqual(hash(Z(42)), hash(42))
  859. def test_hex(self):
  860. self.assertEqual(hex(16), '0x10')
  861. self.assertEqual(hex(-16), '-0x10')
  862. self.assertRaises(TypeError, hex, {})
  863. def test_id(self):
  864. id(None)
  865. id(1)
  866. id(1.0)
  867. id('spam')
  868. id((0,1,2,3))
  869. id([0,1,2,3])
  870. id({'spam': 1, 'eggs': 2, 'ham': 3})
  871. # Test input() later, alphabetized as if it were raw_input
  872. def test_iter(self):
  873. self.assertRaises(TypeError, iter)
  874. self.assertRaises(TypeError, iter, 42, 42)
  875. lists = [("1", "2"), ["1", "2"], "12"]
  876. for l in lists:
  877. i = iter(l)
  878. self.assertEqual(next(i), '1')
  879. self.assertEqual(next(i), '2')
  880. self.assertRaises(StopIteration, next, i)
  881. def test_isinstance(self):
  882. class C:
  883. pass
  884. class D(C):
  885. pass
  886. class E:
  887. pass
  888. c = C()
  889. d = D()
  890. e = E()
  891. self.assertTrue(isinstance(c, C))
  892. self.assertTrue(isinstance(d, C))
  893. self.assertTrue(not isinstance(e, C))
  894. self.assertTrue(not isinstance(c, D))
  895. self.assertTrue(not isinstance('foo', E))
  896. self.assertRaises(TypeError, isinstance, E, 'foo')
  897. self.assertRaises(TypeError, isinstance)
  898. def test_issubclass(self):
  899. class C:
  900. pass
  901. class D(C):
  902. pass
  903. class E:
  904. pass
  905. c = C()
  906. d = D()
  907. e = E()
  908. self.assertTrue(issubclass(D, C))
  909. self.assertTrue(issubclass(C, C))
  910. self.assertTrue(not issubclass(C, D))
  911. self.assertRaises(TypeError, issubclass, 'foo', E)
  912. self.assertRaises(TypeError, issubclass, E, 'foo')
  913. self.assertRaises(TypeError, issubclass)
  914. def test_len(self):
  915. self.assertEqual(len('123'), 3)
  916. self.assertEqual(len(()), 0)
  917. self.assertEqual(len((1, 2, 3, 4)), 4)
  918. self.assertEqual(len([1, 2, 3, 4]), 4)
  919. self.assertEqual(len({}), 0)
  920. self.assertEqual(len({'a':1, 'b': 2}), 2)
  921. class BadSeq:
  922. def __len__(self):
  923. raise ValueError
  924. self.assertRaises(ValueError, len, BadSeq())
  925. class InvalidLen:
  926. def __len__(self):
  927. return None
  928. self.assertRaises(TypeError, len, InvalidLen())
  929. class FloatLen:
  930. def __len__(self):
  931. return 4.5
  932. self.assertRaises(TypeError, len, FloatLen())
  933. class NegativeLen:
  934. def __len__(self):
  935. return -10
  936. self.assertRaises(ValueError, len, NegativeLen())
  937. class HugeLen:
  938. def __len__(self):
  939. return sys.maxsize + 1
  940. self.assertRaises(OverflowError, len, HugeLen())
  941. class HugeNegativeLen:
  942. def __len__(self):
  943. return -sys.maxsize-10
  944. self.assertRaises(ValueError, len, HugeNegativeLen())
  945. class NoLenMethod(object): pass
  946. self.assertRaises(TypeError, len, NoLenMethod())
  947. def test_map(self):
  948. self.assertEqual(
  949. list(map(lambda x: x*x, range(1,4))),
  950. [1, 4, 9]
  951. )
  952. try:
  953. from math import sqrt
  954. except ImportError:
  955. def sqrt(x):
  956. return pow(x, 0.5)
  957. self.assertEqual(
  958. list(map(lambda x: list(map(sqrt, x)), [[16, 4], [81, 9]])),
  959. [[4.0, 2.0], [9.0, 3.0]]
  960. )
  961. self.assertEqual(
  962. list(map(lambda x, y: x+y, [1,3,2], [9,1,4])),
  963. [10, 4, 6]
  964. )
  965. def plus(*v):
  966. accu = 0
  967. for i in v: accu = accu + i
  968. return accu
  969. self.assertEqual(
  970. list(map(plus, [1, 3, 7])),
  971. [1, 3, 7]
  972. )
  973. self.assertEqual(
  974. list(map(plus, [1, 3, 7], [4, 9, 2])),
  975. [1+4, 3+9, 7+2]
  976. )
  977. self.assertEqual(
  978. list(map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0])),
  979. [1+4+1, 3+9+1, 7+2+0]
  980. )
  981. self.assertEqual(
  982. list(map(int, Squares(10))),
  983. [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  984. )
  985. def Max(a, b):
  986. if a is None:
  987. return b
  988. if b is None:
  989. return a
  990. return max(a, b)
  991. self.assertEqual(
  992. list(map(Max, Squares(3), Squares(2))),
  993. [0, 1]
  994. )
  995. self.assertRaises(TypeError, map)
  996. self.assertRaises(TypeError, map, lambda x: x, 42)
  997. class BadSeq:
  998. def __iter__(self):
  999. raise ValueError
  1000. yield None
  1001. self.assertRaises(ValueError, list, map(lambda x: x, BadSeq()))
  1002. def badfunc(x):
  1003. raise RuntimeError
  1004. self.assertRaises(RuntimeError, list, map(badfunc, range(5)))
  1005. def test_map_pickle(self):
  1006. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  1007. m1 = map(map_char, "Is this the real life?")
  1008. m2 = map(map_char, "Is this the real life?")
  1009. self.check_iter_pickle(m1, list(m2), proto)
  1010. def test_max(self):
  1011. self.assertEqual(max('123123'), '3')
  1012. self.assertEqual(max(1, 2, 3), 3)
  1013. self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3)
  1014. self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3)
  1015. self.assertEqual(max(1, 2, 3.0), 3.0)
  1016. self.assertEqual(max(1, 2.0, 3), 3)
  1017. self.assertEqual(max(1.0, 2, 3), 3)
  1018. with self.assertRaisesRegex(
  1019. TypeError,
  1020. 'max expected at least 1 argument, got 0'
  1021. ):
  1022. max()
  1023. self.assertRaises(TypeError, max, 42)
  1024. self.assertRaises(ValueError, max, ())
  1025. class BadSeq:
  1026. def __getitem__(self, index):
  1027. raise ValueError
  1028. self.assertRaises(ValueError, max, BadSeq())
  1029. for stmt in (
  1030. "max(key=int)", # no args
  1031. "max(default=None)",
  1032. "max(1, 2, default=None)", # require container for default
  1033. "max(default=None, key=int)",
  1034. "max(1, key=int)", # single arg not iterable
  1035. "max(1, 2, keystone=int)", # wrong keyword
  1036. "max(1, 2, key=int, abc=int)", # two many keywords
  1037. "max(1, 2, key=1)", # keyfunc is not callable
  1038. ):
  1039. try:
  1040. exec(stmt, globals())
  1041. except TypeError:
  1042. pass
  1043. else:
  1044. self.fail(stmt)
  1045. self.assertEqual(max((1,), key=neg), 1) # one elem iterable
  1046. self.assertEqual(max((1,2), key=neg), 1) # two elem iterable
  1047. self.assertEqual(max(1, 2, key=neg), 1) # two elems
  1048. self.assertEqual(max((), default=None), None) # zero elem iterable
  1049. self.assertEqual(max((1,), default=None), 1) # one elem iterable
  1050. self.assertEqual(max((1,2), default=None), 2) # two elem iterable
  1051. self.assertEqual(max((), default=1, key=neg), 1)
  1052. self.assertEqual(max((1, 2), default=3, key=neg), 1)
  1053. self.assertEqual(max((1, 2), key=None), 2)
  1054. data = [random.randrange(200) for i in range(100)]
  1055. keys = dict((elem, random.randrange(50)) for elem in data)
  1056. f = keys.__getitem__
  1057. self.assertEqual(max(data, key=f),
  1058. sorted(reversed(data), key=f)[-1])
  1059. def test_min(self):
  1060. self.assertEqual(min('123123'), '1')
  1061. self.assertEqual(min(1, 2, 3), 1)
  1062. self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1)
  1063. self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1)
  1064. self.assertEqual(min(1, 2, 3.0), 1)
  1065. self.assertEqual(min(1, 2.0, 3), 1)
  1066. self.assertEqual(min(1.0, 2, 3), 1.0)
  1067. with self.assertRaisesRegex(
  1068. TypeError,
  1069. 'min expected at least 1 argument, got 0'
  1070. ):
  1071. min()
  1072. self.assertRaises(TypeError, min, 42)
  1073. self.assertRaises(ValueError, min, ())
  1074. class BadSeq:
  1075. def __getitem__(self, index):
  1076. raise ValueError
  1077. self.assertRaises(ValueError, min, BadSeq())
  1078. for stmt in (
  1079. "min(key=int)", # no args
  1080. "min(default=None)",
  1081. "min(1, 2, default=None)", # require container for default
  1082. "min(default=None, key=int)",
  1083. "min(1, key=int)", # single arg not iterable
  1084. "min(1, 2, keystone=int)", # wrong keyword
  1085. "min(1, 2, key=int, abc=int)", # two many keywords
  1086. "min(1, 2, key=1)", # keyfunc is not callable
  1087. ):
  1088. try:
  1089. exec(stmt, globals())
  1090. except TypeError:
  1091. pass
  1092. else:
  1093. self.fail(stmt)
  1094. self.assertEqual(min((1,), key=neg), 1) # one elem iterable
  1095. self.assertEqual(min((1,2), key=neg), 2) # two elem iterable
  1096. self.assertEqual(min(1, 2, key=neg), 2) # two elems
  1097. self.assertEqual(min((), default=None), None) # zero elem iterable
  1098. self.assertEqual(min((1,), default=None), 1) # one elem iterable
  1099. self.assertEqual(min((1,2), default=None), 1) # two elem iterable
  1100. self.assertEqual(min((), default=1, key=neg), 1)
  1101. self.assertEqual(min((1, 2), default=1, key=neg), 2)
  1102. self.assertEqual(min((1, 2), key=None), 1)
  1103. data = [random.randrange(200) for i in range(100)]
  1104. keys = dict((elem, random.randrange(50)) for elem in data)
  1105. f = keys.__getitem__
  1106. self.assertEqual(min(data, key=f),
  1107. sorted(data, key=f)[0])
  1108. def test_next(self):
  1109. it = iter(range(2))
  1110. self.assertEqual(next(it), 0)
  1111. self.assertEqual(next(it), 1)
  1112. self.assertRaises(StopIteration, next, it)
  1113. self.assertRaises(StopIteration, next, it)
  1114. self.assertEqual(next(it, 42), 42)
  1115. class Iter(object):
  1116. def __iter__(self):
  1117. return self
  1118. def __next__(self):
  1119. raise StopIteration
  1120. it = iter(Iter())
  1121. self.assertEqual(next(it, 42), 42)
  1122. self.assertRaises(StopIteration, next, it)
  1123. def gen():
  1124. yield 1
  1125. return
  1126. it = gen()
  1127. self.assertEqual(next(it), 1)
  1128. self.assertRaises(StopIteration, next, it)
  1129. self.assertEqual(next(it, 42), 42)
  1130. def test_oct(self):
  1131. self.assertEqual(oct(100), '0o144')
  1132. self.assertEqual(oct(-100), '-0o144')
  1133. self.assertRaises(TypeError, oct, ())
  1134. def write_testfile(self):
  1135. # NB the first 4 lines are also used to test input, below
  1136. fp = open(TESTFN, 'w', encoding="utf-8")
  1137. self.addCleanup(unlink, TESTFN)
  1138. with fp:
  1139. fp.write('1+1\n')
  1140. fp.write('The quick brown fox jumps over the lazy dog')
  1141. fp.write('.\n')
  1142. fp.write('Dear John\n')
  1143. fp.write('XXX'*100)
  1144. fp.write('YYY'*100)
  1145. def test_open(self):
  1146. self.write_testfile()
  1147. fp = open(TESTFN, encoding="utf-8")
  1148. with fp:
  1149. self.assertEqual(fp.readline(4), '1+1\n')
  1150. self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\n')
  1151. self.assertEqual(fp.readline(4), 'Dear')
  1152. self.assertEqual(fp.readline(100), ' John\n')
  1153. self.assertEqual(fp.read(300), 'XXX'*100)
  1154. self.assertEqual(fp.read(1000), 'YYY'*100)
  1155. # embedded null bytes and characters
  1156. self.assertRaises(ValueError, open, 'a\x00b')
  1157. self.assertRaises(ValueError, open, b'a\x00b')
  1158. @unittest.skipIf(sys.flags.utf8_mode, "utf-8 mode is enabled")
  1159. def test_open_default_encoding(self):
  1160. old_environ = dict(os.environ)
  1161. try:
  1162. # try to get a user preferred encoding different than the current
  1163. # locale encoding to check that open() uses the current locale
  1164. # encoding and not the user preferred encoding
  1165. for key in ('LC_ALL', 'LANG', 'LC_CTYPE'):
  1166. if key in os.environ:
  1167. del os.environ[key]
  1168. self.write_testfile()
  1169. current_locale_encoding = locale.getencoding()
  1170. with warnings.catch_warnings():
  1171. warnings.simplefilter("ignore", EncodingWarning)
  1172. fp = open(TESTFN, 'w')
  1173. with fp:
  1174. self.assertEqual(fp.encoding, current_locale_encoding)
  1175. finally:
  1176. os.environ.clear()
  1177. os.environ.update(old_environ)
  1178. @support.requires_subprocess()
  1179. def test_open_non_inheritable(self):
  1180. fileobj = open(__file__, encoding="utf-8")
  1181. with fileobj:
  1182. self.assertFalse(os.get_inheritable(fileobj.fileno()))
  1183. def test_ord(self):
  1184. self.assertEqual(ord(' '), 32)
  1185. self.assertEqual(ord('A'), 65)
  1186. self.assertEqual(ord('a'), 97)
  1187. self.assertEqual(ord('\x80'), 128)
  1188. self.assertEqual(ord('\xff'), 255)
  1189. self.assertEqual(ord(b' '), 32)
  1190. self.assertEqual(ord(b'A'), 65)
  1191. self.assertEqual(ord(b'a'), 97)
  1192. self.assertEqual(ord(b'\x80'), 128)
  1193. self.assertEqual(ord(b'\xff'), 255)
  1194. self.assertEqual(ord(chr(sys.maxunicode)), sys.maxunicode)
  1195. self.assertRaises(TypeError, ord, 42)
  1196. self.assertEqual(ord(chr(0x10FFFF)), 0x10FFFF)
  1197. self.assertEqual(ord("\U0000FFFF"), 0x0000FFFF)
  1198. self.assertEqual(ord("\U00010000"), 0x00010000)
  1199. self.assertEqual(ord("\U00010001"), 0x00010001)
  1200. self.assertEqual(ord("\U000FFFFE"), 0x000FFFFE)
  1201. self.assertEqual(ord("\U000FFFFF"), 0x000FFFFF)
  1202. self.assertEqual(ord("\U00100000"), 0x00100000)
  1203. self.assertEqual(ord("\U00100001"), 0x00100001)
  1204. self.assertEqual(ord("\U0010FFFE"), 0x0010FFFE)
  1205. self.assertEqual(ord("\U0010FFFF"), 0x0010FFFF)
  1206. def test_pow(self):
  1207. self.assertEqual(pow(0,0), 1)
  1208. self.assertEqual(pow(0,1), 0)
  1209. self.assertEqual(pow(1,0), 1)
  1210. self.assertEqual(pow(1,1), 1)
  1211. self.assertEqual(pow(2,0), 1)
  1212. self.assertEqual(pow(2,10), 1024)
  1213. self.assertEqual(pow(2,20), 1024*1024)
  1214. self.assertEqual(pow(2,30), 1024*1024*1024)
  1215. self.assertEqual(pow(-2,0), 1)
  1216. self.assertEqual(pow(-2,1), -2)
  1217. self.assertEqual(pow(-2,2), 4)
  1218. self.assertEqual(pow(-2,3), -8)
  1219. self.assertAlmostEqual(pow(0.,0), 1.)
  1220. self.assertAlmostEqual(pow(0.,1), 0.)
  1221. self.assertAlmostEqual(pow(1.,0), 1.)
  1222. self.assertAlmostEqual(pow(1.,1), 1.)
  1223. self.assertAlmostEqual(pow(2.,0), 1.)
  1224. self.assertAlmostEqual(pow(2.,10), 1024.)
  1225. self.assertAlmostEqual(pow(2.,20), 1024.*1024.)
  1226. self.assertAlmostEqual(pow(2.,30), 1024.*1024.*1024.)
  1227. self.assertAlmostEqual(pow(-2.,0), 1.)
  1228. self.assertAlmostEqual(pow(-2.,1), -2.)
  1229. self.assertAlmostEqual(pow(-2.,2), 4.)
  1230. self.assertAlmostEqual(pow(-2.,3), -8.)
  1231. for x in 2, 2.0:
  1232. for y in 10, 10.0:
  1233. for z in 1000, 1000.0:
  1234. if isinstance(x, float) or \
  1235. isinstance(y, float) or \
  1236. isinstance(z, float):
  1237. self.assertRaises(TypeError, pow, x, y, z)
  1238. else:
  1239. self.assertAlmostEqual(pow(x, y, z), 24.0)
  1240. self.assertAlmostEqual(pow(-1, 0.5), 1j)
  1241. self.assertAlmostEqual(pow(-1, 1/3), 0.5 + 0.8660254037844386j)
  1242. # See test_pow for additional tests for three-argument pow.
  1243. self.assertEqual(pow(-1, -2, 3), 1)
  1244. self.assertRaises(ValueError, pow, 1, 2, 0)
  1245. self.assertRaises(TypeError, pow)
  1246. # Test passing in arguments as keywords.
  1247. self.assertEqual(pow(0, exp=0), 1)
  1248. self.assertEqual(pow(base=2, exp=4), 16)
  1249. self.assertEqual(pow(base=5, exp=2, mod=14), 11)
  1250. twopow = partial(pow, base=2)
  1251. self.assertEqual(twopow(exp=5), 32)
  1252. fifth_power = partial(pow, exp=5)
  1253. self.assertEqual(fifth_power(2), 32)
  1254. mod10 = partial(pow, mod=10)
  1255. self.assertEqual(mod10(2, 6), 4)
  1256. self.assertEqual(mod10(exp=6, base=2), 4)
  1257. def test_input(self):
  1258. self.write_testfile()
  1259. fp = open(TESTFN, encoding="utf-8")
  1260. savestdin = sys.stdin
  1261. savestdout = sys.stdout # Eats the echo
  1262. try:
  1263. sys.stdin = fp
  1264. sys.stdout = BitBucket()
  1265. self.assertEqual(input(), "1+1")
  1266. self.assertEqual(input(), 'The quick brown fox jumps over the lazy dog.')
  1267. self.assertEqual(input('testing\n'), 'Dear John')
  1268. # SF 1535165: don't segfault on closed stdin
  1269. # sys.stdout must be a regular file for triggering
  1270. sys.stdout = savestdout
  1271. sys.stdin.close()
  1272. self.assertRaises(ValueError, input)
  1273. sys.stdout = BitBucket()
  1274. sys.stdin = io.StringIO("NULL\0")
  1275. self.assertRaises(TypeError, input, 42, 42)
  1276. sys.stdin = io.StringIO(" 'whitespace'")
  1277. self.assertEqual(input(), " 'whitespace'")
  1278. sys.stdin = io.StringIO()
  1279. self.assertRaises(EOFError, input)
  1280. del sys.stdout
  1281. self.assertRaises(RuntimeError, input, 'prompt')
  1282. del sys.stdin
  1283. self.assertRaises(RuntimeError, input, 'prompt')
  1284. finally:
  1285. sys.stdin = savestdin
  1286. sys.stdout = savestdout
  1287. fp.close()
  1288. # test_int(): see test_int.py for tests of built-in function int().
  1289. def test_repr(self):
  1290. self.assertEqual(repr(''), '\'\'')
  1291. self.assertEqual(repr(0), '0')
  1292. self.assertEqual(repr(()), '()')
  1293. self.assertEqual(repr([]), '[]')
  1294. self.assertEqual(repr({}), '{}')
  1295. a = []
  1296. a.append(a)
  1297. self.assertEqual(repr(a), '[[...]]')
  1298. a = {}
  1299. a[0] = a
  1300. self.assertEqual(repr(a), '{0: {...}}')
  1301. def test_round(self):
  1302. self.assertEqual(round(0.0), 0.0)
  1303. self.assertEqual(type(round(0.0)), int)
  1304. self.assertEqual(round(1.0), 1.0)
  1305. self.assertEqual(round(10.0), 10.0)
  1306. self.assertEqual(round(1000000000.0), 1000000000.0)
  1307. self.assertEqual(round(1e20), 1e20)
  1308. self.assertEqual(round(-1.0), -1.0)
  1309. self.assertEqual(round(-10.0), -10.0)
  1310. self.assertEqual(round(-1000000000.0), -1000000000.0)
  1311. self.assertEqual(round(-1e20), -1e20)
  1312. self.assertEqual(round(0.1), 0.0)
  1313. self.assertEqual(round(1.1), 1.0)
  1314. self.assertEqual(round(10.1), 10.0)
  1315. self.assertEqual(round(1000000000.1), 1000000000.0)
  1316. self.assertEqual(round(-1.1), -1.0)
  1317. self.assertEqual(round(-10.1), -10.0)
  1318. self.assertEqual(round(-1000000000.1), -1000000000.0)
  1319. self.assertEqual(round(0.9), 1.0)
  1320. self.assertEqual(round(9.9), 10.0)
  1321. self.assertEqual(round(999999999.9), 1000000000.0)
  1322. self.assertEqual(round(-0.9), -1.0)
  1323. self.assertEqual(round(-9.9), -10.0)
  1324. self.assertEqual(round(-999999999.9), -1000000000.0)
  1325. self.assertEqual(round(-8.0, -1), -10.0)
  1326. self.assertEqual(type(round(-8.0, -1)), float)
  1327. self.assertEqual(type(round(-8.0, 0)), float)
  1328. self.assertEqual(type(round(-8.0, 1)), float)
  1329. # Check even / odd rounding behaviour
  1330. self.assertEqual(round(5.5), 6)
  1331. self.assertEqual(round(6.5), 6)
  1332. self.assertEqual(round(-5.5), -6)
  1333. self.assertEqual(round(-6.5), -6)
  1334. # Check behavior on ints
  1335. self.assertEqual(round(0), 0)
  1336. self.assertEqual(round(8), 8)
  1337. self.assertEqual(round(-8), -8)
  1338. self.assertEqual(type(round(0)), int)
  1339. self.assertEqual(type(round(-8, -1)), int)
  1340. self.assertEqual(type(round(-8, 0)), int)
  1341. self.assertEqual(type(round(-8, 1)), int)
  1342. # test new kwargs
  1343. self.assertEqual(round(number=-8.0, ndigits=-1), -10.0)
  1344. self.assertRaises(TypeError, round)
  1345. # test generic rounding delegation for reals
  1346. class TestRound:
  1347. def __round__(self):
  1348. return 23
  1349. class TestNoRound:
  1350. pass
  1351. self.assertEqual(round(TestRound()), 23)
  1352. self.assertRaises(TypeError, round, 1, 2, 3)
  1353. self.assertRaises(TypeError, round, TestNoRound())
  1354. t = TestNoRound()
  1355. t.__round__ = lambda *args: args
  1356. self.assertRaises(TypeError, round, t)
  1357. self.assertRaises(TypeError, round, t, 0)
  1358. # Some versions of glibc for alpha have a bug that affects
  1359. # float -> integer rounding (floor, ceil, rint, round) for
  1360. # values in the range [2**52, 2**53). See:
  1361. #
  1362. # http://sources.redhat.com/bugzilla/show_bug.cgi?id=5350
  1363. #
  1364. # We skip this test on Linux/alpha if it would fail.
  1365. linux_alpha = (platform.system().startswith('Linux') and
  1366. platform.machine().startswith('alpha'))
  1367. system_round_bug = round(5e15+1) != 5e15+1
  1368. @unittest.skipIf(linux_alpha and system_round_bug,
  1369. "test will fail; failure is probably due to a "
  1370. "buggy system round function")
  1371. def test_round_large(self):
  1372. # Issue #1869: integral floats should remain unchanged
  1373. self.assertEqual(round(5e15-1), 5e15-1)
  1374. self.assertEqual(round(5e15), 5e15)
  1375. self.assertEqual(round(5e15+1), 5e15+1)
  1376. self.assertEqual(round(5e15+2), 5e15+2)
  1377. self.assertEqual(round(5e15+3), 5e15+3)
  1378. def test_bug_27936(self):
  1379. # Verify that ndigits=None means the same as passing in no argument
  1380. for x in [1234,
  1381. 1234.56,
  1382. decimal.Decimal('1234.56'),
  1383. fractions.Fraction(123456, 100)]:
  1384. self.assertEqual(round(x, None), round(x))
  1385. self.assertEqual(type(round(x, None)), type(round(x)))
  1386. def test_setattr(self):
  1387. setattr(sys, 'spam', 1)
  1388. self.assertEqual(sys.spam, 1)
  1389. self.assertRaises(TypeError, setattr)
  1390. self.assertRaises(TypeError, setattr, sys)
  1391. self.assertRaises(TypeError, setattr, sys, 'spam')
  1392. msg = r"^attribute name must be string, not 'int'$"
  1393. self.assertRaisesRegex(TypeError, msg, setattr, sys, 1, 'spam')
  1394. # test_str(): see test_unicode.py and test_bytes.py for str() tests.
  1395. def test_sum(self):
  1396. self.assertEqual(sum([]), 0)
  1397. self.assertEqual(sum(list(range(2,8))), 27)
  1398. self.assertEqual(sum(iter(list(range(2,8)))), 27)
  1399. self.assertEqual(sum(Squares(10)), 285)
  1400. self.assertEqual(sum(iter(Squares(10))), 285)
  1401. self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3])
  1402. self.assertEqual(sum(range(10), 1000), 1045)
  1403. self.assertEqual(sum(range(10), start=1000), 1045)
  1404. self.assertEqual(sum(range(10), 2**31-5), 2**31+40)
  1405. self.assertEqual(sum(range(10), 2**63-5), 2**63+40)
  1406. self.assertEqual(sum(i % 2 != 0 for i in range(10)), 5)
  1407. self.assertEqual(sum((i % 2 != 0 for i in range(10)), 2**31-3),
  1408. 2**31+2)
  1409. self.assertEqual(sum((i % 2 != 0 for i in range(10)), 2**63-3),
  1410. 2**63+2)
  1411. self.assertIs(sum([], False), False)
  1412. self.assertEqual(sum(i / 2 for i in range(10)), 22.5)
  1413. self.assertEqual(sum((i / 2 for i in range(10)), 1000), 1022.5)
  1414. self.assertEqual(sum((i / 2 for i in range(10)), 1000.25), 1022.75)
  1415. self.assertEqual(sum([0.5, 1]), 1.5)
  1416. self.assertEqual(sum([1, 0.5]), 1.5)
  1417. self.assertEqual(repr(sum([-0.0])), '0.0')
  1418. self.assertEqual(repr(sum([-0.0], -0.0)), '-0.0')
  1419. self.assertEqual(repr(sum([], -0.0)), '-0.0')
  1420. self.assertRaises(TypeError, sum)
  1421. self.assertRaises(TypeError, sum, 42)
  1422. self.assertRaises(TypeError, sum, ['a', 'b', 'c'])
  1423. self.assertRaises(TypeError, sum, ['a', 'b', 'c'], '')
  1424. self.assertRaises(TypeError, sum, [b'a', b'c'], b'')
  1425. values = [bytearray(b'a'), bytearray(b'b')]
  1426. self.assertRaises(TypeError, sum, values, bytearray(b''))
  1427. self.assertRaises(TypeError, sum, [[1], [2], [3]])
  1428. self.assertRaises(TypeError, sum, [{2:3}])
  1429. self.assertRaises(TypeError, sum, [{2:3}]*2, {2:3})
  1430. self.assertRaises(TypeError, sum, [], '')
  1431. self.assertRaises(TypeError, sum, [], b'')
  1432. self.assertRaises(TypeError, sum, [], bytearray())
  1433. class BadSeq:
  1434. def __getitem__(self, index):
  1435. raise ValueError
  1436. self.assertRaises(ValueError, sum, BadSeq())
  1437. empty = []
  1438. sum(([x] for x in range(10)), empty)
  1439. self.assertEqual(empty, [])
  1440. def test_type(self):
  1441. self.assertEqual(type(''), type('123'))
  1442. self.assertNotEqual(type(''), type(()))
  1443. # We don't want self in vars(), so these are static methods
  1444. @staticmethod
  1445. def get_vars_f0():
  1446. return vars()
  1447. @staticmethod
  1448. def get_vars_f2():
  1449. BuiltinTest.get_vars_f0()
  1450. a = 1
  1451. b = 2
  1452. return vars()
  1453. class C_get_vars(object):
  1454. def getDict(self):
  1455. return {'a':2}
  1456. __dict__ = property(fget=getDict)
  1457. def test_vars(self):
  1458. self.assertEqual(set(vars()), set(dir()))
  1459. self.assertEqual(set(vars(sys)), set(dir(sys)))
  1460. self.assertEqual(self.get_vars_f0(), {})
  1461. self.assertEqual(self.get_vars_f2(), {'a': 1, 'b': 2})
  1462. self.assertRaises(TypeError, vars, 42, 42)
  1463. self.assertRaises(TypeError, vars, 42)
  1464. self.assertEqual(vars(self.C_get_vars()), {'a':2})
  1465. def iter_error(self, iterable, error):
  1466. """Collect `iterable` into a list, catching an expected `error`."""
  1467. items = []
  1468. with self.assertRaises(error):
  1469. for item in iterable:
  1470. items.append(item)
  1471. return items
  1472. def test_zip(self):
  1473. a = (1, 2, 3)
  1474. b = (4, 5, 6)
  1475. t = [(1, 4), (2, 5), (3, 6)]
  1476. self.assertEqual(list(zip(a, b)), t)
  1477. b = [4, 5, 6]
  1478. self.assertEqual(list(zip(a, b)), t)
  1479. b = (4, 5, 6, 7)
  1480. self.assertEqual(list(zip(a, b)), t)
  1481. class I:
  1482. def __getitem__(self, i):
  1483. if i < 0 or i > 2: raise IndexError
  1484. return i + 4
  1485. self.assertEqual(list(zip(a, I())), t)
  1486. self.assertEqual(list(zip()), [])
  1487. self.assertEqual(list(zip(*[])), [])
  1488. self.assertRaises(TypeError, zip, None)
  1489. class G:
  1490. pass
  1491. self.assertRaises(TypeError, zip, a, G())
  1492. self.assertRaises(RuntimeError, zip, a, TestFailingIter())
  1493. # Make sure zip doesn't try to allocate a billion elements for the
  1494. # result list when one of its arguments doesn't say how long it is.
  1495. # A MemoryError is the most likely failure mode.
  1496. class SequenceWithoutALength:
  1497. def __getitem__(self, i):
  1498. if i == 5:
  1499. raise IndexError
  1500. else:
  1501. return i
  1502. self.assertEqual(
  1503. list(zip(SequenceWithoutALength(), range(2**30))),
  1504. list(enumerate(range(5)))
  1505. )
  1506. class BadSeq:
  1507. def __getitem__(self, i):
  1508. if i == 5:
  1509. raise ValueError
  1510. else:
  1511. return i
  1512. self.assertRaises(ValueError, list, zip(BadSeq(), BadSeq()))
  1513. def test_zip_pickle(self):
  1514. a = (1, 2, 3)
  1515. b = (4, 5, 6)
  1516. t = [(1, 4), (2, 5), (3, 6)]
  1517. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  1518. z1 = zip(a, b)
  1519. self.check_iter_pickle(z1, t, proto)
  1520. def test_zip_pickle_strict(self):
  1521. a = (1, 2, 3)
  1522. b = (4, 5, 6)
  1523. t = [(1, 4), (2, 5), (3, 6)]
  1524. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  1525. z1 = zip(a, b, strict=True)
  1526. self.check_iter_pickle(z1, t, proto)
  1527. def test_zip_pickle_strict_fail(self):
  1528. a = (1, 2, 3)
  1529. b = (4, 5, 6, 7)
  1530. t = [(1, 4), (2, 5), (3, 6)]
  1531. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  1532. z1 = zip(a, b, strict=True)
  1533. z2 = pickle.loads(pickle.dumps(z1, proto))
  1534. self.assertEqual(self.iter_error(z1, ValueError), t)
  1535. self.assertEqual(self.iter_error(z2, ValueError), t)
  1536. def test_zip_bad_iterable(self):
  1537. exception = TypeError()
  1538. class BadIterable:
  1539. def __iter__(self):
  1540. raise exception
  1541. with self.assertRaises(TypeError) as cm:
  1542. zip(BadIterable())
  1543. self.assertIs(cm.exception, exception)
  1544. def test_zip_strict(self):
  1545. self.assertEqual(tuple(zip((1, 2, 3), 'abc', strict=True)),
  1546. ((1, 'a'), (2, 'b'), (3, 'c')))
  1547. self.assertRaises(ValueError, tuple,
  1548. zip((1, 2, 3, 4), 'abc', strict=True))
  1549. self.assertRaises(ValueError, tuple,
  1550. zip((1, 2), 'abc', strict=True))
  1551. self.assertRaises(ValueError, tuple,
  1552. zip((1, 2), (1, 2), 'abc', strict=True))
  1553. def test_zip_strict_iterators(self):
  1554. x = iter(range(5))
  1555. y = [0]
  1556. z = iter(range(5))
  1557. self.assertRaises(ValueError, list,
  1558. (zip(x, y, z, strict=True)))
  1559. self.assertEqual(next(x), 2)
  1560. self.assertEqual(next(z), 1)
  1561. def test_zip_strict_error_handling(self):
  1562. class Error(Exception):
  1563. pass
  1564. class Iter:
  1565. def __init__(self, size):
  1566. self.size = size
  1567. def __iter__(self):
  1568. return self
  1569. def __next__(self):
  1570. self.size -= 1
  1571. if self.size < 0:
  1572. raise Error
  1573. return self.size
  1574. l1 = self.iter_error(zip("AB", Iter(1), strict=True), Error)
  1575. self.assertEqual(l1, [("A", 0)])
  1576. l2 = self.iter_error(zip("AB", Iter(2), "A", strict=True), ValueError)
  1577. self.assertEqual(l2, [("A", 1, "A")])
  1578. l3 = self.iter_error(zip("AB", Iter(2), "ABC", strict=True), Error)
  1579. self.assertEqual(l3, [("A", 1, "A"), ("B", 0, "B")])
  1580. l4 = self.iter_error(zip("AB", Iter(3), strict=True), ValueError)
  1581. self.assertEqual(l4, [("A", 2), ("B", 1)])
  1582. l5 = self.iter_error(zip(Iter(1), "AB", strict=True), Error)
  1583. self.assertEqual(l5, [(0, "A")])
  1584. l6 = self.iter_error(zip(Iter(2), "A", strict=True), ValueError)
  1585. self.assertEqual(l6, [(1, "A")])
  1586. l7 = self.iter_error(zip(Iter(2), "ABC", strict=True), Error)
  1587. self.assertEqual(l7, [(1, "A"), (0, "B")])
  1588. l8 = self.iter_error(zip(Iter(3), "AB", strict=True), ValueError)
  1589. self.assertEqual(l8, [(2, "A"), (1, "B")])
  1590. def test_zip_strict_error_handling_stopiteration(self):
  1591. class Iter:
  1592. def __init__(self, size):
  1593. self.size = size
  1594. def __iter__(self):
  1595. return self
  1596. def __next__(self):
  1597. self.size -= 1
  1598. if self.size < 0:
  1599. raise StopIteration
  1600. return self.size
  1601. l1 = self.iter_error(zip("AB", Iter(1), strict=True), ValueError)
  1602. self.assertEqual(l1, [("A", 0)])
  1603. l2 = self.iter_error(zip("AB", Iter(2), "A", strict=True), ValueError)
  1604. self.assertEqual(l2, [("A", 1, "A")])
  1605. l3 = self.iter_error(zip("AB", Iter(2), "ABC", strict=True), ValueError)
  1606. self.assertEqual(l3, [("A", 1, "A"), ("B", 0, "B")])
  1607. l4 = self.iter_error(zip("AB", Iter(3), strict=True), ValueError)
  1608. self.assertEqual(l4, [("A", 2), ("B", 1)])
  1609. l5 = self.iter_error(zip(Iter(1), "AB", strict=True), ValueError)
  1610. self.assertEqual(l5, [(0, "A")])
  1611. l6 = self.iter_error(zip(Iter(2), "A", strict=True), ValueError)
  1612. self.assertEqual(l6, [(1, "A")])
  1613. l7 = self.iter_error(zip(Iter(2), "ABC", strict=True), ValueError)
  1614. self.assertEqual(l7, [(1, "A"), (0, "B")])
  1615. l8 = self.iter_error(zip(Iter(3), "AB", strict=True), ValueError)
  1616. self.assertEqual(l8, [(2, "A"), (1, "B")])
  1617. @support.cpython_only
  1618. def test_zip_result_gc(self):
  1619. # bpo-42536: zip's tuple-reuse speed trick breaks the GC's assumptions
  1620. # about what can be untracked. Make sure we re-track result tuples
  1621. # whenever we reuse them.
  1622. it = zip([[]])
  1623. gc.collect()
  1624. # That GC collection probably untracked the recycled internal result
  1625. # tuple, which is initialized to (None,). Make sure it's re-tracked when
  1626. # it's mutated and returned from __next__:
  1627. self.assertTrue(gc.is_tracked(next(it)))
  1628. def test_format(self):
  1629. # Test the basic machinery of the format() builtin. Don't test
  1630. # the specifics of the various formatters
  1631. self.assertEqual(format(3, ''), '3')
  1632. # Returns some classes to use for various tests. There's
  1633. # an old-style version, and a new-style version
  1634. def classes_new():
  1635. class A(object):
  1636. def __init__(self, x):
  1637. self.x = x
  1638. def __format__(self, format_spec):
  1639. return str(self.x) + format_spec
  1640. class DerivedFromA(A):
  1641. pass
  1642. class Simple(object): pass
  1643. class DerivedFromSimple(Simple):
  1644. def __init__(self, x):
  1645. self.x = x
  1646. def __format__(self, format_spec):
  1647. return str(self.x) + format_spec
  1648. class DerivedFromSimple2(DerivedFromSimple): pass
  1649. return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2
  1650. def class_test(A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2):
  1651. self.assertEqual(format(A(3), 'spec'), '3spec')
  1652. self.assertEqual(format(DerivedFromA(4), 'spec'), '4spec')
  1653. self.assertEqual(format(DerivedFromSimple(5), 'abc'), '5abc')
  1654. self.assertEqual(format(DerivedFromSimple2(10), 'abcdef'),
  1655. '10abcdef')
  1656. class_test(*classes_new())
  1657. def empty_format_spec(value):
  1658. # test that:
  1659. # format(x, '') == str(x)
  1660. # format(x) == str(x)
  1661. self.assertEqual(format(value, ""), str(value))
  1662. self.assertEqual(format(value), str(value))
  1663. # for builtin types, format(x, "") == str(x)
  1664. empty_format_spec(17**13)
  1665. empty_format_spec(1.0)
  1666. empty_format_spec(3.1415e104)
  1667. empty_format_spec(-3.1415e104)
  1668. empty_format_spec(3.1415e-104)
  1669. empty_format_spec(-3.1415e-104)
  1670. empty_format_spec(object)
  1671. empty_format_spec(None)
  1672. # TypeError because self.__format__ returns the wrong type
  1673. class BadFormatResult:
  1674. def __format__(self, format_spec):
  1675. return 1.0
  1676. self.assertRaises(TypeError, format, BadFormatResult(), "")
  1677. # TypeError because format_spec is not unicode or str
  1678. self.assertRaises(TypeError, format, object(), 4)
  1679. self.assertRaises(TypeError, format, object(), object())
  1680. # tests for object.__format__ really belong elsewhere, but
  1681. # there's no good place to put them
  1682. x = object().__format__('')
  1683. self.assertTrue(x.startswith('<object object at'))
  1684. # first argument to object.__format__ must be string
  1685. self.assertRaises(TypeError, object().__format__, 3)
  1686. self.assertRaises(TypeError, object().__format__, object())
  1687. self.assertRaises(TypeError, object().__format__, None)
  1688. # --------------------------------------------------------------------
  1689. # Issue #7994: object.__format__ with a non-empty format string is
  1690. # disallowed
  1691. class A:
  1692. def __format__(self, fmt_str):
  1693. return format('', fmt_str)
  1694. self.assertEqual(format(A()), '')
  1695. self.assertEqual(format(A(), ''), '')
  1696. self.assertEqual(format(A(), 's'), '')
  1697. class B:
  1698. pass
  1699. class C(object):
  1700. pass
  1701. for cls in [object, B, C]:
  1702. obj = cls()
  1703. self.assertEqual(format(obj), str(obj))
  1704. self.assertEqual(format(obj, ''), str(obj))
  1705. with self.assertRaisesRegex(TypeError,
  1706. r'\b%s\b' % re.escape(cls.__name__)):
  1707. format(obj, 's')
  1708. # --------------------------------------------------------------------
  1709. # make sure we can take a subclass of str as a format spec
  1710. class DerivedFromStr(str): pass
  1711. self.assertEqual(format(0, DerivedFromStr('10')), ' 0')
  1712. def test_bin(self):
  1713. self.assertEqual(bin(0), '0b0')
  1714. self.assertEqual(bin(1), '0b1')
  1715. self.assertEqual(bin(-1), '-0b1')
  1716. self.assertEqual(bin(2**65), '0b1' + '0' * 65)
  1717. self.assertEqual(bin(2**65-1), '0b' + '1' * 65)
  1718. self.assertEqual(bin(-(2**65)), '-0b1' + '0' * 65)
  1719. self.assertEqual(bin(-(2**65-1)), '-0b' + '1' * 65)
  1720. def test_bytearray_translate(self):
  1721. x = bytearray(b"abc")
  1722. self.assertRaises(ValueError, x.translate, b"1", 1)
  1723. self.assertRaises(TypeError, x.translate, b"1"*256, 1)
  1724. def test_bytearray_extend_error(self):
  1725. array = bytearray()
  1726. bad_iter = map(int, "X")
  1727. self.assertRaises(ValueError, array.extend, bad_iter)
  1728. def test_construct_singletons(self):
  1729. for const in None, Ellipsis, NotImplemented:
  1730. tp = type(const)
  1731. self.assertIs(tp(), const)
  1732. self.assertRaises(TypeError, tp, 1, 2)
  1733. self.assertRaises(TypeError, tp, a=1, b=2)
  1734. def test_warning_notimplemented(self):
  1735. # Issue #35712: NotImplemented is a sentinel value that should never
  1736. # be evaluated in a boolean context (virtually all such use cases
  1737. # are a result of accidental misuse implementing rich comparison
  1738. # operations in terms of one another).
  1739. # For the time being, it will continue to evaluate as a true value, but
  1740. # issue a deprecation warning (with the eventual intent to make it
  1741. # a TypeError).
  1742. self.assertWarns(DeprecationWarning, bool, NotImplemented)
  1743. with self.assertWarns(DeprecationWarning):
  1744. self.assertTrue(NotImplemented)
  1745. with self.assertWarns(DeprecationWarning):
  1746. self.assertFalse(not NotImplemented)
  1747. class TestBreakpoint(unittest.TestCase):
  1748. def setUp(self):
  1749. # These tests require a clean slate environment. For example, if the
  1750. # test suite is run with $PYTHONBREAKPOINT set to something else, it
  1751. # will mess up these tests. Similarly for sys.breakpointhook.
  1752. # Cleaning the slate here means you can't use breakpoint() to debug
  1753. # these tests, but I think that's okay. Just use pdb.set_trace() if
  1754. # you must.
  1755. self.resources = ExitStack()
  1756. self.addCleanup(self.resources.close)
  1757. self.env = self.resources.enter_context(EnvironmentVarGuard())
  1758. del self.env['PYTHONBREAKPOINT']
  1759. self.resources.enter_context(
  1760. swap_attr(sys, 'breakpointhook', sys.__breakpointhook__))
  1761. def test_breakpoint(self):
  1762. with patch('pdb.set_trace') as mock:
  1763. breakpoint()
  1764. mock.assert_called_once()
  1765. def test_breakpoint_with_breakpointhook_set(self):
  1766. my_breakpointhook = MagicMock()
  1767. sys.breakpointhook = my_breakpointhook
  1768. breakpoint()
  1769. my_breakpointhook.assert_called_once_with()
  1770. def test_breakpoint_with_breakpointhook_reset(self):
  1771. my_breakpointhook = MagicMock()
  1772. sys.breakpointhook = my_breakpointhook
  1773. breakpoint()
  1774. my_breakpointhook.assert_called_once_with()
  1775. # Reset the hook and it will not be called again.
  1776. sys.breakpointhook = sys.__breakpointhook__
  1777. with patch('pdb.set_trace') as mock:
  1778. breakpoint()
  1779. mock.assert_called_once_with()
  1780. my_breakpointhook.assert_called_once_with()
  1781. def test_breakpoint_with_args_and_keywords(self):
  1782. my_breakpointhook = MagicMock()
  1783. sys.breakpointhook = my_breakpointhook
  1784. breakpoint(1, 2, 3, four=4, five=5)
  1785. my_breakpointhook.assert_called_once_with(1, 2, 3, four=4, five=5)
  1786. def test_breakpoint_with_passthru_error(self):
  1787. def my_breakpointhook():
  1788. pass
  1789. sys.breakpointhook = my_breakpointhook
  1790. self.assertRaises(TypeError, breakpoint, 1, 2, 3, four=4, five=5)
  1791. @unittest.skipIf(sys.flags.ignore_environment, '-E was given')
  1792. def test_envar_good_path_builtin(self):
  1793. self.env['PYTHONBREAKPOINT'] = 'int'
  1794. with patch('builtins.int') as mock:
  1795. breakpoint('7')
  1796. mock.assert_called_once_with('7')
  1797. @unittest.skipIf(sys.flags.ignore_environment, '-E was given')
  1798. def test_envar_good_path_other(self):
  1799. self.env['PYTHONBREAKPOINT'] = 'sys.exit'
  1800. with patch('sys.exit') as mock:
  1801. breakpoint()
  1802. mock.assert_called_once_with()
  1803. @unittest.skipIf(sys.flags.ignore_environment, '-E was given')
  1804. def test_envar_good_path_noop_0(self):
  1805. self.env['PYTHONBREAKPOINT'] = '0'
  1806. with patch('pdb.set_trace') as mock:
  1807. breakpoint()
  1808. mock.assert_not_called()
  1809. def test_envar_good_path_empty_string(self):
  1810. # PYTHONBREAKPOINT='' is the same as it not being set.
  1811. self.env['PYTHONBREAKPOINT'] = ''
  1812. with patch('pdb.set_trace') as mock:
  1813. breakpoint()
  1814. mock.assert_called_once_with()
  1815. @unittest.skipIf(sys.flags.ignore_environment, '-E was given')
  1816. def test_envar_unimportable(self):
  1817. for envar in (
  1818. '.', '..', '.foo', 'foo.', '.int', 'int.',
  1819. '.foo.bar', '..foo.bar', '/./',
  1820. 'nosuchbuiltin',
  1821. 'nosuchmodule.nosuchcallable',
  1822. ):
  1823. with self.subTest(envar=envar):
  1824. self.env['PYTHONBREAKPOINT'] = envar
  1825. mock = self.resources.enter_context(patch('pdb.set_trace'))
  1826. w = self.resources.enter_context(check_warnings(quiet=True))
  1827. breakpoint()
  1828. self.assertEqual(
  1829. str(w.message),
  1830. f'Ignoring unimportable $PYTHONBREAKPOINT: "{envar}"')
  1831. self.assertEqual(w.category, RuntimeWarning)
  1832. mock.assert_not_called()
  1833. def test_envar_ignored_when_hook_is_set(self):
  1834. self.env['PYTHONBREAKPOINT'] = 'sys.exit'
  1835. with patch('sys.exit') as mock:
  1836. sys.breakpointhook = int
  1837. breakpoint()
  1838. mock.assert_not_called()
  1839. @unittest.skipUnless(pty, "the pty and signal modules must be available")
  1840. class PtyTests(unittest.TestCase):
  1841. """Tests that use a pseudo terminal to guarantee stdin and stdout are
  1842. terminals in the test environment"""
  1843. @staticmethod
  1844. def handle_sighup(signum, frame):
  1845. # bpo-40140: if the process is the session leader, os.close(fd)
  1846. # of "pid, fd = pty.fork()" can raise SIGHUP signal:
  1847. # just ignore the signal.
  1848. pass
  1849. def run_child(self, child, terminal_input):
  1850. old_sighup = signal.signal(signal.SIGHUP, self.handle_sighup)
  1851. try:
  1852. return self._run_child(child, terminal_input)
  1853. finally:
  1854. signal.signal(signal.SIGHUP, old_sighup)
  1855. def _run_child(self, child, terminal_input):
  1856. r, w = os.pipe() # Pipe test results from child back to parent
  1857. try:
  1858. pid, fd = pty.fork()
  1859. except (OSError, AttributeError) as e:
  1860. os.close(r)
  1861. os.close(w)
  1862. self.skipTest("pty.fork() raised {}".format(e))
  1863. raise
  1864. if pid == 0:
  1865. # Child
  1866. try:
  1867. # Make sure we don't get stuck if there's a problem
  1868. signal.alarm(2)
  1869. os.close(r)
  1870. with open(w, "w") as wpipe:
  1871. child(wpipe)
  1872. except:
  1873. traceback.print_exc()
  1874. finally:
  1875. # We don't want to return to unittest...
  1876. os._exit(0)
  1877. # Parent
  1878. os.close(w)
  1879. os.write(fd, terminal_input)
  1880. # Get results from the pipe
  1881. with open(r, encoding="utf-8") as rpipe:
  1882. lines = []
  1883. while True:
  1884. line = rpipe.readline().strip()
  1885. if line == "":
  1886. # The other end was closed => the child exited
  1887. break
  1888. lines.append(line)
  1889. # Check the result was got and corresponds to the user's terminal input
  1890. if len(lines) != 2:
  1891. # Something went wrong, try to get at stderr
  1892. # Beware of Linux raising EIO when the slave is closed
  1893. child_output = bytearray()
  1894. while True:
  1895. try:
  1896. chunk = os.read(fd, 3000)
  1897. except OSError: # Assume EIO
  1898. break
  1899. if not chunk:
  1900. break
  1901. child_output.extend(chunk)
  1902. os.close(fd)
  1903. child_output = child_output.decode("ascii", "ignore")
  1904. self.fail("got %d lines in pipe but expected 2, child output was:\n%s"
  1905. % (len(lines), child_output))
  1906. # bpo-40155: Close the PTY before waiting for the child process
  1907. # completion, otherwise the child process hangs on AIX.
  1908. os.close(fd)
  1909. support.wait_process(pid, exitcode=0)
  1910. return lines
  1911. def check_input_tty(self, prompt, terminal_input, stdio_encoding=None):
  1912. if not sys.stdin.isatty() or not sys.stdout.isatty():
  1913. self.skipTest("stdin and stdout must be ttys")
  1914. def child(wpipe):
  1915. # Check the error handlers are accounted for
  1916. if stdio_encoding:
  1917. sys.stdin = io.TextIOWrapper(sys.stdin.detach(),
  1918. encoding=stdio_encoding,
  1919. errors='surrogateescape')
  1920. sys.stdout = io.TextIOWrapper(sys.stdout.detach(),
  1921. encoding=stdio_encoding,
  1922. errors='replace')
  1923. print("tty =", sys.stdin.isatty() and sys.stdout.isatty(), file=wpipe)
  1924. print(ascii(input(prompt)), file=wpipe)
  1925. lines = self.run_child(child, terminal_input + b"\r\n")
  1926. # Check we did exercise the GNU readline path
  1927. self.assertIn(lines[0], {'tty = True', 'tty = False'})
  1928. if lines[0] != 'tty = True':
  1929. self.skipTest("standard IO in should have been a tty")
  1930. input_result = eval(lines[1]) # ascii() -> eval() roundtrip
  1931. if stdio_encoding:
  1932. expected = terminal_input.decode(stdio_encoding, 'surrogateescape')
  1933. else:
  1934. expected = terminal_input.decode(sys.stdin.encoding) # what else?
  1935. self.assertEqual(input_result, expected)
  1936. def test_input_tty(self):
  1937. # Test input() functionality when wired to a tty (the code path
  1938. # is different and invokes GNU readline if available).
  1939. self.check_input_tty("prompt", b"quux")
  1940. def skip_if_readline(self):
  1941. # bpo-13886: When the readline module is loaded, PyOS_Readline() uses
  1942. # the readline implementation. In some cases, the Python readline
  1943. # callback rlhandler() is called by readline with a string without
  1944. # non-ASCII characters. Skip tests on non-ASCII characters if the
  1945. # readline module is loaded, since test_builtin is not intented to test
  1946. # the readline module, but the builtins module.
  1947. if 'readline' in sys.modules:
  1948. self.skipTest("the readline module is loaded")
  1949. def test_input_tty_non_ascii(self):
  1950. self.skip_if_readline()
  1951. # Check stdin/stdout encoding is used when invoking PyOS_Readline()
  1952. self.check_input_tty("prompté", b"quux\xe9", "utf-8")
  1953. def test_input_tty_non_ascii_unicode_errors(self):
  1954. self.skip_if_readline()
  1955. # Check stdin/stdout error handler is used when invoking PyOS_Readline()
  1956. self.check_input_tty("prompté", b"quux\xe9", "ascii")
  1957. def test_input_no_stdout_fileno(self):
  1958. # Issue #24402: If stdin is the original terminal but stdout.fileno()
  1959. # fails, do not use the original stdout file descriptor
  1960. def child(wpipe):
  1961. print("stdin.isatty():", sys.stdin.isatty(), file=wpipe)
  1962. sys.stdout = io.StringIO() # Does not support fileno()
  1963. input("prompt")
  1964. print("captured:", ascii(sys.stdout.getvalue()), file=wpipe)
  1965. lines = self.run_child(child, b"quux\r")
  1966. expected = (
  1967. "stdin.isatty(): True",
  1968. "captured: 'prompt'",
  1969. )
  1970. self.assertSequenceEqual(lines, expected)
  1971. class TestSorted(unittest.TestCase):
  1972. def test_basic(self):
  1973. data = list(range(100))
  1974. copy = data[:]
  1975. random.shuffle(copy)
  1976. self.assertEqual(data, sorted(copy))
  1977. self.assertNotEqual(data, copy)
  1978. data.reverse()
  1979. random.shuffle(copy)
  1980. self.assertEqual(data, sorted(copy, key=lambda x: -x))
  1981. self.assertNotEqual(data, copy)
  1982. random.shuffle(copy)
  1983. self.assertEqual(data, sorted(copy, reverse=True))
  1984. self.assertNotEqual(data, copy)
  1985. def test_bad_arguments(self):
  1986. # Issue #29327: The first argument is positional-only.
  1987. sorted([])
  1988. with self.assertRaises(TypeError):
  1989. sorted(iterable=[])
  1990. # Other arguments are keyword-only
  1991. sorted([], key=None)
  1992. with self.assertRaises(TypeError):
  1993. sorted([], None)
  1994. def test_inputtypes(self):
  1995. s = 'abracadabra'
  1996. types = [list, tuple, str]
  1997. for T in types:
  1998. self.assertEqual(sorted(s), sorted(T(s)))
  1999. s = ''.join(set(s)) # unique letters only
  2000. types = [str, set, frozenset, list, tuple, dict.fromkeys]
  2001. for T in types:
  2002. self.assertEqual(sorted(s), sorted(T(s)))
  2003. def test_baddecorator(self):
  2004. data = 'The quick Brown fox Jumped over The lazy Dog'.split()
  2005. self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0)
  2006. class ShutdownTest(unittest.TestCase):
  2007. def test_cleanup(self):
  2008. # Issue #19255: builtins are still available at shutdown
  2009. code = """if 1:
  2010. import builtins
  2011. import sys
  2012. class C:
  2013. def __del__(self):
  2014. print("before")
  2015. # Check that builtins still exist
  2016. len(())
  2017. print("after")
  2018. c = C()
  2019. # Make this module survive until builtins and sys are cleaned
  2020. builtins.here = sys.modules[__name__]
  2021. sys.here = sys.modules[__name__]
  2022. # Create a reference loop so that this module needs to go
  2023. # through a GC phase.
  2024. here = sys.modules[__name__]
  2025. """
  2026. # Issue #20599: Force ASCII encoding to get a codec implemented in C,
  2027. # otherwise the codec may be unloaded before C.__del__() is called, and
  2028. # so print("before") fails because the codec cannot be used to encode
  2029. # "before" to sys.stdout.encoding. For example, on Windows,
  2030. # sys.stdout.encoding is the OEM code page and these code pages are
  2031. # implemented in Python
  2032. rc, out, err = assert_python_ok("-c", code,
  2033. PYTHONIOENCODING="ascii")
  2034. self.assertEqual(["before", "after"], out.decode().splitlines())
  2035. class TestType(unittest.TestCase):
  2036. def test_new_type(self):
  2037. A = type('A', (), {})
  2038. self.assertEqual(A.__name__, 'A')
  2039. self.assertEqual(A.__qualname__, 'A')
  2040. self.assertEqual(A.__module__, __name__)
  2041. self.assertEqual(A.__bases__, (object,))
  2042. self.assertIs(A.__base__, object)
  2043. x = A()
  2044. self.assertIs(type(x), A)
  2045. self.assertIs(x.__class__, A)
  2046. class B:
  2047. def ham(self):
  2048. return 'ham%d' % self
  2049. C = type('C', (B, int), {'spam': lambda self: 'spam%s' % self})
  2050. self.assertEqual(C.__name__, 'C')
  2051. self.assertEqual(C.__qualname__, 'C')
  2052. self.assertEqual(C.__module__, __name__)
  2053. self.assertEqual(C.__bases__, (B, int))
  2054. self.assertIs(C.__base__, int)
  2055. self.assertIn('spam', C.__dict__)
  2056. self.assertNotIn('ham', C.__dict__)
  2057. x = C(42)
  2058. self.assertEqual(x, 42)
  2059. self.assertIs(type(x), C)
  2060. self.assertIs(x.__class__, C)
  2061. self.assertEqual(x.ham(), 'ham42')
  2062. self.assertEqual(x.spam(), 'spam42')
  2063. self.assertEqual(x.to_bytes(2, 'little'), b'\x2a\x00')
  2064. def test_type_nokwargs(self):
  2065. with self.assertRaises(TypeError):
  2066. type('a', (), {}, x=5)
  2067. with self.assertRaises(TypeError):
  2068. type('a', (), dict={})
  2069. def test_type_name(self):
  2070. for name in 'A', '\xc4', '\U0001f40d', 'B.A', '42', '':
  2071. with self.subTest(name=name):
  2072. A = type(name, (), {})
  2073. self.assertEqual(A.__name__, name)
  2074. self.assertEqual(A.__qualname__, name)
  2075. self.assertEqual(A.__module__, __name__)
  2076. with self.assertRaises(ValueError):
  2077. type('A\x00B', (), {})
  2078. with self.assertRaises(UnicodeEncodeError):
  2079. type('A\udcdcB', (), {})
  2080. with self.assertRaises(TypeError):
  2081. type(b'A', (), {})
  2082. C = type('C', (), {})
  2083. for name in 'A', '\xc4', '\U0001f40d', 'B.A', '42', '':
  2084. with self.subTest(name=name):
  2085. C.__name__ = name
  2086. self.assertEqual(C.__name__, name)
  2087. self.assertEqual(C.__qualname__, 'C')
  2088. self.assertEqual(C.__module__, __name__)
  2089. A = type('C', (), {})
  2090. with self.assertRaises(ValueError):
  2091. A.__name__ = 'A\x00B'
  2092. self.assertEqual(A.__name__, 'C')
  2093. with self.assertRaises(UnicodeEncodeError):
  2094. A.__name__ = 'A\udcdcB'
  2095. self.assertEqual(A.__name__, 'C')
  2096. with self.assertRaises(TypeError):
  2097. A.__name__ = b'A'
  2098. self.assertEqual(A.__name__, 'C')
  2099. def test_type_qualname(self):
  2100. A = type('A', (), {'__qualname__': 'B.C'})
  2101. self.assertEqual(A.__name__, 'A')
  2102. self.assertEqual(A.__qualname__, 'B.C')
  2103. self.assertEqual(A.__module__, __name__)
  2104. with self.assertRaises(TypeError):
  2105. type('A', (), {'__qualname__': b'B'})
  2106. self.assertEqual(A.__qualname__, 'B.C')
  2107. A.__qualname__ = 'D.E'
  2108. self.assertEqual(A.__name__, 'A')
  2109. self.assertEqual(A.__qualname__, 'D.E')
  2110. with self.assertRaises(TypeError):
  2111. A.__qualname__ = b'B'
  2112. self.assertEqual(A.__qualname__, 'D.E')
  2113. def test_type_doc(self):
  2114. for doc in 'x', '\xc4', '\U0001f40d', 'x\x00y', b'x', 42, None:
  2115. A = type('A', (), {'__doc__': doc})
  2116. self.assertEqual(A.__doc__, doc)
  2117. with self.assertRaises(UnicodeEncodeError):
  2118. type('A', (), {'__doc__': 'x\udcdcy'})
  2119. A = type('A', (), {})
  2120. self.assertEqual(A.__doc__, None)
  2121. for doc in 'x', '\xc4', '\U0001f40d', 'x\x00y', 'x\udcdcy', b'x', 42, None:
  2122. A.__doc__ = doc
  2123. self.assertEqual(A.__doc__, doc)
  2124. def test_bad_args(self):
  2125. with self.assertRaises(TypeError):
  2126. type()
  2127. with self.assertRaises(TypeError):
  2128. type('A', ())
  2129. with self.assertRaises(TypeError):
  2130. type('A', (), {}, ())
  2131. with self.assertRaises(TypeError):
  2132. type('A', (), dict={})
  2133. with self.assertRaises(TypeError):
  2134. type('A', [], {})
  2135. with self.assertRaises(TypeError):
  2136. type('A', (), types.MappingProxyType({}))
  2137. with self.assertRaises(TypeError):
  2138. type('A', (None,), {})
  2139. with self.assertRaises(TypeError):
  2140. type('A', (bool,), {})
  2141. with self.assertRaises(TypeError):
  2142. type('A', (int, str), {})
  2143. def test_bad_slots(self):
  2144. with self.assertRaises(TypeError):
  2145. type('A', (), {'__slots__': b'x'})
  2146. with self.assertRaises(TypeError):
  2147. type('A', (int,), {'__slots__': 'x'})
  2148. with self.assertRaises(TypeError):
  2149. type('A', (), {'__slots__': ''})
  2150. with self.assertRaises(TypeError):
  2151. type('A', (), {'__slots__': '42'})
  2152. with self.assertRaises(TypeError):
  2153. type('A', (), {'__slots__': 'x\x00y'})
  2154. with self.assertRaises(ValueError):
  2155. type('A', (), {'__slots__': 'x', 'x': 0})
  2156. with self.assertRaises(TypeError):
  2157. type('A', (), {'__slots__': ('__dict__', '__dict__')})
  2158. with self.assertRaises(TypeError):
  2159. type('A', (), {'__slots__': ('__weakref__', '__weakref__')})
  2160. class B:
  2161. pass
  2162. with self.assertRaises(TypeError):
  2163. type('A', (B,), {'__slots__': '__dict__'})
  2164. with self.assertRaises(TypeError):
  2165. type('A', (B,), {'__slots__': '__weakref__'})
  2166. def test_namespace_order(self):
  2167. # bpo-34320: namespace should preserve order
  2168. od = collections.OrderedDict([('a', 1), ('b', 2)])
  2169. od.move_to_end('a')
  2170. expected = list(od.items())
  2171. C = type('C', (), od)
  2172. self.assertEqual(list(C.__dict__.items())[:2], [('b', 2), ('a', 1)])
  2173. def load_tests(loader, tests, pattern):
  2174. from doctest import DocTestSuite
  2175. tests.addTest(DocTestSuite(builtins))
  2176. return tests
  2177. if __name__ == "__main__":
  2178. unittest.main()