test_exceptions.py 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682
  1. # Python test set -- part 5, built-in exceptions
  2. import copy
  3. import gc
  4. import os
  5. import sys
  6. import unittest
  7. import pickle
  8. import weakref
  9. import errno
  10. from textwrap import dedent
  11. from test.support import (captured_stderr, check_impl_detail,
  12. cpython_only, gc_collect,
  13. no_tracing, script_helper,
  14. SuppressCrashReport)
  15. from test.support.import_helper import import_module
  16. from test.support.os_helper import TESTFN, unlink
  17. from test.support.warnings_helper import check_warnings
  18. from test import support
  19. class NaiveException(Exception):
  20. def __init__(self, x):
  21. self.x = x
  22. class SlottedNaiveException(Exception):
  23. __slots__ = ('x',)
  24. def __init__(self, x):
  25. self.x = x
  26. class BrokenStrException(Exception):
  27. def __str__(self):
  28. raise Exception("str() is broken")
  29. # XXX This is not really enough, each *operation* should be tested!
  30. class ExceptionTests(unittest.TestCase):
  31. def raise_catch(self, exc, excname):
  32. with self.subTest(exc=exc, excname=excname):
  33. try:
  34. raise exc("spam")
  35. except exc as err:
  36. buf1 = str(err)
  37. try:
  38. raise exc("spam")
  39. except exc as err:
  40. buf2 = str(err)
  41. self.assertEqual(buf1, buf2)
  42. self.assertEqual(exc.__name__, excname)
  43. def testRaising(self):
  44. self.raise_catch(AttributeError, "AttributeError")
  45. self.assertRaises(AttributeError, getattr, sys, "undefined_attribute")
  46. self.raise_catch(EOFError, "EOFError")
  47. fp = open(TESTFN, 'w', encoding="utf-8")
  48. fp.close()
  49. fp = open(TESTFN, 'r', encoding="utf-8")
  50. savestdin = sys.stdin
  51. try:
  52. try:
  53. import marshal
  54. marshal.loads(b'')
  55. except EOFError:
  56. pass
  57. finally:
  58. sys.stdin = savestdin
  59. fp.close()
  60. unlink(TESTFN)
  61. self.raise_catch(OSError, "OSError")
  62. self.assertRaises(OSError, open, 'this file does not exist', 'r')
  63. self.raise_catch(ImportError, "ImportError")
  64. self.assertRaises(ImportError, __import__, "undefined_module")
  65. self.raise_catch(IndexError, "IndexError")
  66. x = []
  67. self.assertRaises(IndexError, x.__getitem__, 10)
  68. self.raise_catch(KeyError, "KeyError")
  69. x = {}
  70. self.assertRaises(KeyError, x.__getitem__, 'key')
  71. self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt")
  72. self.raise_catch(MemoryError, "MemoryError")
  73. self.raise_catch(NameError, "NameError")
  74. try: x = undefined_variable
  75. except NameError: pass
  76. self.raise_catch(OverflowError, "OverflowError")
  77. x = 1
  78. for dummy in range(128):
  79. x += x # this simply shouldn't blow up
  80. self.raise_catch(RuntimeError, "RuntimeError")
  81. self.raise_catch(RecursionError, "RecursionError")
  82. self.raise_catch(SyntaxError, "SyntaxError")
  83. try: exec('/\n')
  84. except SyntaxError: pass
  85. self.raise_catch(IndentationError, "IndentationError")
  86. self.raise_catch(TabError, "TabError")
  87. try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n",
  88. '<string>', 'exec')
  89. except TabError: pass
  90. else: self.fail("TabError not raised")
  91. self.raise_catch(SystemError, "SystemError")
  92. self.raise_catch(SystemExit, "SystemExit")
  93. self.assertRaises(SystemExit, sys.exit, 0)
  94. self.raise_catch(TypeError, "TypeError")
  95. try: [] + ()
  96. except TypeError: pass
  97. self.raise_catch(ValueError, "ValueError")
  98. self.assertRaises(ValueError, chr, 17<<16)
  99. self.raise_catch(ZeroDivisionError, "ZeroDivisionError")
  100. try: x = 1/0
  101. except ZeroDivisionError: pass
  102. self.raise_catch(Exception, "Exception")
  103. try: x = 1/0
  104. except Exception as e: pass
  105. self.raise_catch(StopAsyncIteration, "StopAsyncIteration")
  106. def testSyntaxErrorMessage(self):
  107. # make sure the right exception message is raised for each of
  108. # these code fragments
  109. def ckmsg(src, msg):
  110. with self.subTest(src=src, msg=msg):
  111. try:
  112. compile(src, '<fragment>', 'exec')
  113. except SyntaxError as e:
  114. if e.msg != msg:
  115. self.fail("expected %s, got %s" % (msg, e.msg))
  116. else:
  117. self.fail("failed to get expected SyntaxError")
  118. s = '''if 1:
  119. try:
  120. continue
  121. except:
  122. pass'''
  123. ckmsg(s, "'continue' not properly in loop")
  124. ckmsg("continue\n", "'continue' not properly in loop")
  125. def testSyntaxErrorMissingParens(self):
  126. def ckmsg(src, msg, exception=SyntaxError):
  127. try:
  128. compile(src, '<fragment>', 'exec')
  129. except exception as e:
  130. if e.msg != msg:
  131. self.fail("expected %s, got %s" % (msg, e.msg))
  132. else:
  133. self.fail("failed to get expected SyntaxError")
  134. s = '''print "old style"'''
  135. ckmsg(s, "Missing parentheses in call to 'print'. Did you mean print(...)?")
  136. s = '''print "old style",'''
  137. ckmsg(s, "Missing parentheses in call to 'print'. Did you mean print(...)?")
  138. s = 'print f(a+b,c)'
  139. ckmsg(s, "Missing parentheses in call to 'print'. Did you mean print(...)?")
  140. s = '''exec "old style"'''
  141. ckmsg(s, "Missing parentheses in call to 'exec'. Did you mean exec(...)?")
  142. s = 'exec f(a+b,c)'
  143. ckmsg(s, "Missing parentheses in call to 'exec'. Did you mean exec(...)?")
  144. # Check that we don't incorrectly identify '(...)' as an expression to the right
  145. # of 'print'
  146. s = 'print (a+b,c) $ 42'
  147. ckmsg(s, "invalid syntax")
  148. s = 'exec (a+b,c) $ 42'
  149. ckmsg(s, "invalid syntax")
  150. # should not apply to subclasses, see issue #31161
  151. s = '''if True:\nprint "No indent"'''
  152. ckmsg(s, "expected an indented block after 'if' statement on line 1", IndentationError)
  153. s = '''if True:\n print()\n\texec "mixed tabs and spaces"'''
  154. ckmsg(s, "inconsistent use of tabs and spaces in indentation", TabError)
  155. def check(self, src, lineno, offset, end_lineno=None, end_offset=None, encoding='utf-8'):
  156. with self.subTest(source=src, lineno=lineno, offset=offset):
  157. with self.assertRaises(SyntaxError) as cm:
  158. compile(src, '<fragment>', 'exec')
  159. self.assertEqual(cm.exception.lineno, lineno)
  160. self.assertEqual(cm.exception.offset, offset)
  161. if end_lineno is not None:
  162. self.assertEqual(cm.exception.end_lineno, end_lineno)
  163. if end_offset is not None:
  164. self.assertEqual(cm.exception.end_offset, end_offset)
  165. if cm.exception.text is not None:
  166. if not isinstance(src, str):
  167. src = src.decode(encoding, 'replace')
  168. line = src.split('\n')[lineno-1]
  169. self.assertIn(line, cm.exception.text)
  170. def test_error_offset_continuation_characters(self):
  171. check = self.check
  172. check('"\\\n"(1 for c in I,\\\n\\', 2, 2)
  173. def testSyntaxErrorOffset(self):
  174. check = self.check
  175. check('def fact(x):\n\treturn x!\n', 2, 10)
  176. check('1 +\n', 1, 4)
  177. check('def spam():\n print(1)\n print(2)', 3, 10)
  178. check('Python = "Python" +', 1, 20)
  179. check('Python = "\u1e54\xfd\u0163\u0125\xf2\xf1" +', 1, 20)
  180. check(b'# -*- coding: cp1251 -*-\nPython = "\xcf\xb3\xf2\xee\xed" +',
  181. 2, 19, encoding='cp1251')
  182. check(b'Python = "\xcf\xb3\xf2\xee\xed" +', 1, 18)
  183. check('x = "a', 1, 5)
  184. check('lambda x: x = 2', 1, 1)
  185. check('f{a + b + c}', 1, 2)
  186. check('[file for str(file) in []\n]', 1, 11)
  187. check('a = « hello » « world »', 1, 5)
  188. check('[\nfile\nfor str(file)\nin\n[]\n]', 3, 5)
  189. check('[file for\n str(file) in []]', 2, 2)
  190. check("ages = {'Alice'=22, 'Bob'=23}", 1, 9)
  191. check('match ...:\n case {**rest, "key": value}:\n ...', 2, 19)
  192. check("[a b c d e f]", 1, 2)
  193. check("for x yfff:", 1, 7)
  194. check("f(a for a in b, c)", 1, 3, 1, 15)
  195. check("f(a for a in b if a, c)", 1, 3, 1, 20)
  196. check("f(a, b for b in c)", 1, 6, 1, 18)
  197. check("f(a, b for b in c, d)", 1, 6, 1, 18)
  198. # Errors thrown by compile.c
  199. check('class foo:return 1', 1, 11)
  200. check('def f():\n continue', 2, 3)
  201. check('def f():\n break', 2, 3)
  202. check('try:\n pass\nexcept:\n pass\nexcept ValueError:\n pass', 3, 1)
  203. check('try:\n pass\nexcept*:\n pass', 3, 8)
  204. check('try:\n pass\nexcept*:\n pass\nexcept* ValueError:\n pass', 3, 8)
  205. # Errors thrown by tokenizer.c
  206. check('(0x+1)', 1, 3)
  207. check('x = 0xI', 1, 6)
  208. check('0010 + 2', 1, 1)
  209. check('x = 32e-+4', 1, 8)
  210. check('x = 0o9', 1, 7)
  211. check('\u03b1 = 0xI', 1, 6)
  212. check(b'\xce\xb1 = 0xI', 1, 6)
  213. check(b'# -*- coding: iso8859-7 -*-\n\xe1 = 0xI', 2, 6,
  214. encoding='iso8859-7')
  215. check(b"""if 1:
  216. def foo():
  217. '''
  218. def bar():
  219. pass
  220. def baz():
  221. '''quux'''
  222. """, 9, 24)
  223. check("pass\npass\npass\n(1+)\npass\npass\npass", 4, 4)
  224. check("(1+)", 1, 4)
  225. check("[interesting\nfoo()\n", 1, 1)
  226. check(b"\xef\xbb\xbf#coding: utf8\nprint('\xe6\x88\x91')\n", 0, -1)
  227. check("""f'''
  228. {
  229. (123_a)
  230. }'''""", 3, 17)
  231. check("""f'''
  232. {
  233. f\"\"\"
  234. {
  235. (123_a)
  236. }
  237. \"\"\"
  238. }'''""", 5, 17)
  239. check('''f"""
  240. {
  241. 6
  242. 0="""''', 5, 13)
  243. # Errors thrown by symtable.c
  244. check('x = [(yield i) for i in range(3)]', 1, 7)
  245. check('def f():\n from _ import *', 2, 17)
  246. check('def f(x, x):\n pass', 1, 10)
  247. check('{i for i in range(5) if (j := 0) for j in range(5)}', 1, 38)
  248. check('def f(x):\n nonlocal x', 2, 3)
  249. check('def f(x):\n x = 1\n global x', 3, 3)
  250. check('nonlocal x', 1, 1)
  251. check('def f():\n global x\n nonlocal x', 2, 3)
  252. # Errors thrown by future.c
  253. check('from __future__ import doesnt_exist', 1, 1)
  254. check('from __future__ import braces', 1, 1)
  255. check('x=1\nfrom __future__ import division', 2, 1)
  256. check('foo(1=2)', 1, 5)
  257. check('def f():\n x, y: int', 2, 3)
  258. check('[*x for x in xs]', 1, 2)
  259. check('foo(x for x in range(10), 100)', 1, 5)
  260. check('for 1 in []: pass', 1, 5)
  261. check('(yield i) = 2', 1, 2)
  262. check('def f(*):\n pass', 1, 7)
  263. @cpython_only
  264. def testSettingException(self):
  265. # test that setting an exception at the C level works even if the
  266. # exception object can't be constructed.
  267. class BadException(Exception):
  268. def __init__(self_):
  269. raise RuntimeError("can't instantiate BadException")
  270. class InvalidException:
  271. pass
  272. def test_capi1():
  273. import _testcapi
  274. try:
  275. _testcapi.raise_exception(BadException, 1)
  276. except TypeError as err:
  277. exc, err, tb = sys.exc_info()
  278. co = tb.tb_frame.f_code
  279. self.assertEqual(co.co_name, "test_capi1")
  280. self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
  281. else:
  282. self.fail("Expected exception")
  283. def test_capi2():
  284. import _testcapi
  285. try:
  286. _testcapi.raise_exception(BadException, 0)
  287. except RuntimeError as err:
  288. exc, err, tb = sys.exc_info()
  289. co = tb.tb_frame.f_code
  290. self.assertEqual(co.co_name, "__init__")
  291. self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
  292. co2 = tb.tb_frame.f_back.f_code
  293. self.assertEqual(co2.co_name, "test_capi2")
  294. else:
  295. self.fail("Expected exception")
  296. def test_capi3():
  297. import _testcapi
  298. self.assertRaises(SystemError, _testcapi.raise_exception,
  299. InvalidException, 1)
  300. if not sys.platform.startswith('java'):
  301. test_capi1()
  302. test_capi2()
  303. test_capi3()
  304. def test_WindowsError(self):
  305. try:
  306. WindowsError
  307. except NameError:
  308. pass
  309. else:
  310. self.assertIs(WindowsError, OSError)
  311. self.assertEqual(str(OSError(1001)), "1001")
  312. self.assertEqual(str(OSError(1001, "message")),
  313. "[Errno 1001] message")
  314. # POSIX errno (9 aka EBADF) is untranslated
  315. w = OSError(9, 'foo', 'bar')
  316. self.assertEqual(w.errno, 9)
  317. self.assertEqual(w.winerror, None)
  318. self.assertEqual(str(w), "[Errno 9] foo: 'bar'")
  319. # ERROR_PATH_NOT_FOUND (win error 3) becomes ENOENT (2)
  320. w = OSError(0, 'foo', 'bar', 3)
  321. self.assertEqual(w.errno, 2)
  322. self.assertEqual(w.winerror, 3)
  323. self.assertEqual(w.strerror, 'foo')
  324. self.assertEqual(w.filename, 'bar')
  325. self.assertEqual(w.filename2, None)
  326. self.assertEqual(str(w), "[WinError 3] foo: 'bar'")
  327. # Unknown win error becomes EINVAL (22)
  328. w = OSError(0, 'foo', None, 1001)
  329. self.assertEqual(w.errno, 22)
  330. self.assertEqual(w.winerror, 1001)
  331. self.assertEqual(w.strerror, 'foo')
  332. self.assertEqual(w.filename, None)
  333. self.assertEqual(w.filename2, None)
  334. self.assertEqual(str(w), "[WinError 1001] foo")
  335. # Non-numeric "errno"
  336. w = OSError('bar', 'foo')
  337. self.assertEqual(w.errno, 'bar')
  338. self.assertEqual(w.winerror, None)
  339. self.assertEqual(w.strerror, 'foo')
  340. self.assertEqual(w.filename, None)
  341. self.assertEqual(w.filename2, None)
  342. @unittest.skipUnless(sys.platform == 'win32',
  343. 'test specific to Windows')
  344. def test_windows_message(self):
  345. """Should fill in unknown error code in Windows error message"""
  346. ctypes = import_module('ctypes')
  347. # this error code has no message, Python formats it as hexadecimal
  348. code = 3765269347
  349. with self.assertRaisesRegex(OSError, 'Windows Error 0x%x' % code):
  350. ctypes.pythonapi.PyErr_SetFromWindowsErr(code)
  351. def testAttributes(self):
  352. # test that exception attributes are happy
  353. exceptionList = [
  354. (BaseException, (), {'args' : ()}),
  355. (BaseException, (1, ), {'args' : (1,)}),
  356. (BaseException, ('foo',),
  357. {'args' : ('foo',)}),
  358. (BaseException, ('foo', 1),
  359. {'args' : ('foo', 1)}),
  360. (SystemExit, ('foo',),
  361. {'args' : ('foo',), 'code' : 'foo'}),
  362. (OSError, ('foo',),
  363. {'args' : ('foo',), 'filename' : None, 'filename2' : None,
  364. 'errno' : None, 'strerror' : None}),
  365. (OSError, ('foo', 'bar'),
  366. {'args' : ('foo', 'bar'),
  367. 'filename' : None, 'filename2' : None,
  368. 'errno' : 'foo', 'strerror' : 'bar'}),
  369. (OSError, ('foo', 'bar', 'baz'),
  370. {'args' : ('foo', 'bar'),
  371. 'filename' : 'baz', 'filename2' : None,
  372. 'errno' : 'foo', 'strerror' : 'bar'}),
  373. (OSError, ('foo', 'bar', 'baz', None, 'quux'),
  374. {'args' : ('foo', 'bar'), 'filename' : 'baz', 'filename2': 'quux'}),
  375. (OSError, ('errnoStr', 'strErrorStr', 'filenameStr'),
  376. {'args' : ('errnoStr', 'strErrorStr'),
  377. 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
  378. 'filename' : 'filenameStr'}),
  379. (OSError, (1, 'strErrorStr', 'filenameStr'),
  380. {'args' : (1, 'strErrorStr'), 'errno' : 1,
  381. 'strerror' : 'strErrorStr',
  382. 'filename' : 'filenameStr', 'filename2' : None}),
  383. (SyntaxError, (), {'msg' : None, 'text' : None,
  384. 'filename' : None, 'lineno' : None, 'offset' : None,
  385. 'end_offset': None, 'print_file_and_line' : None}),
  386. (SyntaxError, ('msgStr',),
  387. {'args' : ('msgStr',), 'text' : None,
  388. 'print_file_and_line' : None, 'msg' : 'msgStr',
  389. 'filename' : None, 'lineno' : None, 'offset' : None,
  390. 'end_offset': None}),
  391. (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
  392. 'textStr', 'endLinenoStr', 'endOffsetStr')),
  393. {'offset' : 'offsetStr', 'text' : 'textStr',
  394. 'args' : ('msgStr', ('filenameStr', 'linenoStr',
  395. 'offsetStr', 'textStr',
  396. 'endLinenoStr', 'endOffsetStr')),
  397. 'print_file_and_line' : None, 'msg' : 'msgStr',
  398. 'filename' : 'filenameStr', 'lineno' : 'linenoStr',
  399. 'end_lineno': 'endLinenoStr', 'end_offset': 'endOffsetStr'}),
  400. (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
  401. 'textStr', 'endLinenoStr', 'endOffsetStr',
  402. 'print_file_and_lineStr'),
  403. {'text' : None,
  404. 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
  405. 'textStr', 'endLinenoStr', 'endOffsetStr',
  406. 'print_file_and_lineStr'),
  407. 'print_file_and_line' : None, 'msg' : 'msgStr',
  408. 'filename' : None, 'lineno' : None, 'offset' : None,
  409. 'end_lineno': None, 'end_offset': None}),
  410. (UnicodeError, (), {'args' : (),}),
  411. (UnicodeEncodeError, ('ascii', 'a', 0, 1,
  412. 'ordinal not in range'),
  413. {'args' : ('ascii', 'a', 0, 1,
  414. 'ordinal not in range'),
  415. 'encoding' : 'ascii', 'object' : 'a',
  416. 'start' : 0, 'reason' : 'ordinal not in range'}),
  417. (UnicodeDecodeError, ('ascii', bytearray(b'\xff'), 0, 1,
  418. 'ordinal not in range'),
  419. {'args' : ('ascii', bytearray(b'\xff'), 0, 1,
  420. 'ordinal not in range'),
  421. 'encoding' : 'ascii', 'object' : b'\xff',
  422. 'start' : 0, 'reason' : 'ordinal not in range'}),
  423. (UnicodeDecodeError, ('ascii', b'\xff', 0, 1,
  424. 'ordinal not in range'),
  425. {'args' : ('ascii', b'\xff', 0, 1,
  426. 'ordinal not in range'),
  427. 'encoding' : 'ascii', 'object' : b'\xff',
  428. 'start' : 0, 'reason' : 'ordinal not in range'}),
  429. (UnicodeTranslateError, ("\u3042", 0, 1, "ouch"),
  430. {'args' : ('\u3042', 0, 1, 'ouch'),
  431. 'object' : '\u3042', 'reason' : 'ouch',
  432. 'start' : 0, 'end' : 1}),
  433. (NaiveException, ('foo',),
  434. {'args': ('foo',), 'x': 'foo'}),
  435. (SlottedNaiveException, ('foo',),
  436. {'args': ('foo',), 'x': 'foo'}),
  437. ]
  438. try:
  439. # More tests are in test_WindowsError
  440. exceptionList.append(
  441. (WindowsError, (1, 'strErrorStr', 'filenameStr'),
  442. {'args' : (1, 'strErrorStr'),
  443. 'strerror' : 'strErrorStr', 'winerror' : None,
  444. 'errno' : 1,
  445. 'filename' : 'filenameStr', 'filename2' : None})
  446. )
  447. except NameError:
  448. pass
  449. for exc, args, expected in exceptionList:
  450. try:
  451. e = exc(*args)
  452. except:
  453. print("\nexc=%r, args=%r" % (exc, args), file=sys.stderr)
  454. # raise
  455. else:
  456. # Verify module name
  457. if not type(e).__name__.endswith('NaiveException'):
  458. self.assertEqual(type(e).__module__, 'builtins')
  459. # Verify no ref leaks in Exc_str()
  460. s = str(e)
  461. for checkArgName in expected:
  462. value = getattr(e, checkArgName)
  463. self.assertEqual(repr(value),
  464. repr(expected[checkArgName]),
  465. '%r.%s == %r, expected %r' % (
  466. e, checkArgName,
  467. value, expected[checkArgName]))
  468. # test for pickling support
  469. for p in [pickle]:
  470. for protocol in range(p.HIGHEST_PROTOCOL + 1):
  471. s = p.dumps(e, protocol)
  472. new = p.loads(s)
  473. for checkArgName in expected:
  474. got = repr(getattr(new, checkArgName))
  475. want = repr(expected[checkArgName])
  476. self.assertEqual(got, want,
  477. 'pickled "%r", attribute "%s' %
  478. (e, checkArgName))
  479. def test_notes(self):
  480. for e in [BaseException(1), Exception(2), ValueError(3)]:
  481. with self.subTest(e=e):
  482. self.assertFalse(hasattr(e, '__notes__'))
  483. e.add_note("My Note")
  484. self.assertEqual(e.__notes__, ["My Note"])
  485. with self.assertRaises(TypeError):
  486. e.add_note(42)
  487. self.assertEqual(e.__notes__, ["My Note"])
  488. e.add_note("Your Note")
  489. self.assertEqual(e.__notes__, ["My Note", "Your Note"])
  490. del e.__notes__
  491. self.assertFalse(hasattr(e, '__notes__'))
  492. e.add_note("Our Note")
  493. self.assertEqual(e.__notes__, ["Our Note"])
  494. e.__notes__ = 42
  495. self.assertEqual(e.__notes__, 42)
  496. with self.assertRaises(TypeError):
  497. e.add_note("will not work")
  498. self.assertEqual(e.__notes__, 42)
  499. def testWithTraceback(self):
  500. try:
  501. raise IndexError(4)
  502. except:
  503. tb = sys.exc_info()[2]
  504. e = BaseException().with_traceback(tb)
  505. self.assertIsInstance(e, BaseException)
  506. self.assertEqual(e.__traceback__, tb)
  507. e = IndexError(5).with_traceback(tb)
  508. self.assertIsInstance(e, IndexError)
  509. self.assertEqual(e.__traceback__, tb)
  510. class MyException(Exception):
  511. pass
  512. e = MyException().with_traceback(tb)
  513. self.assertIsInstance(e, MyException)
  514. self.assertEqual(e.__traceback__, tb)
  515. def testInvalidTraceback(self):
  516. try:
  517. Exception().__traceback__ = 5
  518. except TypeError as e:
  519. self.assertIn("__traceback__ must be a traceback", str(e))
  520. else:
  521. self.fail("No exception raised")
  522. def testInvalidAttrs(self):
  523. self.assertRaises(TypeError, setattr, Exception(), '__cause__', 1)
  524. self.assertRaises(TypeError, delattr, Exception(), '__cause__')
  525. self.assertRaises(TypeError, setattr, Exception(), '__context__', 1)
  526. self.assertRaises(TypeError, delattr, Exception(), '__context__')
  527. def testNoneClearsTracebackAttr(self):
  528. try:
  529. raise IndexError(4)
  530. except:
  531. tb = sys.exc_info()[2]
  532. e = Exception()
  533. e.__traceback__ = tb
  534. e.__traceback__ = None
  535. self.assertEqual(e.__traceback__, None)
  536. def testChainingAttrs(self):
  537. e = Exception()
  538. self.assertIsNone(e.__context__)
  539. self.assertIsNone(e.__cause__)
  540. e = TypeError()
  541. self.assertIsNone(e.__context__)
  542. self.assertIsNone(e.__cause__)
  543. class MyException(OSError):
  544. pass
  545. e = MyException()
  546. self.assertIsNone(e.__context__)
  547. self.assertIsNone(e.__cause__)
  548. def testChainingDescriptors(self):
  549. try:
  550. raise Exception()
  551. except Exception as exc:
  552. e = exc
  553. self.assertIsNone(e.__context__)
  554. self.assertIsNone(e.__cause__)
  555. self.assertFalse(e.__suppress_context__)
  556. e.__context__ = NameError()
  557. e.__cause__ = None
  558. self.assertIsInstance(e.__context__, NameError)
  559. self.assertIsNone(e.__cause__)
  560. self.assertTrue(e.__suppress_context__)
  561. e.__suppress_context__ = False
  562. self.assertFalse(e.__suppress_context__)
  563. def testKeywordArgs(self):
  564. # test that builtin exception don't take keyword args,
  565. # but user-defined subclasses can if they want
  566. self.assertRaises(TypeError, BaseException, a=1)
  567. class DerivedException(BaseException):
  568. def __init__(self, fancy_arg):
  569. BaseException.__init__(self)
  570. self.fancy_arg = fancy_arg
  571. x = DerivedException(fancy_arg=42)
  572. self.assertEqual(x.fancy_arg, 42)
  573. @no_tracing
  574. def testInfiniteRecursion(self):
  575. def f():
  576. return f()
  577. self.assertRaises(RecursionError, f)
  578. def g():
  579. try:
  580. return g()
  581. except ValueError:
  582. return -1
  583. self.assertRaises(RecursionError, g)
  584. def test_str(self):
  585. # Make sure both instances and classes have a str representation.
  586. self.assertTrue(str(Exception))
  587. self.assertTrue(str(Exception('a')))
  588. self.assertTrue(str(Exception('a', 'b')))
  589. def test_exception_cleanup_names(self):
  590. # Make sure the local variable bound to the exception instance by
  591. # an "except" statement is only visible inside the except block.
  592. try:
  593. raise Exception()
  594. except Exception as e:
  595. self.assertIsInstance(e, Exception)
  596. self.assertNotIn('e', locals())
  597. with self.assertRaises(UnboundLocalError):
  598. e
  599. def test_exception_cleanup_names2(self):
  600. # Make sure the cleanup doesn't break if the variable is explicitly deleted.
  601. try:
  602. raise Exception()
  603. except Exception as e:
  604. self.assertIsInstance(e, Exception)
  605. del e
  606. self.assertNotIn('e', locals())
  607. with self.assertRaises(UnboundLocalError):
  608. e
  609. def testExceptionCleanupState(self):
  610. # Make sure exception state is cleaned up as soon as the except
  611. # block is left. See #2507
  612. class MyException(Exception):
  613. def __init__(self, obj):
  614. self.obj = obj
  615. class MyObj:
  616. pass
  617. def inner_raising_func():
  618. # Create some references in exception value and traceback
  619. local_ref = obj
  620. raise MyException(obj)
  621. # Qualified "except" with "as"
  622. obj = MyObj()
  623. wr = weakref.ref(obj)
  624. try:
  625. inner_raising_func()
  626. except MyException as e:
  627. pass
  628. obj = None
  629. gc_collect() # For PyPy or other GCs.
  630. obj = wr()
  631. self.assertIsNone(obj)
  632. # Qualified "except" without "as"
  633. obj = MyObj()
  634. wr = weakref.ref(obj)
  635. try:
  636. inner_raising_func()
  637. except MyException:
  638. pass
  639. obj = None
  640. gc_collect() # For PyPy or other GCs.
  641. obj = wr()
  642. self.assertIsNone(obj)
  643. # Bare "except"
  644. obj = MyObj()
  645. wr = weakref.ref(obj)
  646. try:
  647. inner_raising_func()
  648. except:
  649. pass
  650. obj = None
  651. gc_collect() # For PyPy or other GCs.
  652. obj = wr()
  653. self.assertIsNone(obj)
  654. # "except" with premature block leave
  655. obj = MyObj()
  656. wr = weakref.ref(obj)
  657. for i in [0]:
  658. try:
  659. inner_raising_func()
  660. except:
  661. break
  662. obj = None
  663. gc_collect() # For PyPy or other GCs.
  664. obj = wr()
  665. self.assertIsNone(obj)
  666. # "except" block raising another exception
  667. obj = MyObj()
  668. wr = weakref.ref(obj)
  669. try:
  670. try:
  671. inner_raising_func()
  672. except:
  673. raise KeyError
  674. except KeyError as e:
  675. # We want to test that the except block above got rid of
  676. # the exception raised in inner_raising_func(), but it
  677. # also ends up in the __context__ of the KeyError, so we
  678. # must clear the latter manually for our test to succeed.
  679. e.__context__ = None
  680. obj = None
  681. gc_collect() # For PyPy or other GCs.
  682. obj = wr()
  683. # guarantee no ref cycles on CPython (don't gc_collect)
  684. if check_impl_detail(cpython=False):
  685. gc_collect()
  686. self.assertIsNone(obj)
  687. # Some complicated construct
  688. obj = MyObj()
  689. wr = weakref.ref(obj)
  690. try:
  691. inner_raising_func()
  692. except MyException:
  693. try:
  694. try:
  695. raise
  696. finally:
  697. raise
  698. except MyException:
  699. pass
  700. obj = None
  701. if check_impl_detail(cpython=False):
  702. gc_collect()
  703. obj = wr()
  704. self.assertIsNone(obj)
  705. # Inside an exception-silencing "with" block
  706. class Context:
  707. def __enter__(self):
  708. return self
  709. def __exit__ (self, exc_type, exc_value, exc_tb):
  710. return True
  711. obj = MyObj()
  712. wr = weakref.ref(obj)
  713. with Context():
  714. inner_raising_func()
  715. obj = None
  716. if check_impl_detail(cpython=False):
  717. gc_collect()
  718. obj = wr()
  719. self.assertIsNone(obj)
  720. def test_exception_target_in_nested_scope(self):
  721. # issue 4617: This used to raise a SyntaxError
  722. # "can not delete variable 'e' referenced in nested scope"
  723. def print_error():
  724. e
  725. try:
  726. something
  727. except Exception as e:
  728. print_error()
  729. # implicit "del e" here
  730. def test_generator_leaking(self):
  731. # Test that generator exception state doesn't leak into the calling
  732. # frame
  733. def yield_raise():
  734. try:
  735. raise KeyError("caught")
  736. except KeyError:
  737. yield sys.exc_info()[0]
  738. yield sys.exc_info()[0]
  739. yield sys.exc_info()[0]
  740. g = yield_raise()
  741. self.assertEqual(next(g), KeyError)
  742. self.assertEqual(sys.exc_info()[0], None)
  743. self.assertEqual(next(g), KeyError)
  744. self.assertEqual(sys.exc_info()[0], None)
  745. self.assertEqual(next(g), None)
  746. # Same test, but inside an exception handler
  747. try:
  748. raise TypeError("foo")
  749. except TypeError:
  750. g = yield_raise()
  751. self.assertEqual(next(g), KeyError)
  752. self.assertEqual(sys.exc_info()[0], TypeError)
  753. self.assertEqual(next(g), KeyError)
  754. self.assertEqual(sys.exc_info()[0], TypeError)
  755. self.assertEqual(next(g), TypeError)
  756. del g
  757. self.assertEqual(sys.exc_info()[0], TypeError)
  758. def test_generator_leaking2(self):
  759. # See issue 12475.
  760. def g():
  761. yield
  762. try:
  763. raise RuntimeError
  764. except RuntimeError:
  765. it = g()
  766. next(it)
  767. try:
  768. next(it)
  769. except StopIteration:
  770. pass
  771. self.assertEqual(sys.exc_info(), (None, None, None))
  772. def test_generator_leaking3(self):
  773. # See issue #23353. When gen.throw() is called, the caller's
  774. # exception state should be save and restored.
  775. def g():
  776. try:
  777. yield
  778. except ZeroDivisionError:
  779. yield sys.exc_info()[1]
  780. it = g()
  781. next(it)
  782. try:
  783. 1/0
  784. except ZeroDivisionError as e:
  785. self.assertIs(sys.exc_info()[1], e)
  786. gen_exc = it.throw(e)
  787. self.assertIs(sys.exc_info()[1], e)
  788. self.assertIs(gen_exc, e)
  789. self.assertEqual(sys.exc_info(), (None, None, None))
  790. def test_generator_leaking4(self):
  791. # See issue #23353. When an exception is raised by a generator,
  792. # the caller's exception state should still be restored.
  793. def g():
  794. try:
  795. 1/0
  796. except ZeroDivisionError:
  797. yield sys.exc_info()[0]
  798. raise
  799. it = g()
  800. try:
  801. raise TypeError
  802. except TypeError:
  803. # The caller's exception state (TypeError) is temporarily
  804. # saved in the generator.
  805. tp = next(it)
  806. self.assertIs(tp, ZeroDivisionError)
  807. try:
  808. next(it)
  809. # We can't check it immediately, but while next() returns
  810. # with an exception, it shouldn't have restored the old
  811. # exception state (TypeError).
  812. except ZeroDivisionError as e:
  813. self.assertIs(sys.exc_info()[1], e)
  814. # We used to find TypeError here.
  815. self.assertEqual(sys.exc_info(), (None, None, None))
  816. def test_generator_doesnt_retain_old_exc(self):
  817. def g():
  818. self.assertIsInstance(sys.exc_info()[1], RuntimeError)
  819. yield
  820. self.assertEqual(sys.exc_info(), (None, None, None))
  821. it = g()
  822. try:
  823. raise RuntimeError
  824. except RuntimeError:
  825. next(it)
  826. self.assertRaises(StopIteration, next, it)
  827. def test_generator_finalizing_and_exc_info(self):
  828. # See #7173
  829. def simple_gen():
  830. yield 1
  831. def run_gen():
  832. gen = simple_gen()
  833. try:
  834. raise RuntimeError
  835. except RuntimeError:
  836. return next(gen)
  837. run_gen()
  838. gc_collect()
  839. self.assertEqual(sys.exc_info(), (None, None, None))
  840. def _check_generator_cleanup_exc_state(self, testfunc):
  841. # Issue #12791: exception state is cleaned up as soon as a generator
  842. # is closed (reference cycles are broken).
  843. class MyException(Exception):
  844. def __init__(self, obj):
  845. self.obj = obj
  846. class MyObj:
  847. pass
  848. def raising_gen():
  849. try:
  850. raise MyException(obj)
  851. except MyException:
  852. yield
  853. obj = MyObj()
  854. wr = weakref.ref(obj)
  855. g = raising_gen()
  856. next(g)
  857. testfunc(g)
  858. g = obj = None
  859. gc_collect() # For PyPy or other GCs.
  860. obj = wr()
  861. self.assertIsNone(obj)
  862. def test_generator_throw_cleanup_exc_state(self):
  863. def do_throw(g):
  864. try:
  865. g.throw(RuntimeError())
  866. except RuntimeError:
  867. pass
  868. self._check_generator_cleanup_exc_state(do_throw)
  869. def test_generator_close_cleanup_exc_state(self):
  870. def do_close(g):
  871. g.close()
  872. self._check_generator_cleanup_exc_state(do_close)
  873. def test_generator_del_cleanup_exc_state(self):
  874. def do_del(g):
  875. g = None
  876. self._check_generator_cleanup_exc_state(do_del)
  877. def test_generator_next_cleanup_exc_state(self):
  878. def do_next(g):
  879. try:
  880. next(g)
  881. except StopIteration:
  882. pass
  883. else:
  884. self.fail("should have raised StopIteration")
  885. self._check_generator_cleanup_exc_state(do_next)
  886. def test_generator_send_cleanup_exc_state(self):
  887. def do_send(g):
  888. try:
  889. g.send(None)
  890. except StopIteration:
  891. pass
  892. else:
  893. self.fail("should have raised StopIteration")
  894. self._check_generator_cleanup_exc_state(do_send)
  895. def test_3114(self):
  896. # Bug #3114: in its destructor, MyObject retrieves a pointer to
  897. # obsolete and/or deallocated objects.
  898. class MyObject:
  899. def __del__(self):
  900. nonlocal e
  901. e = sys.exc_info()
  902. e = ()
  903. try:
  904. raise Exception(MyObject())
  905. except:
  906. pass
  907. gc_collect() # For PyPy or other GCs.
  908. self.assertEqual(e, (None, None, None))
  909. def test_raise_does_not_create_context_chain_cycle(self):
  910. class A(Exception):
  911. pass
  912. class B(Exception):
  913. pass
  914. class C(Exception):
  915. pass
  916. # Create a context chain:
  917. # C -> B -> A
  918. # Then raise A in context of C.
  919. try:
  920. try:
  921. raise A
  922. except A as a_:
  923. a = a_
  924. try:
  925. raise B
  926. except B as b_:
  927. b = b_
  928. try:
  929. raise C
  930. except C as c_:
  931. c = c_
  932. self.assertIsInstance(a, A)
  933. self.assertIsInstance(b, B)
  934. self.assertIsInstance(c, C)
  935. self.assertIsNone(a.__context__)
  936. self.assertIs(b.__context__, a)
  937. self.assertIs(c.__context__, b)
  938. raise a
  939. except A as e:
  940. exc = e
  941. # Expect A -> C -> B, without cycle
  942. self.assertIs(exc, a)
  943. self.assertIs(a.__context__, c)
  944. self.assertIs(c.__context__, b)
  945. self.assertIsNone(b.__context__)
  946. def test_no_hang_on_context_chain_cycle1(self):
  947. # See issue 25782. Cycle in context chain.
  948. def cycle():
  949. try:
  950. raise ValueError(1)
  951. except ValueError as ex:
  952. ex.__context__ = ex
  953. raise TypeError(2)
  954. try:
  955. cycle()
  956. except Exception as e:
  957. exc = e
  958. self.assertIsInstance(exc, TypeError)
  959. self.assertIsInstance(exc.__context__, ValueError)
  960. self.assertIs(exc.__context__.__context__, exc.__context__)
  961. @unittest.skip("See issue 44895")
  962. def test_no_hang_on_context_chain_cycle2(self):
  963. # See issue 25782. Cycle at head of context chain.
  964. class A(Exception):
  965. pass
  966. class B(Exception):
  967. pass
  968. class C(Exception):
  969. pass
  970. # Context cycle:
  971. # +-----------+
  972. # V |
  973. # C --> B --> A
  974. with self.assertRaises(C) as cm:
  975. try:
  976. raise A()
  977. except A as _a:
  978. a = _a
  979. try:
  980. raise B()
  981. except B as _b:
  982. b = _b
  983. try:
  984. raise C()
  985. except C as _c:
  986. c = _c
  987. a.__context__ = c
  988. raise c
  989. self.assertIs(cm.exception, c)
  990. # Verify the expected context chain cycle
  991. self.assertIs(c.__context__, b)
  992. self.assertIs(b.__context__, a)
  993. self.assertIs(a.__context__, c)
  994. def test_no_hang_on_context_chain_cycle3(self):
  995. # See issue 25782. Longer context chain with cycle.
  996. class A(Exception):
  997. pass
  998. class B(Exception):
  999. pass
  1000. class C(Exception):
  1001. pass
  1002. class D(Exception):
  1003. pass
  1004. class E(Exception):
  1005. pass
  1006. # Context cycle:
  1007. # +-----------+
  1008. # V |
  1009. # E --> D --> C --> B --> A
  1010. with self.assertRaises(E) as cm:
  1011. try:
  1012. raise A()
  1013. except A as _a:
  1014. a = _a
  1015. try:
  1016. raise B()
  1017. except B as _b:
  1018. b = _b
  1019. try:
  1020. raise C()
  1021. except C as _c:
  1022. c = _c
  1023. a.__context__ = c
  1024. try:
  1025. raise D()
  1026. except D as _d:
  1027. d = _d
  1028. e = E()
  1029. raise e
  1030. self.assertIs(cm.exception, e)
  1031. # Verify the expected context chain cycle
  1032. self.assertIs(e.__context__, d)
  1033. self.assertIs(d.__context__, c)
  1034. self.assertIs(c.__context__, b)
  1035. self.assertIs(b.__context__, a)
  1036. self.assertIs(a.__context__, c)
  1037. def test_context_of_exception_in_try_and_finally(self):
  1038. try:
  1039. try:
  1040. te = TypeError(1)
  1041. raise te
  1042. finally:
  1043. ve = ValueError(2)
  1044. raise ve
  1045. except Exception as e:
  1046. exc = e
  1047. self.assertIs(exc, ve)
  1048. self.assertIs(exc.__context__, te)
  1049. def test_context_of_exception_in_except_and_finally(self):
  1050. try:
  1051. try:
  1052. te = TypeError(1)
  1053. raise te
  1054. except:
  1055. ve = ValueError(2)
  1056. raise ve
  1057. finally:
  1058. oe = OSError(3)
  1059. raise oe
  1060. except Exception as e:
  1061. exc = e
  1062. self.assertIs(exc, oe)
  1063. self.assertIs(exc.__context__, ve)
  1064. self.assertIs(exc.__context__.__context__, te)
  1065. def test_context_of_exception_in_else_and_finally(self):
  1066. try:
  1067. try:
  1068. pass
  1069. except:
  1070. pass
  1071. else:
  1072. ve = ValueError(1)
  1073. raise ve
  1074. finally:
  1075. oe = OSError(2)
  1076. raise oe
  1077. except Exception as e:
  1078. exc = e
  1079. self.assertIs(exc, oe)
  1080. self.assertIs(exc.__context__, ve)
  1081. def test_unicode_change_attributes(self):
  1082. # See issue 7309. This was a crasher.
  1083. u = UnicodeEncodeError('baz', 'xxxxx', 1, 5, 'foo')
  1084. self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: foo")
  1085. u.end = 2
  1086. self.assertEqual(str(u), "'baz' codec can't encode character '\\x78' in position 1: foo")
  1087. u.end = 5
  1088. u.reason = 0x345345345345345345
  1089. self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: 965230951443685724997")
  1090. u.encoding = 4000
  1091. self.assertEqual(str(u), "'4000' codec can't encode characters in position 1-4: 965230951443685724997")
  1092. u.start = 1000
  1093. self.assertEqual(str(u), "'4000' codec can't encode characters in position 1000-4: 965230951443685724997")
  1094. u = UnicodeDecodeError('baz', b'xxxxx', 1, 5, 'foo')
  1095. self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: foo")
  1096. u.end = 2
  1097. self.assertEqual(str(u), "'baz' codec can't decode byte 0x78 in position 1: foo")
  1098. u.end = 5
  1099. u.reason = 0x345345345345345345
  1100. self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: 965230951443685724997")
  1101. u.encoding = 4000
  1102. self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1-4: 965230951443685724997")
  1103. u.start = 1000
  1104. self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1000-4: 965230951443685724997")
  1105. u = UnicodeTranslateError('xxxx', 1, 5, 'foo')
  1106. self.assertEqual(str(u), "can't translate characters in position 1-4: foo")
  1107. u.end = 2
  1108. self.assertEqual(str(u), "can't translate character '\\x78' in position 1: foo")
  1109. u.end = 5
  1110. u.reason = 0x345345345345345345
  1111. self.assertEqual(str(u), "can't translate characters in position 1-4: 965230951443685724997")
  1112. u.start = 1000
  1113. self.assertEqual(str(u), "can't translate characters in position 1000-4: 965230951443685724997")
  1114. def test_unicode_errors_no_object(self):
  1115. # See issue #21134.
  1116. klasses = UnicodeEncodeError, UnicodeDecodeError, UnicodeTranslateError
  1117. for klass in klasses:
  1118. self.assertEqual(str(klass.__new__(klass)), "")
  1119. @no_tracing
  1120. def test_badisinstance(self):
  1121. # Bug #2542: if issubclass(e, MyException) raises an exception,
  1122. # it should be ignored
  1123. class Meta(type):
  1124. def __subclasscheck__(cls, subclass):
  1125. raise ValueError()
  1126. class MyException(Exception, metaclass=Meta):
  1127. pass
  1128. with captured_stderr() as stderr:
  1129. try:
  1130. raise KeyError()
  1131. except MyException as e:
  1132. self.fail("exception should not be a MyException")
  1133. except KeyError:
  1134. pass
  1135. except:
  1136. self.fail("Should have raised KeyError")
  1137. else:
  1138. self.fail("Should have raised KeyError")
  1139. def g():
  1140. try:
  1141. return g()
  1142. except RecursionError:
  1143. return sys.exc_info()
  1144. e, v, tb = g()
  1145. self.assertIsInstance(v, RecursionError, type(v))
  1146. self.assertIn("maximum recursion depth exceeded", str(v))
  1147. @cpython_only
  1148. def test_trashcan_recursion(self):
  1149. # See bpo-33930
  1150. def foo():
  1151. o = object()
  1152. for x in range(1_000_000):
  1153. # Create a big chain of method objects that will trigger
  1154. # a deep chain of calls when they need to be destructed.
  1155. o = o.__dir__
  1156. foo()
  1157. support.gc_collect()
  1158. @cpython_only
  1159. def test_recursion_normalizing_exception(self):
  1160. # Issue #22898.
  1161. # Test that a RecursionError is raised when tstate->recursion_depth is
  1162. # equal to recursion_limit in PyErr_NormalizeException() and check
  1163. # that a ResourceWarning is printed.
  1164. # Prior to #22898, the recursivity of PyErr_NormalizeException() was
  1165. # controlled by tstate->recursion_depth and a PyExc_RecursionErrorInst
  1166. # singleton was being used in that case, that held traceback data and
  1167. # locals indefinitely and would cause a segfault in _PyExc_Fini() upon
  1168. # finalization of these locals.
  1169. code = """if 1:
  1170. import sys
  1171. from _testinternalcapi import get_recursion_depth
  1172. class MyException(Exception): pass
  1173. def setrecursionlimit(depth):
  1174. while 1:
  1175. try:
  1176. sys.setrecursionlimit(depth)
  1177. return depth
  1178. except RecursionError:
  1179. # sys.setrecursionlimit() raises a RecursionError if
  1180. # the new recursion limit is too low (issue #25274).
  1181. depth += 1
  1182. def recurse(cnt):
  1183. cnt -= 1
  1184. if cnt:
  1185. recurse(cnt)
  1186. else:
  1187. generator.throw(MyException)
  1188. def gen():
  1189. f = open(%a, mode='rb', buffering=0)
  1190. yield
  1191. generator = gen()
  1192. next(generator)
  1193. recursionlimit = sys.getrecursionlimit()
  1194. depth = get_recursion_depth()
  1195. try:
  1196. # Upon the last recursive invocation of recurse(),
  1197. # tstate->recursion_depth is equal to (recursion_limit - 1)
  1198. # and is equal to recursion_limit when _gen_throw() calls
  1199. # PyErr_NormalizeException().
  1200. recurse(setrecursionlimit(depth + 2) - depth)
  1201. finally:
  1202. sys.setrecursionlimit(recursionlimit)
  1203. print('Done.')
  1204. """ % __file__
  1205. rc, out, err = script_helper.assert_python_failure("-Wd", "-c", code)
  1206. # Check that the program does not fail with SIGABRT.
  1207. self.assertEqual(rc, 1)
  1208. self.assertIn(b'RecursionError', err)
  1209. self.assertIn(b'ResourceWarning', err)
  1210. self.assertIn(b'Done.', out)
  1211. @cpython_only
  1212. def test_recursion_normalizing_infinite_exception(self):
  1213. # Issue #30697. Test that a RecursionError is raised when
  1214. # PyErr_NormalizeException() maximum recursion depth has been
  1215. # exceeded.
  1216. code = """if 1:
  1217. import _testcapi
  1218. try:
  1219. raise _testcapi.RecursingInfinitelyError
  1220. finally:
  1221. print('Done.')
  1222. """
  1223. rc, out, err = script_helper.assert_python_failure("-c", code)
  1224. self.assertEqual(rc, 1)
  1225. self.assertIn(b'RecursionError: maximum recursion depth exceeded '
  1226. b'while normalizing an exception', err)
  1227. self.assertIn(b'Done.', out)
  1228. def test_recursion_in_except_handler(self):
  1229. def set_relative_recursion_limit(n):
  1230. depth = 1
  1231. while True:
  1232. try:
  1233. sys.setrecursionlimit(depth)
  1234. except RecursionError:
  1235. depth += 1
  1236. else:
  1237. break
  1238. sys.setrecursionlimit(depth+n)
  1239. def recurse_in_except():
  1240. try:
  1241. 1/0
  1242. except:
  1243. recurse_in_except()
  1244. def recurse_after_except():
  1245. try:
  1246. 1/0
  1247. except:
  1248. pass
  1249. recurse_after_except()
  1250. def recurse_in_body_and_except():
  1251. try:
  1252. recurse_in_body_and_except()
  1253. except:
  1254. recurse_in_body_and_except()
  1255. recursionlimit = sys.getrecursionlimit()
  1256. try:
  1257. set_relative_recursion_limit(10)
  1258. for func in (recurse_in_except, recurse_after_except, recurse_in_body_and_except):
  1259. with self.subTest(func=func):
  1260. try:
  1261. func()
  1262. except RecursionError:
  1263. pass
  1264. else:
  1265. self.fail("Should have raised a RecursionError")
  1266. finally:
  1267. sys.setrecursionlimit(recursionlimit)
  1268. @cpython_only
  1269. def test_recursion_normalizing_with_no_memory(self):
  1270. # Issue #30697. Test that in the abort that occurs when there is no
  1271. # memory left and the size of the Python frames stack is greater than
  1272. # the size of the list of preallocated MemoryError instances, the
  1273. # Fatal Python error message mentions MemoryError.
  1274. code = """if 1:
  1275. import _testcapi
  1276. class C(): pass
  1277. def recurse(cnt):
  1278. cnt -= 1
  1279. if cnt:
  1280. recurse(cnt)
  1281. else:
  1282. _testcapi.set_nomemory(0)
  1283. C()
  1284. recurse(16)
  1285. """
  1286. with SuppressCrashReport():
  1287. rc, out, err = script_helper.assert_python_failure("-c", code)
  1288. self.assertIn(b'MemoryError', err)
  1289. @cpython_only
  1290. def test_MemoryError(self):
  1291. # PyErr_NoMemory always raises the same exception instance.
  1292. # Check that the traceback is not doubled.
  1293. import traceback
  1294. from _testcapi import raise_memoryerror
  1295. def raiseMemError():
  1296. try:
  1297. raise_memoryerror()
  1298. except MemoryError as e:
  1299. tb = e.__traceback__
  1300. else:
  1301. self.fail("Should have raised a MemoryError")
  1302. return traceback.format_tb(tb)
  1303. tb1 = raiseMemError()
  1304. tb2 = raiseMemError()
  1305. self.assertEqual(tb1, tb2)
  1306. @cpython_only
  1307. def test_exception_with_doc(self):
  1308. import _testcapi
  1309. doc2 = "This is a test docstring."
  1310. doc4 = "This is another test docstring."
  1311. self.assertRaises(SystemError, _testcapi.make_exception_with_doc,
  1312. "error1")
  1313. # test basic usage of PyErr_NewException
  1314. error1 = _testcapi.make_exception_with_doc("_testcapi.error1")
  1315. self.assertIs(type(error1), type)
  1316. self.assertTrue(issubclass(error1, Exception))
  1317. self.assertIsNone(error1.__doc__)
  1318. # test with given docstring
  1319. error2 = _testcapi.make_exception_with_doc("_testcapi.error2", doc2)
  1320. self.assertEqual(error2.__doc__, doc2)
  1321. # test with explicit base (without docstring)
  1322. error3 = _testcapi.make_exception_with_doc("_testcapi.error3",
  1323. base=error2)
  1324. self.assertTrue(issubclass(error3, error2))
  1325. # test with explicit base tuple
  1326. class C(object):
  1327. pass
  1328. error4 = _testcapi.make_exception_with_doc("_testcapi.error4", doc4,
  1329. (error3, C))
  1330. self.assertTrue(issubclass(error4, error3))
  1331. self.assertTrue(issubclass(error4, C))
  1332. self.assertEqual(error4.__doc__, doc4)
  1333. # test with explicit dictionary
  1334. error5 = _testcapi.make_exception_with_doc("_testcapi.error5", "",
  1335. error4, {'a': 1})
  1336. self.assertTrue(issubclass(error5, error4))
  1337. self.assertEqual(error5.a, 1)
  1338. self.assertEqual(error5.__doc__, "")
  1339. @cpython_only
  1340. def test_memory_error_cleanup(self):
  1341. # Issue #5437: preallocated MemoryError instances should not keep
  1342. # traceback objects alive.
  1343. from _testcapi import raise_memoryerror
  1344. class C:
  1345. pass
  1346. wr = None
  1347. def inner():
  1348. nonlocal wr
  1349. c = C()
  1350. wr = weakref.ref(c)
  1351. raise_memoryerror()
  1352. # We cannot use assertRaises since it manually deletes the traceback
  1353. try:
  1354. inner()
  1355. except MemoryError as e:
  1356. self.assertNotEqual(wr(), None)
  1357. else:
  1358. self.fail("MemoryError not raised")
  1359. gc_collect() # For PyPy or other GCs.
  1360. self.assertEqual(wr(), None)
  1361. @no_tracing
  1362. def test_recursion_error_cleanup(self):
  1363. # Same test as above, but with "recursion exceeded" errors
  1364. class C:
  1365. pass
  1366. wr = None
  1367. def inner():
  1368. nonlocal wr
  1369. c = C()
  1370. wr = weakref.ref(c)
  1371. inner()
  1372. # We cannot use assertRaises since it manually deletes the traceback
  1373. try:
  1374. inner()
  1375. except RecursionError as e:
  1376. self.assertNotEqual(wr(), None)
  1377. else:
  1378. self.fail("RecursionError not raised")
  1379. gc_collect() # For PyPy or other GCs.
  1380. self.assertEqual(wr(), None)
  1381. def test_errno_ENOTDIR(self):
  1382. # Issue #12802: "not a directory" errors are ENOTDIR even on Windows
  1383. with self.assertRaises(OSError) as cm:
  1384. os.listdir(__file__)
  1385. self.assertEqual(cm.exception.errno, errno.ENOTDIR, cm.exception)
  1386. def test_unraisable(self):
  1387. # Issue #22836: PyErr_WriteUnraisable() should give sensible reports
  1388. class BrokenDel:
  1389. def __del__(self):
  1390. exc = ValueError("del is broken")
  1391. # The following line is included in the traceback report:
  1392. raise exc
  1393. obj = BrokenDel()
  1394. with support.catch_unraisable_exception() as cm:
  1395. del obj
  1396. gc_collect() # For PyPy or other GCs.
  1397. self.assertEqual(cm.unraisable.object, BrokenDel.__del__)
  1398. self.assertIsNotNone(cm.unraisable.exc_traceback)
  1399. def test_unhandled(self):
  1400. # Check for sensible reporting of unhandled exceptions
  1401. for exc_type in (ValueError, BrokenStrException):
  1402. with self.subTest(exc_type):
  1403. try:
  1404. exc = exc_type("test message")
  1405. # The following line is included in the traceback report:
  1406. raise exc
  1407. except exc_type:
  1408. with captured_stderr() as stderr:
  1409. sys.__excepthook__(*sys.exc_info())
  1410. report = stderr.getvalue()
  1411. self.assertIn("test_exceptions.py", report)
  1412. self.assertIn("raise exc", report)
  1413. self.assertIn(exc_type.__name__, report)
  1414. if exc_type is BrokenStrException:
  1415. self.assertIn("<exception str() failed>", report)
  1416. else:
  1417. self.assertIn("test message", report)
  1418. self.assertTrue(report.endswith("\n"))
  1419. @cpython_only
  1420. def test_memory_error_in_PyErr_PrintEx(self):
  1421. code = """if 1:
  1422. import _testcapi
  1423. class C(): pass
  1424. _testcapi.set_nomemory(0, %d)
  1425. C()
  1426. """
  1427. # Issue #30817: Abort in PyErr_PrintEx() when no memory.
  1428. # Span a large range of tests as the CPython code always evolves with
  1429. # changes that add or remove memory allocations.
  1430. for i in range(1, 20):
  1431. rc, out, err = script_helper.assert_python_failure("-c", code % i)
  1432. self.assertIn(rc, (1, 120))
  1433. self.assertIn(b'MemoryError', err)
  1434. def test_yield_in_nested_try_excepts(self):
  1435. #Issue #25612
  1436. class MainError(Exception):
  1437. pass
  1438. class SubError(Exception):
  1439. pass
  1440. def main():
  1441. try:
  1442. raise MainError()
  1443. except MainError:
  1444. try:
  1445. yield
  1446. except SubError:
  1447. pass
  1448. raise
  1449. coro = main()
  1450. coro.send(None)
  1451. with self.assertRaises(MainError):
  1452. coro.throw(SubError())
  1453. def test_generator_doesnt_retain_old_exc2(self):
  1454. #Issue 28884#msg282532
  1455. def g():
  1456. try:
  1457. raise ValueError
  1458. except ValueError:
  1459. yield 1
  1460. self.assertEqual(sys.exc_info(), (None, None, None))
  1461. yield 2
  1462. gen = g()
  1463. try:
  1464. raise IndexError
  1465. except IndexError:
  1466. self.assertEqual(next(gen), 1)
  1467. self.assertEqual(next(gen), 2)
  1468. def test_raise_in_generator(self):
  1469. #Issue 25612#msg304117
  1470. def g():
  1471. yield 1
  1472. raise
  1473. yield 2
  1474. with self.assertRaises(ZeroDivisionError):
  1475. i = g()
  1476. try:
  1477. 1/0
  1478. except:
  1479. next(i)
  1480. next(i)
  1481. @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
  1482. def test_assert_shadowing(self):
  1483. # Shadowing AssertionError would cause the assert statement to
  1484. # misbehave.
  1485. global AssertionError
  1486. AssertionError = TypeError
  1487. try:
  1488. assert False, 'hello'
  1489. except BaseException as e:
  1490. del AssertionError
  1491. self.assertIsInstance(e, AssertionError)
  1492. self.assertEqual(str(e), 'hello')
  1493. else:
  1494. del AssertionError
  1495. self.fail('Expected exception')
  1496. def test_memory_error_subclasses(self):
  1497. # bpo-41654: MemoryError instances use a freelist of objects that are
  1498. # linked using the 'dict' attribute when they are inactive/dead.
  1499. # Subclasses of MemoryError should not participate in the freelist
  1500. # schema. This test creates a MemoryError object and keeps it alive
  1501. # (therefore advancing the freelist) and then it creates and destroys a
  1502. # subclass object. Finally, it checks that creating a new MemoryError
  1503. # succeeds, proving that the freelist is not corrupted.
  1504. class TestException(MemoryError):
  1505. pass
  1506. try:
  1507. raise MemoryError
  1508. except MemoryError as exc:
  1509. inst = exc
  1510. try:
  1511. raise TestException
  1512. except Exception:
  1513. pass
  1514. for _ in range(10):
  1515. try:
  1516. raise MemoryError
  1517. except MemoryError as exc:
  1518. pass
  1519. gc_collect()
  1520. global_for_suggestions = None
  1521. class NameErrorTests(unittest.TestCase):
  1522. def test_name_error_has_name(self):
  1523. try:
  1524. bluch
  1525. except NameError as exc:
  1526. self.assertEqual("bluch", exc.name)
  1527. def test_name_error_suggestions(self):
  1528. def Substitution():
  1529. noise = more_noise = a = bc = None
  1530. blech = None
  1531. print(bluch)
  1532. def Elimination():
  1533. noise = more_noise = a = bc = None
  1534. blch = None
  1535. print(bluch)
  1536. def Addition():
  1537. noise = more_noise = a = bc = None
  1538. bluchin = None
  1539. print(bluch)
  1540. def SubstitutionOverElimination():
  1541. blach = None
  1542. bluc = None
  1543. print(bluch)
  1544. def SubstitutionOverAddition():
  1545. blach = None
  1546. bluchi = None
  1547. print(bluch)
  1548. def EliminationOverAddition():
  1549. blucha = None
  1550. bluc = None
  1551. print(bluch)
  1552. for func, suggestion in [(Substitution, "'blech'?"),
  1553. (Elimination, "'blch'?"),
  1554. (Addition, "'bluchin'?"),
  1555. (EliminationOverAddition, "'blucha'?"),
  1556. (SubstitutionOverElimination, "'blach'?"),
  1557. (SubstitutionOverAddition, "'blach'?")]:
  1558. err = None
  1559. try:
  1560. func()
  1561. except NameError as exc:
  1562. with support.captured_stderr() as err:
  1563. sys.__excepthook__(*sys.exc_info())
  1564. self.assertIn(suggestion, err.getvalue())
  1565. def test_name_error_suggestions_from_globals(self):
  1566. def func():
  1567. print(global_for_suggestio)
  1568. try:
  1569. func()
  1570. except NameError as exc:
  1571. with support.captured_stderr() as err:
  1572. sys.__excepthook__(*sys.exc_info())
  1573. self.assertIn("'global_for_suggestions'?", err.getvalue())
  1574. def test_name_error_suggestions_from_builtins(self):
  1575. def func():
  1576. print(ZeroDivisionErrrrr)
  1577. try:
  1578. func()
  1579. except NameError as exc:
  1580. with support.captured_stderr() as err:
  1581. sys.__excepthook__(*sys.exc_info())
  1582. self.assertIn("'ZeroDivisionError'?", err.getvalue())
  1583. def test_name_error_suggestions_do_not_trigger_for_long_names(self):
  1584. def f():
  1585. somethingverywronghehehehehehe = None
  1586. print(somethingverywronghe)
  1587. try:
  1588. f()
  1589. except NameError as exc:
  1590. with support.captured_stderr() as err:
  1591. sys.__excepthook__(*sys.exc_info())
  1592. self.assertNotIn("somethingverywronghehe", err.getvalue())
  1593. def test_name_error_bad_suggestions_do_not_trigger_for_small_names(self):
  1594. vvv = mom = w = id = pytho = None
  1595. with self.subTest(name="b"):
  1596. try:
  1597. b
  1598. except NameError as exc:
  1599. with support.captured_stderr() as err:
  1600. sys.__excepthook__(*sys.exc_info())
  1601. self.assertNotIn("you mean", err.getvalue())
  1602. self.assertNotIn("vvv", err.getvalue())
  1603. self.assertNotIn("mom", err.getvalue())
  1604. self.assertNotIn("'id'", err.getvalue())
  1605. self.assertNotIn("'w'", err.getvalue())
  1606. self.assertNotIn("'pytho'", err.getvalue())
  1607. with self.subTest(name="v"):
  1608. try:
  1609. v
  1610. except NameError as exc:
  1611. with support.captured_stderr() as err:
  1612. sys.__excepthook__(*sys.exc_info())
  1613. self.assertNotIn("you mean", err.getvalue())
  1614. self.assertNotIn("vvv", err.getvalue())
  1615. self.assertNotIn("mom", err.getvalue())
  1616. self.assertNotIn("'id'", err.getvalue())
  1617. self.assertNotIn("'w'", err.getvalue())
  1618. self.assertNotIn("'pytho'", err.getvalue())
  1619. with self.subTest(name="m"):
  1620. try:
  1621. m
  1622. except NameError as exc:
  1623. with support.captured_stderr() as err:
  1624. sys.__excepthook__(*sys.exc_info())
  1625. self.assertNotIn("you mean", err.getvalue())
  1626. self.assertNotIn("vvv", err.getvalue())
  1627. self.assertNotIn("mom", err.getvalue())
  1628. self.assertNotIn("'id'", err.getvalue())
  1629. self.assertNotIn("'w'", err.getvalue())
  1630. self.assertNotIn("'pytho'", err.getvalue())
  1631. with self.subTest(name="py"):
  1632. try:
  1633. py
  1634. except NameError as exc:
  1635. with support.captured_stderr() as err:
  1636. sys.__excepthook__(*sys.exc_info())
  1637. self.assertNotIn("you mean", err.getvalue())
  1638. self.assertNotIn("vvv", err.getvalue())
  1639. self.assertNotIn("mom", err.getvalue())
  1640. self.assertNotIn("'id'", err.getvalue())
  1641. self.assertNotIn("'w'", err.getvalue())
  1642. self.assertNotIn("'pytho'", err.getvalue())
  1643. def test_name_error_suggestions_do_not_trigger_for_too_many_locals(self):
  1644. def f():
  1645. # Mutating locals() is unreliable, so we need to do it by hand
  1646. a1 = a2 = a3 = a4 = a5 = a6 = a7 = a8 = a9 = a10 = \
  1647. a11 = a12 = a13 = a14 = a15 = a16 = a17 = a18 = a19 = a20 = \
  1648. a21 = a22 = a23 = a24 = a25 = a26 = a27 = a28 = a29 = a30 = \
  1649. a31 = a32 = a33 = a34 = a35 = a36 = a37 = a38 = a39 = a40 = \
  1650. a41 = a42 = a43 = a44 = a45 = a46 = a47 = a48 = a49 = a50 = \
  1651. a51 = a52 = a53 = a54 = a55 = a56 = a57 = a58 = a59 = a60 = \
  1652. a61 = a62 = a63 = a64 = a65 = a66 = a67 = a68 = a69 = a70 = \
  1653. a71 = a72 = a73 = a74 = a75 = a76 = a77 = a78 = a79 = a80 = \
  1654. a81 = a82 = a83 = a84 = a85 = a86 = a87 = a88 = a89 = a90 = \
  1655. a91 = a92 = a93 = a94 = a95 = a96 = a97 = a98 = a99 = a100 = \
  1656. a101 = a102 = a103 = a104 = a105 = a106 = a107 = a108 = a109 = a110 = \
  1657. a111 = a112 = a113 = a114 = a115 = a116 = a117 = a118 = a119 = a120 = \
  1658. a121 = a122 = a123 = a124 = a125 = a126 = a127 = a128 = a129 = a130 = \
  1659. a131 = a132 = a133 = a134 = a135 = a136 = a137 = a138 = a139 = a140 = \
  1660. a141 = a142 = a143 = a144 = a145 = a146 = a147 = a148 = a149 = a150 = \
  1661. a151 = a152 = a153 = a154 = a155 = a156 = a157 = a158 = a159 = a160 = \
  1662. a161 = a162 = a163 = a164 = a165 = a166 = a167 = a168 = a169 = a170 = \
  1663. a171 = a172 = a173 = a174 = a175 = a176 = a177 = a178 = a179 = a180 = \
  1664. a181 = a182 = a183 = a184 = a185 = a186 = a187 = a188 = a189 = a190 = \
  1665. a191 = a192 = a193 = a194 = a195 = a196 = a197 = a198 = a199 = a200 = \
  1666. a201 = a202 = a203 = a204 = a205 = a206 = a207 = a208 = a209 = a210 = \
  1667. a211 = a212 = a213 = a214 = a215 = a216 = a217 = a218 = a219 = a220 = \
  1668. a221 = a222 = a223 = a224 = a225 = a226 = a227 = a228 = a229 = a230 = \
  1669. a231 = a232 = a233 = a234 = a235 = a236 = a237 = a238 = a239 = a240 = \
  1670. a241 = a242 = a243 = a244 = a245 = a246 = a247 = a248 = a249 = a250 = \
  1671. a251 = a252 = a253 = a254 = a255 = a256 = a257 = a258 = a259 = a260 = \
  1672. a261 = a262 = a263 = a264 = a265 = a266 = a267 = a268 = a269 = a270 = \
  1673. a271 = a272 = a273 = a274 = a275 = a276 = a277 = a278 = a279 = a280 = \
  1674. a281 = a282 = a283 = a284 = a285 = a286 = a287 = a288 = a289 = a290 = \
  1675. a291 = a292 = a293 = a294 = a295 = a296 = a297 = a298 = a299 = a300 = \
  1676. a301 = a302 = a303 = a304 = a305 = a306 = a307 = a308 = a309 = a310 = \
  1677. a311 = a312 = a313 = a314 = a315 = a316 = a317 = a318 = a319 = a320 = \
  1678. a321 = a322 = a323 = a324 = a325 = a326 = a327 = a328 = a329 = a330 = \
  1679. a331 = a332 = a333 = a334 = a335 = a336 = a337 = a338 = a339 = a340 = \
  1680. a341 = a342 = a343 = a344 = a345 = a346 = a347 = a348 = a349 = a350 = \
  1681. a351 = a352 = a353 = a354 = a355 = a356 = a357 = a358 = a359 = a360 = \
  1682. a361 = a362 = a363 = a364 = a365 = a366 = a367 = a368 = a369 = a370 = \
  1683. a371 = a372 = a373 = a374 = a375 = a376 = a377 = a378 = a379 = a380 = \
  1684. a381 = a382 = a383 = a384 = a385 = a386 = a387 = a388 = a389 = a390 = \
  1685. a391 = a392 = a393 = a394 = a395 = a396 = a397 = a398 = a399 = a400 = \
  1686. a401 = a402 = a403 = a404 = a405 = a406 = a407 = a408 = a409 = a410 = \
  1687. a411 = a412 = a413 = a414 = a415 = a416 = a417 = a418 = a419 = a420 = \
  1688. a421 = a422 = a423 = a424 = a425 = a426 = a427 = a428 = a429 = a430 = \
  1689. a431 = a432 = a433 = a434 = a435 = a436 = a437 = a438 = a439 = a440 = \
  1690. a441 = a442 = a443 = a444 = a445 = a446 = a447 = a448 = a449 = a450 = \
  1691. a451 = a452 = a453 = a454 = a455 = a456 = a457 = a458 = a459 = a460 = \
  1692. a461 = a462 = a463 = a464 = a465 = a466 = a467 = a468 = a469 = a470 = \
  1693. a471 = a472 = a473 = a474 = a475 = a476 = a477 = a478 = a479 = a480 = \
  1694. a481 = a482 = a483 = a484 = a485 = a486 = a487 = a488 = a489 = a490 = \
  1695. a491 = a492 = a493 = a494 = a495 = a496 = a497 = a498 = a499 = a500 = \
  1696. a501 = a502 = a503 = a504 = a505 = a506 = a507 = a508 = a509 = a510 = \
  1697. a511 = a512 = a513 = a514 = a515 = a516 = a517 = a518 = a519 = a520 = \
  1698. a521 = a522 = a523 = a524 = a525 = a526 = a527 = a528 = a529 = a530 = \
  1699. a531 = a532 = a533 = a534 = a535 = a536 = a537 = a538 = a539 = a540 = \
  1700. a541 = a542 = a543 = a544 = a545 = a546 = a547 = a548 = a549 = a550 = \
  1701. a551 = a552 = a553 = a554 = a555 = a556 = a557 = a558 = a559 = a560 = \
  1702. a561 = a562 = a563 = a564 = a565 = a566 = a567 = a568 = a569 = a570 = \
  1703. a571 = a572 = a573 = a574 = a575 = a576 = a577 = a578 = a579 = a580 = \
  1704. a581 = a582 = a583 = a584 = a585 = a586 = a587 = a588 = a589 = a590 = \
  1705. a591 = a592 = a593 = a594 = a595 = a596 = a597 = a598 = a599 = a600 = \
  1706. a601 = a602 = a603 = a604 = a605 = a606 = a607 = a608 = a609 = a610 = \
  1707. a611 = a612 = a613 = a614 = a615 = a616 = a617 = a618 = a619 = a620 = \
  1708. a621 = a622 = a623 = a624 = a625 = a626 = a627 = a628 = a629 = a630 = \
  1709. a631 = a632 = a633 = a634 = a635 = a636 = a637 = a638 = a639 = a640 = \
  1710. a641 = a642 = a643 = a644 = a645 = a646 = a647 = a648 = a649 = a650 = \
  1711. a651 = a652 = a653 = a654 = a655 = a656 = a657 = a658 = a659 = a660 = \
  1712. a661 = a662 = a663 = a664 = a665 = a666 = a667 = a668 = a669 = a670 = \
  1713. a671 = a672 = a673 = a674 = a675 = a676 = a677 = a678 = a679 = a680 = \
  1714. a681 = a682 = a683 = a684 = a685 = a686 = a687 = a688 = a689 = a690 = \
  1715. a691 = a692 = a693 = a694 = a695 = a696 = a697 = a698 = a699 = a700 = \
  1716. a701 = a702 = a703 = a704 = a705 = a706 = a707 = a708 = a709 = a710 = \
  1717. a711 = a712 = a713 = a714 = a715 = a716 = a717 = a718 = a719 = a720 = \
  1718. a721 = a722 = a723 = a724 = a725 = a726 = a727 = a728 = a729 = a730 = \
  1719. a731 = a732 = a733 = a734 = a735 = a736 = a737 = a738 = a739 = a740 = \
  1720. a741 = a742 = a743 = a744 = a745 = a746 = a747 = a748 = a749 = a750 = \
  1721. a751 = a752 = a753 = a754 = a755 = a756 = a757 = a758 = a759 = a760 = \
  1722. a761 = a762 = a763 = a764 = a765 = a766 = a767 = a768 = a769 = a770 = \
  1723. a771 = a772 = a773 = a774 = a775 = a776 = a777 = a778 = a779 = a780 = \
  1724. a781 = a782 = a783 = a784 = a785 = a786 = a787 = a788 = a789 = a790 = \
  1725. a791 = a792 = a793 = a794 = a795 = a796 = a797 = a798 = a799 = a800 \
  1726. = None
  1727. print(a0)
  1728. try:
  1729. f()
  1730. except NameError as exc:
  1731. with support.captured_stderr() as err:
  1732. sys.__excepthook__(*sys.exc_info())
  1733. self.assertNotRegex(err.getvalue(), r"NameError.*a1")
  1734. def test_name_error_with_custom_exceptions(self):
  1735. def f():
  1736. blech = None
  1737. raise NameError()
  1738. try:
  1739. f()
  1740. except NameError as exc:
  1741. with support.captured_stderr() as err:
  1742. sys.__excepthook__(*sys.exc_info())
  1743. self.assertNotIn("blech", err.getvalue())
  1744. def f():
  1745. blech = None
  1746. raise NameError
  1747. try:
  1748. f()
  1749. except NameError as exc:
  1750. with support.captured_stderr() as err:
  1751. sys.__excepthook__(*sys.exc_info())
  1752. self.assertNotIn("blech", err.getvalue())
  1753. def test_unbound_local_error_doesn_not_match(self):
  1754. def foo():
  1755. something = 3
  1756. print(somethong)
  1757. somethong = 3
  1758. try:
  1759. foo()
  1760. except UnboundLocalError as exc:
  1761. with support.captured_stderr() as err:
  1762. sys.__excepthook__(*sys.exc_info())
  1763. self.assertNotIn("something", err.getvalue())
  1764. def test_issue45826(self):
  1765. # regression test for bpo-45826
  1766. def f():
  1767. with self.assertRaisesRegex(NameError, 'aaa'):
  1768. aab
  1769. try:
  1770. f()
  1771. except self.failureException:
  1772. with support.captured_stderr() as err:
  1773. sys.__excepthook__(*sys.exc_info())
  1774. self.assertIn("aab", err.getvalue())
  1775. def test_issue45826_focused(self):
  1776. def f():
  1777. try:
  1778. nonsense
  1779. except BaseException as E:
  1780. E.with_traceback(None)
  1781. raise ZeroDivisionError()
  1782. try:
  1783. f()
  1784. except ZeroDivisionError:
  1785. with support.captured_stderr() as err:
  1786. sys.__excepthook__(*sys.exc_info())
  1787. self.assertIn("nonsense", err.getvalue())
  1788. self.assertIn("ZeroDivisionError", err.getvalue())
  1789. class AttributeErrorTests(unittest.TestCase):
  1790. def test_attributes(self):
  1791. # Setting 'attr' should not be a problem.
  1792. exc = AttributeError('Ouch!')
  1793. self.assertIsNone(exc.name)
  1794. self.assertIsNone(exc.obj)
  1795. sentinel = object()
  1796. exc = AttributeError('Ouch', name='carry', obj=sentinel)
  1797. self.assertEqual(exc.name, 'carry')
  1798. self.assertIs(exc.obj, sentinel)
  1799. def test_getattr_has_name_and_obj(self):
  1800. class A:
  1801. blech = None
  1802. obj = A()
  1803. try:
  1804. obj.bluch
  1805. except AttributeError as exc:
  1806. self.assertEqual("bluch", exc.name)
  1807. self.assertEqual(obj, exc.obj)
  1808. try:
  1809. object.__getattribute__(obj, "bluch")
  1810. except AttributeError as exc:
  1811. self.assertEqual("bluch", exc.name)
  1812. self.assertEqual(obj, exc.obj)
  1813. def test_getattr_has_name_and_obj_for_method(self):
  1814. class A:
  1815. def blech(self):
  1816. return
  1817. obj = A()
  1818. try:
  1819. obj.bluch()
  1820. except AttributeError as exc:
  1821. self.assertEqual("bluch", exc.name)
  1822. self.assertEqual(obj, exc.obj)
  1823. def test_getattr_suggestions(self):
  1824. class Substitution:
  1825. noise = more_noise = a = bc = None
  1826. blech = None
  1827. class Elimination:
  1828. noise = more_noise = a = bc = None
  1829. blch = None
  1830. class Addition:
  1831. noise = more_noise = a = bc = None
  1832. bluchin = None
  1833. class SubstitutionOverElimination:
  1834. blach = None
  1835. bluc = None
  1836. class SubstitutionOverAddition:
  1837. blach = None
  1838. bluchi = None
  1839. class EliminationOverAddition:
  1840. blucha = None
  1841. bluc = None
  1842. for cls, suggestion in [(Substitution, "'blech'?"),
  1843. (Elimination, "'blch'?"),
  1844. (Addition, "'bluchin'?"),
  1845. (EliminationOverAddition, "'bluc'?"),
  1846. (SubstitutionOverElimination, "'blach'?"),
  1847. (SubstitutionOverAddition, "'blach'?")]:
  1848. try:
  1849. cls().bluch
  1850. except AttributeError as exc:
  1851. with support.captured_stderr() as err:
  1852. sys.__excepthook__(*sys.exc_info())
  1853. self.assertIn(suggestion, err.getvalue())
  1854. def test_getattr_suggestions_do_not_trigger_for_long_attributes(self):
  1855. class A:
  1856. blech = None
  1857. try:
  1858. A().somethingverywrong
  1859. except AttributeError as exc:
  1860. with support.captured_stderr() as err:
  1861. sys.__excepthook__(*sys.exc_info())
  1862. self.assertNotIn("blech", err.getvalue())
  1863. def test_getattr_error_bad_suggestions_do_not_trigger_for_small_names(self):
  1864. class MyClass:
  1865. vvv = mom = w = id = pytho = None
  1866. with self.subTest(name="b"):
  1867. try:
  1868. MyClass.b
  1869. except AttributeError as exc:
  1870. with support.captured_stderr() as err:
  1871. sys.__excepthook__(*sys.exc_info())
  1872. self.assertNotIn("you mean", err.getvalue())
  1873. self.assertNotIn("vvv", err.getvalue())
  1874. self.assertNotIn("mom", err.getvalue())
  1875. self.assertNotIn("'id'", err.getvalue())
  1876. self.assertNotIn("'w'", err.getvalue())
  1877. self.assertNotIn("'pytho'", err.getvalue())
  1878. with self.subTest(name="v"):
  1879. try:
  1880. MyClass.v
  1881. except AttributeError as exc:
  1882. with support.captured_stderr() as err:
  1883. sys.__excepthook__(*sys.exc_info())
  1884. self.assertNotIn("you mean", err.getvalue())
  1885. self.assertNotIn("vvv", err.getvalue())
  1886. self.assertNotIn("mom", err.getvalue())
  1887. self.assertNotIn("'id'", err.getvalue())
  1888. self.assertNotIn("'w'", err.getvalue())
  1889. self.assertNotIn("'pytho'", err.getvalue())
  1890. with self.subTest(name="m"):
  1891. try:
  1892. MyClass.m
  1893. except AttributeError as exc:
  1894. with support.captured_stderr() as err:
  1895. sys.__excepthook__(*sys.exc_info())
  1896. self.assertNotIn("you mean", err.getvalue())
  1897. self.assertNotIn("vvv", err.getvalue())
  1898. self.assertNotIn("mom", err.getvalue())
  1899. self.assertNotIn("'id'", err.getvalue())
  1900. self.assertNotIn("'w'", err.getvalue())
  1901. self.assertNotIn("'pytho'", err.getvalue())
  1902. with self.subTest(name="py"):
  1903. try:
  1904. MyClass.py
  1905. except AttributeError as exc:
  1906. with support.captured_stderr() as err:
  1907. sys.__excepthook__(*sys.exc_info())
  1908. self.assertNotIn("you mean", err.getvalue())
  1909. self.assertNotIn("vvv", err.getvalue())
  1910. self.assertNotIn("mom", err.getvalue())
  1911. self.assertNotIn("'id'", err.getvalue())
  1912. self.assertNotIn("'w'", err.getvalue())
  1913. self.assertNotIn("'pytho'", err.getvalue())
  1914. def test_getattr_suggestions_do_not_trigger_for_big_dicts(self):
  1915. class A:
  1916. blech = None
  1917. # A class with a very big __dict__ will not be consider
  1918. # for suggestions.
  1919. for index in range(2000):
  1920. setattr(A, f"index_{index}", None)
  1921. try:
  1922. A().bluch
  1923. except AttributeError as exc:
  1924. with support.captured_stderr() as err:
  1925. sys.__excepthook__(*sys.exc_info())
  1926. self.assertNotIn("blech", err.getvalue())
  1927. def test_getattr_suggestions_no_args(self):
  1928. class A:
  1929. blech = None
  1930. def __getattr__(self, attr):
  1931. raise AttributeError()
  1932. try:
  1933. A().bluch
  1934. except AttributeError as exc:
  1935. with support.captured_stderr() as err:
  1936. sys.__excepthook__(*sys.exc_info())
  1937. self.assertIn("blech", err.getvalue())
  1938. class A:
  1939. blech = None
  1940. def __getattr__(self, attr):
  1941. raise AttributeError
  1942. try:
  1943. A().bluch
  1944. except AttributeError as exc:
  1945. with support.captured_stderr() as err:
  1946. sys.__excepthook__(*sys.exc_info())
  1947. self.assertIn("blech", err.getvalue())
  1948. def test_getattr_suggestions_invalid_args(self):
  1949. class NonStringifyClass:
  1950. __str__ = None
  1951. __repr__ = None
  1952. class A:
  1953. blech = None
  1954. def __getattr__(self, attr):
  1955. raise AttributeError(NonStringifyClass())
  1956. class B:
  1957. blech = None
  1958. def __getattr__(self, attr):
  1959. raise AttributeError("Error", 23)
  1960. class C:
  1961. blech = None
  1962. def __getattr__(self, attr):
  1963. raise AttributeError(23)
  1964. for cls in [A, B, C]:
  1965. try:
  1966. cls().bluch
  1967. except AttributeError as exc:
  1968. with support.captured_stderr() as err:
  1969. sys.__excepthook__(*sys.exc_info())
  1970. self.assertIn("blech", err.getvalue())
  1971. def test_getattr_suggestions_for_same_name(self):
  1972. class A:
  1973. def __dir__(self):
  1974. return ['blech']
  1975. try:
  1976. A().blech
  1977. except AttributeError as exc:
  1978. with support.captured_stderr() as err:
  1979. sys.__excepthook__(*sys.exc_info())
  1980. self.assertNotIn("Did you mean", err.getvalue())
  1981. def test_attribute_error_with_failing_dict(self):
  1982. class T:
  1983. bluch = 1
  1984. def __dir__(self):
  1985. raise AttributeError("oh no!")
  1986. try:
  1987. T().blich
  1988. except AttributeError as exc:
  1989. with support.captured_stderr() as err:
  1990. sys.__excepthook__(*sys.exc_info())
  1991. self.assertNotIn("blech", err.getvalue())
  1992. self.assertNotIn("oh no!", err.getvalue())
  1993. def test_attribute_error_with_bad_name(self):
  1994. try:
  1995. raise AttributeError(name=12, obj=23)
  1996. except AttributeError as exc:
  1997. with support.captured_stderr() as err:
  1998. sys.__excepthook__(*sys.exc_info())
  1999. self.assertNotIn("?", err.getvalue())
  2000. def test_attribute_error_inside_nested_getattr(self):
  2001. class A:
  2002. bluch = 1
  2003. class B:
  2004. def __getattribute__(self, attr):
  2005. a = A()
  2006. return a.blich
  2007. try:
  2008. B().something
  2009. except AttributeError as exc:
  2010. with support.captured_stderr() as err:
  2011. sys.__excepthook__(*sys.exc_info())
  2012. self.assertIn("Did you mean", err.getvalue())
  2013. self.assertIn("bluch", err.getvalue())
  2014. class ImportErrorTests(unittest.TestCase):
  2015. def test_attributes(self):
  2016. # Setting 'name' and 'path' should not be a problem.
  2017. exc = ImportError('test')
  2018. self.assertIsNone(exc.name)
  2019. self.assertIsNone(exc.path)
  2020. exc = ImportError('test', name='somemodule')
  2021. self.assertEqual(exc.name, 'somemodule')
  2022. self.assertIsNone(exc.path)
  2023. exc = ImportError('test', path='somepath')
  2024. self.assertEqual(exc.path, 'somepath')
  2025. self.assertIsNone(exc.name)
  2026. exc = ImportError('test', path='somepath', name='somename')
  2027. self.assertEqual(exc.name, 'somename')
  2028. self.assertEqual(exc.path, 'somepath')
  2029. msg = "'invalid' is an invalid keyword argument for ImportError"
  2030. with self.assertRaisesRegex(TypeError, msg):
  2031. ImportError('test', invalid='keyword')
  2032. with self.assertRaisesRegex(TypeError, msg):
  2033. ImportError('test', name='name', invalid='keyword')
  2034. with self.assertRaisesRegex(TypeError, msg):
  2035. ImportError('test', path='path', invalid='keyword')
  2036. with self.assertRaisesRegex(TypeError, msg):
  2037. ImportError(invalid='keyword')
  2038. with self.assertRaisesRegex(TypeError, msg):
  2039. ImportError('test', invalid='keyword', another=True)
  2040. def test_reset_attributes(self):
  2041. exc = ImportError('test', name='name', path='path')
  2042. self.assertEqual(exc.args, ('test',))
  2043. self.assertEqual(exc.msg, 'test')
  2044. self.assertEqual(exc.name, 'name')
  2045. self.assertEqual(exc.path, 'path')
  2046. # Reset not specified attributes
  2047. exc.__init__()
  2048. self.assertEqual(exc.args, ())
  2049. self.assertEqual(exc.msg, None)
  2050. self.assertEqual(exc.name, None)
  2051. self.assertEqual(exc.path, None)
  2052. def test_non_str_argument(self):
  2053. # Issue #15778
  2054. with check_warnings(('', BytesWarning), quiet=True):
  2055. arg = b'abc'
  2056. exc = ImportError(arg)
  2057. self.assertEqual(str(arg), str(exc))
  2058. def test_copy_pickle(self):
  2059. for kwargs in (dict(),
  2060. dict(name='somename'),
  2061. dict(path='somepath'),
  2062. dict(name='somename', path='somepath')):
  2063. orig = ImportError('test', **kwargs)
  2064. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  2065. exc = pickle.loads(pickle.dumps(orig, proto))
  2066. self.assertEqual(exc.args, ('test',))
  2067. self.assertEqual(exc.msg, 'test')
  2068. self.assertEqual(exc.name, orig.name)
  2069. self.assertEqual(exc.path, orig.path)
  2070. for c in copy.copy, copy.deepcopy:
  2071. exc = c(orig)
  2072. self.assertEqual(exc.args, ('test',))
  2073. self.assertEqual(exc.msg, 'test')
  2074. self.assertEqual(exc.name, orig.name)
  2075. self.assertEqual(exc.path, orig.path)
  2076. class SyntaxErrorTests(unittest.TestCase):
  2077. def test_range_of_offsets(self):
  2078. cases = [
  2079. # Basic range from 2->7
  2080. (("bad.py", 1, 2, "abcdefg", 1, 7),
  2081. dedent(
  2082. """
  2083. File "bad.py", line 1
  2084. abcdefg
  2085. ^^^^^
  2086. SyntaxError: bad bad
  2087. """)),
  2088. # end_offset = start_offset + 1
  2089. (("bad.py", 1, 2, "abcdefg", 1, 3),
  2090. dedent(
  2091. """
  2092. File "bad.py", line 1
  2093. abcdefg
  2094. ^
  2095. SyntaxError: bad bad
  2096. """)),
  2097. # Negative end offset
  2098. (("bad.py", 1, 2, "abcdefg", 1, -2),
  2099. dedent(
  2100. """
  2101. File "bad.py", line 1
  2102. abcdefg
  2103. ^
  2104. SyntaxError: bad bad
  2105. """)),
  2106. # end offset before starting offset
  2107. (("bad.py", 1, 4, "abcdefg", 1, 2),
  2108. dedent(
  2109. """
  2110. File "bad.py", line 1
  2111. abcdefg
  2112. ^
  2113. SyntaxError: bad bad
  2114. """)),
  2115. # Both offsets negative
  2116. (("bad.py", 1, -4, "abcdefg", 1, -2),
  2117. dedent(
  2118. """
  2119. File "bad.py", line 1
  2120. abcdefg
  2121. SyntaxError: bad bad
  2122. """)),
  2123. # Both offsets negative and the end more negative
  2124. (("bad.py", 1, -4, "abcdefg", 1, -5),
  2125. dedent(
  2126. """
  2127. File "bad.py", line 1
  2128. abcdefg
  2129. SyntaxError: bad bad
  2130. """)),
  2131. # Both offsets 0
  2132. (("bad.py", 1, 0, "abcdefg", 1, 0),
  2133. dedent(
  2134. """
  2135. File "bad.py", line 1
  2136. abcdefg
  2137. SyntaxError: bad bad
  2138. """)),
  2139. # Start offset 0 and end offset not 0
  2140. (("bad.py", 1, 0, "abcdefg", 1, 5),
  2141. dedent(
  2142. """
  2143. File "bad.py", line 1
  2144. abcdefg
  2145. SyntaxError: bad bad
  2146. """)),
  2147. # End offset pass the source length
  2148. (("bad.py", 1, 2, "abcdefg", 1, 100),
  2149. dedent(
  2150. """
  2151. File "bad.py", line 1
  2152. abcdefg
  2153. ^^^^^^
  2154. SyntaxError: bad bad
  2155. """)),
  2156. ]
  2157. for args, expected in cases:
  2158. with self.subTest(args=args):
  2159. try:
  2160. raise SyntaxError("bad bad", args)
  2161. except SyntaxError as exc:
  2162. with support.captured_stderr() as err:
  2163. sys.__excepthook__(*sys.exc_info())
  2164. self.assertIn(expected, err.getvalue())
  2165. the_exception = exc
  2166. def test_encodings(self):
  2167. source = (
  2168. '# -*- coding: cp437 -*-\n'
  2169. '"¢¢¢¢¢¢" + f(4, x for x in range(1))\n'
  2170. )
  2171. try:
  2172. with open(TESTFN, 'w', encoding='cp437') as testfile:
  2173. testfile.write(source)
  2174. rc, out, err = script_helper.assert_python_failure('-Wd', '-X', 'utf8', TESTFN)
  2175. err = err.decode('utf-8').splitlines()
  2176. self.assertEqual(err[-3], ' "¢¢¢¢¢¢" + f(4, x for x in range(1))')
  2177. self.assertEqual(err[-2], ' ^^^^^^^^^^^^^^^^^^^')
  2178. finally:
  2179. unlink(TESTFN)
  2180. # Check backwards tokenizer errors
  2181. source = '# -*- coding: ascii -*-\n\n(\n'
  2182. try:
  2183. with open(TESTFN, 'w', encoding='ascii') as testfile:
  2184. testfile.write(source)
  2185. rc, out, err = script_helper.assert_python_failure('-Wd', '-X', 'utf8', TESTFN)
  2186. err = err.decode('utf-8').splitlines()
  2187. self.assertEqual(err[-3], ' (')
  2188. self.assertEqual(err[-2], ' ^')
  2189. finally:
  2190. unlink(TESTFN)
  2191. def test_non_utf8(self):
  2192. # Check non utf-8 characters
  2193. try:
  2194. with open(TESTFN, 'bw') as testfile:
  2195. testfile.write(b"\x89")
  2196. rc, out, err = script_helper.assert_python_failure('-Wd', '-X', 'utf8', TESTFN)
  2197. err = err.decode('utf-8').splitlines()
  2198. self.assertIn("SyntaxError: Non-UTF-8 code starting with '\\x89' in file", err[-1])
  2199. finally:
  2200. unlink(TESTFN)
  2201. def test_attributes_new_constructor(self):
  2202. args = ("bad.py", 1, 2, "abcdefg", 1, 100)
  2203. the_exception = SyntaxError("bad bad", args)
  2204. filename, lineno, offset, error, end_lineno, end_offset = args
  2205. self.assertEqual(filename, the_exception.filename)
  2206. self.assertEqual(lineno, the_exception.lineno)
  2207. self.assertEqual(end_lineno, the_exception.end_lineno)
  2208. self.assertEqual(offset, the_exception.offset)
  2209. self.assertEqual(end_offset, the_exception.end_offset)
  2210. self.assertEqual(error, the_exception.text)
  2211. self.assertEqual("bad bad", the_exception.msg)
  2212. def test_attributes_old_constructor(self):
  2213. args = ("bad.py", 1, 2, "abcdefg")
  2214. the_exception = SyntaxError("bad bad", args)
  2215. filename, lineno, offset, error = args
  2216. self.assertEqual(filename, the_exception.filename)
  2217. self.assertEqual(lineno, the_exception.lineno)
  2218. self.assertEqual(None, the_exception.end_lineno)
  2219. self.assertEqual(offset, the_exception.offset)
  2220. self.assertEqual(None, the_exception.end_offset)
  2221. self.assertEqual(error, the_exception.text)
  2222. self.assertEqual("bad bad", the_exception.msg)
  2223. def test_incorrect_constructor(self):
  2224. args = ("bad.py", 1, 2)
  2225. self.assertRaises(TypeError, SyntaxError, "bad bad", args)
  2226. args = ("bad.py", 1, 2, 4, 5, 6, 7)
  2227. self.assertRaises(TypeError, SyntaxError, "bad bad", args)
  2228. args = ("bad.py", 1, 2, "abcdefg", 1)
  2229. self.assertRaises(TypeError, SyntaxError, "bad bad", args)
  2230. class TestInvalidExceptionMatcher(unittest.TestCase):
  2231. def test_except_star_invalid_exception_type(self):
  2232. with self.assertRaises(TypeError):
  2233. try:
  2234. raise ValueError
  2235. except 42:
  2236. pass
  2237. with self.assertRaises(TypeError):
  2238. try:
  2239. raise ValueError
  2240. except (ValueError, 42):
  2241. pass
  2242. class PEP626Tests(unittest.TestCase):
  2243. def lineno_after_raise(self, f, *expected):
  2244. try:
  2245. f()
  2246. except Exception as ex:
  2247. t = ex.__traceback__
  2248. else:
  2249. self.fail("No exception raised")
  2250. lines = []
  2251. t = t.tb_next # Skip this function
  2252. while t:
  2253. frame = t.tb_frame
  2254. lines.append(
  2255. None if frame.f_lineno is None else
  2256. frame.f_lineno-frame.f_code.co_firstlineno
  2257. )
  2258. t = t.tb_next
  2259. self.assertEqual(tuple(lines), expected)
  2260. def test_lineno_after_raise_simple(self):
  2261. def simple():
  2262. 1/0
  2263. pass
  2264. self.lineno_after_raise(simple, 1)
  2265. def test_lineno_after_raise_in_except(self):
  2266. def in_except():
  2267. try:
  2268. 1/0
  2269. except:
  2270. 1/0
  2271. pass
  2272. self.lineno_after_raise(in_except, 4)
  2273. def test_lineno_after_other_except(self):
  2274. def other_except():
  2275. try:
  2276. 1/0
  2277. except TypeError as ex:
  2278. pass
  2279. self.lineno_after_raise(other_except, 3)
  2280. def test_lineno_in_named_except(self):
  2281. def in_named_except():
  2282. try:
  2283. 1/0
  2284. except Exception as ex:
  2285. 1/0
  2286. pass
  2287. self.lineno_after_raise(in_named_except, 4)
  2288. def test_lineno_in_try(self):
  2289. def in_try():
  2290. try:
  2291. 1/0
  2292. finally:
  2293. pass
  2294. self.lineno_after_raise(in_try, 4)
  2295. def test_lineno_in_finally_normal(self):
  2296. def in_finally_normal():
  2297. try:
  2298. pass
  2299. finally:
  2300. 1/0
  2301. pass
  2302. self.lineno_after_raise(in_finally_normal, 4)
  2303. def test_lineno_in_finally_except(self):
  2304. def in_finally_except():
  2305. try:
  2306. 1/0
  2307. finally:
  2308. 1/0
  2309. pass
  2310. self.lineno_after_raise(in_finally_except, 4)
  2311. def test_lineno_after_with(self):
  2312. class Noop:
  2313. def __enter__(self):
  2314. return self
  2315. def __exit__(self, *args):
  2316. pass
  2317. def after_with():
  2318. with Noop():
  2319. 1/0
  2320. pass
  2321. self.lineno_after_raise(after_with, 2)
  2322. def test_missing_lineno_shows_as_none(self):
  2323. def f():
  2324. 1/0
  2325. self.lineno_after_raise(f, 1)
  2326. f.__code__ = f.__code__.replace(co_linetable=b'\xf8\xf8\xf8\xf9\xf8\xf8\xf8')
  2327. self.lineno_after_raise(f, None)
  2328. def test_lineno_after_raise_in_with_exit(self):
  2329. class ExitFails:
  2330. def __enter__(self):
  2331. return self
  2332. def __exit__(self, *args):
  2333. raise ValueError
  2334. def after_with():
  2335. with ExitFails():
  2336. 1/0
  2337. self.lineno_after_raise(after_with, 1, 1)
  2338. if __name__ == '__main__':
  2339. unittest.main()