test_greenlet.py 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324
  1. import gc
  2. import sys
  3. import time
  4. import threading
  5. import unittest
  6. from abc import ABCMeta
  7. from abc import abstractmethod
  8. import greenlet
  9. from greenlet import greenlet as RawGreenlet
  10. from . import TestCase
  11. from . import RUNNING_ON_MANYLINUX
  12. from . import PY313
  13. from .leakcheck import fails_leakcheck
  14. # We manually manage locks in many tests
  15. # pylint:disable=consider-using-with
  16. # pylint:disable=too-many-public-methods
  17. # This module is quite large.
  18. # TODO: Refactor into separate test files. For example,
  19. # put all the regression tests that used to produce
  20. # crashes in test_greenlet_no_crash; put tests that DO deliberately crash
  21. # the interpreter into test_greenlet_crash.
  22. # pylint:disable=too-many-lines
  23. class SomeError(Exception):
  24. pass
  25. def fmain(seen):
  26. try:
  27. greenlet.getcurrent().parent.switch()
  28. except:
  29. seen.append(sys.exc_info()[0])
  30. raise
  31. raise SomeError
  32. def send_exception(g, exc):
  33. # note: send_exception(g, exc) can be now done with g.throw(exc).
  34. # the purpose of this test is to explicitly check the propagation rules.
  35. def crasher(exc):
  36. raise exc
  37. g1 = RawGreenlet(crasher, parent=g)
  38. g1.switch(exc)
  39. class TestGreenlet(TestCase):
  40. def _do_simple_test(self):
  41. lst = []
  42. def f():
  43. lst.append(1)
  44. greenlet.getcurrent().parent.switch()
  45. lst.append(3)
  46. g = RawGreenlet(f)
  47. lst.append(0)
  48. g.switch()
  49. lst.append(2)
  50. g.switch()
  51. lst.append(4)
  52. self.assertEqual(lst, list(range(5)))
  53. def test_simple(self):
  54. self._do_simple_test()
  55. def test_switch_no_run_raises_AttributeError(self):
  56. g = RawGreenlet()
  57. with self.assertRaises(AttributeError) as exc:
  58. g.switch()
  59. self.assertIn("run", str(exc.exception))
  60. def test_throw_no_run_raises_AttributeError(self):
  61. g = RawGreenlet()
  62. with self.assertRaises(AttributeError) as exc:
  63. g.throw(SomeError)
  64. self.assertIn("run", str(exc.exception))
  65. def test_parent_equals_None(self):
  66. g = RawGreenlet(parent=None)
  67. self.assertIsNotNone(g)
  68. self.assertIs(g.parent, greenlet.getcurrent())
  69. def test_run_equals_None(self):
  70. g = RawGreenlet(run=None)
  71. self.assertIsNotNone(g)
  72. self.assertIsNone(g.run)
  73. def test_two_children(self):
  74. lst = []
  75. def f():
  76. lst.append(1)
  77. greenlet.getcurrent().parent.switch()
  78. lst.extend([1, 1])
  79. g = RawGreenlet(f)
  80. h = RawGreenlet(f)
  81. g.switch()
  82. self.assertEqual(len(lst), 1)
  83. h.switch()
  84. self.assertEqual(len(lst), 2)
  85. h.switch()
  86. self.assertEqual(len(lst), 4)
  87. self.assertEqual(h.dead, True)
  88. g.switch()
  89. self.assertEqual(len(lst), 6)
  90. self.assertEqual(g.dead, True)
  91. def test_two_recursive_children(self):
  92. lst = []
  93. def f():
  94. lst.append('b')
  95. greenlet.getcurrent().parent.switch()
  96. def g():
  97. lst.append('a')
  98. g = RawGreenlet(f)
  99. g.switch()
  100. lst.append('c')
  101. g = RawGreenlet(g)
  102. self.assertEqual(sys.getrefcount(g), 2)
  103. g.switch()
  104. self.assertEqual(lst, ['a', 'b', 'c'])
  105. # Just the one in this frame, plus the one on the stack we pass to the function
  106. self.assertEqual(sys.getrefcount(g), 2)
  107. def test_threads(self):
  108. success = []
  109. def f():
  110. self._do_simple_test()
  111. success.append(True)
  112. ths = [threading.Thread(target=f) for i in range(10)]
  113. for th in ths:
  114. th.start()
  115. for th in ths:
  116. th.join(10)
  117. self.assertEqual(len(success), len(ths))
  118. def test_exception(self):
  119. seen = []
  120. g1 = RawGreenlet(fmain)
  121. g2 = RawGreenlet(fmain)
  122. g1.switch(seen)
  123. g2.switch(seen)
  124. g2.parent = g1
  125. self.assertEqual(seen, [])
  126. #with self.assertRaises(SomeError):
  127. # p("***Switching back")
  128. # g2.switch()
  129. # Creating this as a bound method can reveal bugs that
  130. # are hidden on newer versions of Python that avoid creating
  131. # bound methods for direct expressions; IOW, don't use the `with`
  132. # form!
  133. self.assertRaises(SomeError, g2.switch)
  134. self.assertEqual(seen, [SomeError])
  135. value = g2.switch()
  136. self.assertEqual(value, ())
  137. self.assertEqual(seen, [SomeError])
  138. value = g2.switch(25)
  139. self.assertEqual(value, 25)
  140. self.assertEqual(seen, [SomeError])
  141. def test_send_exception(self):
  142. seen = []
  143. g1 = RawGreenlet(fmain)
  144. g1.switch(seen)
  145. self.assertRaises(KeyError, send_exception, g1, KeyError)
  146. self.assertEqual(seen, [KeyError])
  147. def test_dealloc(self):
  148. seen = []
  149. g1 = RawGreenlet(fmain)
  150. g2 = RawGreenlet(fmain)
  151. g1.switch(seen)
  152. g2.switch(seen)
  153. self.assertEqual(seen, [])
  154. del g1
  155. gc.collect()
  156. self.assertEqual(seen, [greenlet.GreenletExit])
  157. del g2
  158. gc.collect()
  159. self.assertEqual(seen, [greenlet.GreenletExit, greenlet.GreenletExit])
  160. def test_dealloc_catches_GreenletExit_throws_other(self):
  161. def run():
  162. try:
  163. greenlet.getcurrent().parent.switch()
  164. except greenlet.GreenletExit:
  165. raise SomeError from None
  166. g = RawGreenlet(run)
  167. g.switch()
  168. # Destroying the only reference to the greenlet causes it
  169. # to get GreenletExit; when it in turn raises, even though we're the parent
  170. # we don't get the exception, it just gets printed.
  171. # When we run on 3.8 only, we can use sys.unraisablehook
  172. oldstderr = sys.stderr
  173. from io import StringIO
  174. stderr = sys.stderr = StringIO()
  175. try:
  176. del g
  177. finally:
  178. sys.stderr = oldstderr
  179. v = stderr.getvalue()
  180. self.assertIn("Exception", v)
  181. self.assertIn('ignored', v)
  182. self.assertIn("SomeError", v)
  183. @unittest.skipIf(
  184. PY313 and RUNNING_ON_MANYLINUX,
  185. "Sometimes flaky (getting one GreenletExit in the second list)"
  186. # Probably due to funky timing interactions?
  187. # TODO: FIXME Make that work.
  188. )
  189. def test_dealloc_other_thread(self):
  190. seen = []
  191. someref = []
  192. bg_glet_created_running_and_no_longer_ref_in_bg = threading.Event()
  193. fg_ref_released = threading.Event()
  194. bg_should_be_clear = threading.Event()
  195. ok_to_exit_bg_thread = threading.Event()
  196. def f():
  197. g1 = RawGreenlet(fmain)
  198. g1.switch(seen)
  199. someref.append(g1)
  200. del g1
  201. gc.collect()
  202. bg_glet_created_running_and_no_longer_ref_in_bg.set()
  203. fg_ref_released.wait(3)
  204. RawGreenlet() # trigger release
  205. bg_should_be_clear.set()
  206. ok_to_exit_bg_thread.wait(3)
  207. RawGreenlet() # One more time
  208. t = threading.Thread(target=f)
  209. t.start()
  210. bg_glet_created_running_and_no_longer_ref_in_bg.wait(10)
  211. self.assertEqual(seen, [])
  212. self.assertEqual(len(someref), 1)
  213. del someref[:]
  214. gc.collect()
  215. # g1 is not released immediately because it's from another thread
  216. self.assertEqual(seen, [])
  217. fg_ref_released.set()
  218. bg_should_be_clear.wait(3)
  219. try:
  220. self.assertEqual(seen, [greenlet.GreenletExit])
  221. finally:
  222. ok_to_exit_bg_thread.set()
  223. t.join(10)
  224. del seen[:]
  225. del someref[:]
  226. def test_frame(self):
  227. def f1():
  228. f = sys._getframe(0) # pylint:disable=protected-access
  229. self.assertEqual(f.f_back, None)
  230. greenlet.getcurrent().parent.switch(f)
  231. return "meaning of life"
  232. g = RawGreenlet(f1)
  233. frame = g.switch()
  234. self.assertTrue(frame is g.gr_frame)
  235. self.assertTrue(g)
  236. from_g = g.switch()
  237. self.assertFalse(g)
  238. self.assertEqual(from_g, 'meaning of life')
  239. self.assertEqual(g.gr_frame, None)
  240. def test_thread_bug(self):
  241. def runner(x):
  242. g = RawGreenlet(lambda: time.sleep(x))
  243. g.switch()
  244. t1 = threading.Thread(target=runner, args=(0.2,))
  245. t2 = threading.Thread(target=runner, args=(0.3,))
  246. t1.start()
  247. t2.start()
  248. t1.join(10)
  249. t2.join(10)
  250. def test_switch_kwargs(self):
  251. def run(a, b):
  252. self.assertEqual(a, 4)
  253. self.assertEqual(b, 2)
  254. return 42
  255. x = RawGreenlet(run).switch(a=4, b=2)
  256. self.assertEqual(x, 42)
  257. def test_switch_kwargs_to_parent(self):
  258. def run(x):
  259. greenlet.getcurrent().parent.switch(x=x)
  260. greenlet.getcurrent().parent.switch(2, x=3)
  261. return x, x ** 2
  262. g = RawGreenlet(run)
  263. self.assertEqual({'x': 3}, g.switch(3))
  264. self.assertEqual(((2,), {'x': 3}), g.switch())
  265. self.assertEqual((3, 9), g.switch())
  266. def test_switch_to_another_thread(self):
  267. data = {}
  268. created_event = threading.Event()
  269. done_event = threading.Event()
  270. def run():
  271. data['g'] = RawGreenlet(lambda: None)
  272. created_event.set()
  273. done_event.wait(10)
  274. thread = threading.Thread(target=run)
  275. thread.start()
  276. created_event.wait(10)
  277. with self.assertRaises(greenlet.error):
  278. data['g'].switch()
  279. done_event.set()
  280. thread.join(10)
  281. # XXX: Should handle this automatically
  282. data.clear()
  283. def test_exc_state(self):
  284. def f():
  285. try:
  286. raise ValueError('fun')
  287. except: # pylint:disable=bare-except
  288. exc_info = sys.exc_info()
  289. RawGreenlet(h).switch()
  290. self.assertEqual(exc_info, sys.exc_info())
  291. def h():
  292. self.assertEqual(sys.exc_info(), (None, None, None))
  293. RawGreenlet(f).switch()
  294. def test_instance_dict(self):
  295. def f():
  296. greenlet.getcurrent().test = 42
  297. def deldict(g):
  298. del g.__dict__
  299. def setdict(g, value):
  300. g.__dict__ = value
  301. g = RawGreenlet(f)
  302. self.assertEqual(g.__dict__, {})
  303. g.switch()
  304. self.assertEqual(g.test, 42)
  305. self.assertEqual(g.__dict__, {'test': 42})
  306. g.__dict__ = g.__dict__
  307. self.assertEqual(g.__dict__, {'test': 42})
  308. self.assertRaises(TypeError, deldict, g)
  309. self.assertRaises(TypeError, setdict, g, 42)
  310. def test_running_greenlet_has_no_run(self):
  311. has_run = []
  312. def func():
  313. has_run.append(
  314. hasattr(greenlet.getcurrent(), 'run')
  315. )
  316. g = RawGreenlet(func)
  317. g.switch()
  318. self.assertEqual(has_run, [False])
  319. def test_deepcopy(self):
  320. import copy
  321. self.assertRaises(TypeError, copy.copy, RawGreenlet())
  322. self.assertRaises(TypeError, copy.deepcopy, RawGreenlet())
  323. def test_parent_restored_on_kill(self):
  324. hub = RawGreenlet(lambda: None)
  325. main = greenlet.getcurrent()
  326. result = []
  327. def worker():
  328. try:
  329. # Wait to be killed by going back to the test.
  330. main.switch()
  331. except greenlet.GreenletExit:
  332. # Resurrect and switch to parent
  333. result.append(greenlet.getcurrent().parent)
  334. result.append(greenlet.getcurrent())
  335. hub.switch()
  336. g = RawGreenlet(worker, parent=hub)
  337. g.switch()
  338. # delete the only reference, thereby raising GreenletExit
  339. del g
  340. self.assertTrue(result)
  341. self.assertIs(result[0], main)
  342. self.assertIs(result[1].parent, hub)
  343. # Delete them, thereby breaking the cycle between the greenlet
  344. # and the frame, which otherwise would never be collectable
  345. # XXX: We should be able to automatically fix this.
  346. del result[:]
  347. hub = None
  348. main = None
  349. def test_parent_return_failure(self):
  350. # No run causes AttributeError on switch
  351. g1 = RawGreenlet()
  352. # Greenlet that implicitly switches to parent
  353. g2 = RawGreenlet(lambda: None, parent=g1)
  354. # AttributeError should propagate to us, no fatal errors
  355. with self.assertRaises(AttributeError):
  356. g2.switch()
  357. def test_throw_exception_not_lost(self):
  358. class mygreenlet(RawGreenlet):
  359. def __getattribute__(self, name):
  360. try:
  361. raise Exception # pylint:disable=broad-exception-raised
  362. except: # pylint:disable=bare-except
  363. pass
  364. return RawGreenlet.__getattribute__(self, name)
  365. g = mygreenlet(lambda: None)
  366. self.assertRaises(SomeError, g.throw, SomeError())
  367. @fails_leakcheck
  368. def _do_test_throw_to_dead_thread_doesnt_crash(self, wait_for_cleanup=False):
  369. result = []
  370. def worker():
  371. greenlet.getcurrent().parent.switch()
  372. def creator():
  373. g = RawGreenlet(worker)
  374. g.switch()
  375. result.append(g)
  376. if wait_for_cleanup:
  377. # Let this greenlet eventually be cleaned up.
  378. g.switch()
  379. greenlet.getcurrent()
  380. t = threading.Thread(target=creator)
  381. t.start()
  382. t.join(10)
  383. del t
  384. # But, depending on the operating system, the thread
  385. # deallocator may not actually have run yet! So we can't be
  386. # sure about the error message unless we wait.
  387. if wait_for_cleanup:
  388. self.wait_for_pending_cleanups()
  389. with self.assertRaises(greenlet.error) as exc:
  390. result[0].throw(SomeError)
  391. if not wait_for_cleanup:
  392. s = str(exc.exception)
  393. self.assertTrue(
  394. s == "cannot switch to a different thread (which happens to have exited)"
  395. or 'Cannot switch' in s
  396. )
  397. else:
  398. self.assertEqual(
  399. str(exc.exception),
  400. "cannot switch to a different thread (which happens to have exited)",
  401. )
  402. if hasattr(result[0].gr_frame, 'clear'):
  403. # The frame is actually executing (it thinks), we can't clear it.
  404. with self.assertRaises(RuntimeError):
  405. result[0].gr_frame.clear()
  406. # Unfortunately, this doesn't actually clear the references, they're in the
  407. # fast local array.
  408. if not wait_for_cleanup:
  409. # f_locals has no clear method in Python 3.13
  410. if hasattr(result[0].gr_frame.f_locals, 'clear'):
  411. result[0].gr_frame.f_locals.clear()
  412. else:
  413. self.assertIsNone(result[0].gr_frame)
  414. del creator
  415. worker = None
  416. del result[:]
  417. # XXX: we ought to be able to automatically fix this.
  418. # See issue 252
  419. self.expect_greenlet_leak = True # direct us not to wait for it to go away
  420. @fails_leakcheck
  421. def test_throw_to_dead_thread_doesnt_crash(self):
  422. self._do_test_throw_to_dead_thread_doesnt_crash()
  423. def test_throw_to_dead_thread_doesnt_crash_wait(self):
  424. self._do_test_throw_to_dead_thread_doesnt_crash(True)
  425. @fails_leakcheck
  426. def test_recursive_startup(self):
  427. class convoluted(RawGreenlet):
  428. def __init__(self):
  429. RawGreenlet.__init__(self)
  430. self.count = 0
  431. def __getattribute__(self, name):
  432. if name == 'run' and self.count == 0:
  433. self.count = 1
  434. self.switch(43)
  435. return RawGreenlet.__getattribute__(self, name)
  436. def run(self, value):
  437. while True:
  438. self.parent.switch(value)
  439. g = convoluted()
  440. self.assertEqual(g.switch(42), 43)
  441. # Exits the running greenlet, otherwise it leaks
  442. # XXX: We should be able to automatically fix this
  443. #g.throw(greenlet.GreenletExit)
  444. #del g
  445. self.expect_greenlet_leak = True
  446. def test_threaded_updatecurrent(self):
  447. # released when main thread should execute
  448. lock1 = threading.Lock()
  449. lock1.acquire()
  450. # released when another thread should execute
  451. lock2 = threading.Lock()
  452. lock2.acquire()
  453. class finalized(object):
  454. def __del__(self):
  455. # happens while in green_updatecurrent() in main greenlet
  456. # should be very careful not to accidentally call it again
  457. # at the same time we must make sure another thread executes
  458. lock2.release()
  459. lock1.acquire()
  460. # now ts_current belongs to another thread
  461. def deallocator():
  462. greenlet.getcurrent().parent.switch()
  463. def fthread():
  464. lock2.acquire()
  465. greenlet.getcurrent()
  466. del g[0]
  467. lock1.release()
  468. lock2.acquire()
  469. greenlet.getcurrent()
  470. lock1.release()
  471. main = greenlet.getcurrent()
  472. g = [RawGreenlet(deallocator)]
  473. g[0].bomb = finalized()
  474. g[0].switch()
  475. t = threading.Thread(target=fthread)
  476. t.start()
  477. # let another thread grab ts_current and deallocate g[0]
  478. lock2.release()
  479. lock1.acquire()
  480. # this is the corner stone
  481. # getcurrent() will notice that ts_current belongs to another thread
  482. # and start the update process, which would notice that g[0] should
  483. # be deallocated, and that will execute an object's finalizer. Now,
  484. # that object will let another thread run so it can grab ts_current
  485. # again, which would likely crash the interpreter if there's no
  486. # check for this case at the end of green_updatecurrent(). This test
  487. # passes if getcurrent() returns correct result, but it's likely
  488. # to randomly crash if it's not anyway.
  489. self.assertEqual(greenlet.getcurrent(), main)
  490. # wait for another thread to complete, just in case
  491. t.join(10)
  492. def test_dealloc_switch_args_not_lost(self):
  493. seen = []
  494. def worker():
  495. # wait for the value
  496. value = greenlet.getcurrent().parent.switch()
  497. # delete all references to ourself
  498. del worker[0]
  499. initiator.parent = greenlet.getcurrent().parent
  500. # switch to main with the value, but because
  501. # ts_current is the last reference to us we
  502. # return here immediately, where we resurrect ourself.
  503. try:
  504. greenlet.getcurrent().parent.switch(value)
  505. finally:
  506. seen.append(greenlet.getcurrent())
  507. def initiator():
  508. return 42 # implicitly falls thru to parent
  509. worker = [RawGreenlet(worker)]
  510. worker[0].switch() # prime worker
  511. initiator = RawGreenlet(initiator, worker[0])
  512. value = initiator.switch()
  513. self.assertTrue(seen)
  514. self.assertEqual(value, 42)
  515. def test_tuple_subclass(self):
  516. # The point of this test is to see what happens when a custom
  517. # tuple subclass is used as an object passed directly to the C
  518. # function ``green_switch``; part of ``green_switch`` checks
  519. # the ``len()`` of the ``args`` tuple, and that can call back
  520. # into Python. Here, when it calls back into Python, we
  521. # recursively enter ``green_switch`` again.
  522. # This test is really only relevant on Python 2. The builtin
  523. # `apply` function directly passes the given args tuple object
  524. # to the underlying function, whereas the Python 3 version
  525. # unpacks and repacks into an actual tuple. This could still
  526. # happen using the C API on Python 3 though. We should write a
  527. # builtin version of apply() ourself.
  528. def _apply(func, a, k):
  529. func(*a, **k)
  530. class mytuple(tuple):
  531. def __len__(self):
  532. greenlet.getcurrent().switch()
  533. return tuple.__len__(self)
  534. args = mytuple()
  535. kwargs = dict(a=42)
  536. def switchapply():
  537. _apply(greenlet.getcurrent().parent.switch, args, kwargs)
  538. g = RawGreenlet(switchapply)
  539. self.assertEqual(g.switch(), kwargs)
  540. def test_abstract_subclasses(self):
  541. AbstractSubclass = ABCMeta(
  542. 'AbstractSubclass',
  543. (RawGreenlet,),
  544. {'run': abstractmethod(lambda self: None)})
  545. class BadSubclass(AbstractSubclass):
  546. pass
  547. class GoodSubclass(AbstractSubclass):
  548. def run(self):
  549. pass
  550. GoodSubclass() # should not raise
  551. self.assertRaises(TypeError, BadSubclass)
  552. def test_implicit_parent_with_threads(self):
  553. if not gc.isenabled():
  554. return # cannot test with disabled gc
  555. N = gc.get_threshold()[0]
  556. if N < 50:
  557. return # cannot test with such a small N
  558. def attempt():
  559. lock1 = threading.Lock()
  560. lock1.acquire()
  561. lock2 = threading.Lock()
  562. lock2.acquire()
  563. recycled = [False]
  564. def another_thread():
  565. lock1.acquire() # wait for gc
  566. greenlet.getcurrent() # update ts_current
  567. lock2.release() # release gc
  568. t = threading.Thread(target=another_thread)
  569. t.start()
  570. class gc_callback(object):
  571. def __del__(self):
  572. lock1.release()
  573. lock2.acquire()
  574. recycled[0] = True
  575. class garbage(object):
  576. def __init__(self):
  577. self.cycle = self
  578. self.callback = gc_callback()
  579. l = []
  580. x = range(N*2)
  581. current = greenlet.getcurrent()
  582. g = garbage()
  583. for _ in x:
  584. g = None # lose reference to garbage
  585. if recycled[0]:
  586. # gc callback called prematurely
  587. t.join(10)
  588. return False
  589. last = RawGreenlet()
  590. if recycled[0]:
  591. break # yes! gc called in green_new
  592. l.append(last) # increase allocation counter
  593. else:
  594. # gc callback not called when expected
  595. gc.collect()
  596. if recycled[0]:
  597. t.join(10)
  598. return False
  599. self.assertEqual(last.parent, current)
  600. for g in l:
  601. self.assertEqual(g.parent, current)
  602. return True
  603. for _ in range(5):
  604. if attempt():
  605. break
  606. def test_issue_245_reference_counting_subclass_no_threads(self):
  607. # https://github.com/python-greenlet/greenlet/issues/245
  608. # Before the fix, this crashed pretty reliably on
  609. # Python 3.10, at least on macOS; but much less reliably on other
  610. # interpreters (memory layout must have changed).
  611. # The threaded test crashed more reliably on more interpreters.
  612. from greenlet import getcurrent
  613. from greenlet import GreenletExit
  614. class Greenlet(RawGreenlet):
  615. pass
  616. initial_refs = sys.getrefcount(Greenlet)
  617. # This has to be an instance variable because
  618. # Python 2 raises a SyntaxError if we delete a local
  619. # variable referenced in an inner scope.
  620. self.glets = [] # pylint:disable=attribute-defined-outside-init
  621. def greenlet_main():
  622. try:
  623. getcurrent().parent.switch()
  624. except GreenletExit:
  625. self.glets.append(getcurrent())
  626. # Before the
  627. for _ in range(10):
  628. Greenlet(greenlet_main).switch()
  629. del self.glets
  630. self.assertEqual(sys.getrefcount(Greenlet), initial_refs)
  631. @unittest.skipIf(
  632. PY313 and RUNNING_ON_MANYLINUX,
  633. "The manylinux images appear to hang on this test on 3.13rc2"
  634. # Or perhaps I just got tired of waiting for the 450s timeout.
  635. # Still, it shouldn't take anywhere near that long. Does not reproduce in
  636. # Ubuntu images, on macOS or Windows.
  637. )
  638. def test_issue_245_reference_counting_subclass_threads(self):
  639. # https://github.com/python-greenlet/greenlet/issues/245
  640. from threading import Thread
  641. from threading import Event
  642. from greenlet import getcurrent
  643. class MyGreenlet(RawGreenlet):
  644. pass
  645. glets = []
  646. ref_cleared = Event()
  647. def greenlet_main():
  648. getcurrent().parent.switch()
  649. def thread_main(greenlet_running_event):
  650. mine = MyGreenlet(greenlet_main)
  651. glets.append(mine)
  652. # The greenlets being deleted must be active
  653. mine.switch()
  654. # Don't keep any reference to it in this thread
  655. del mine
  656. # Let main know we published our greenlet.
  657. greenlet_running_event.set()
  658. # Wait for main to let us know the references are
  659. # gone and the greenlet objects no longer reachable
  660. ref_cleared.wait(10)
  661. # The creating thread must call getcurrent() (or a few other
  662. # greenlet APIs) because that's when the thread-local list of dead
  663. # greenlets gets cleared.
  664. getcurrent()
  665. # We start with 3 references to the subclass:
  666. # - This module
  667. # - Its __mro__
  668. # - The __subclassess__ attribute of greenlet
  669. # - (If we call gc.get_referents(), we find four entries, including
  670. # some other tuple ``(greenlet)`` that I'm not sure about but must be part
  671. # of the machinery.)
  672. #
  673. # On Python 3.10 it's often enough to just run 3 threads; on Python 2.7,
  674. # more threads are needed, and the results are still
  675. # non-deterministic. Presumably the memory layouts are different
  676. initial_refs = sys.getrefcount(MyGreenlet)
  677. thread_ready_events = []
  678. for _ in range(
  679. initial_refs + 45
  680. ):
  681. event = Event()
  682. thread = Thread(target=thread_main, args=(event,))
  683. thread_ready_events.append(event)
  684. thread.start()
  685. for done_event in thread_ready_events:
  686. done_event.wait(10)
  687. del glets[:]
  688. ref_cleared.set()
  689. # Let any other thread run; it will crash the interpreter
  690. # if not fixed (or silently corrupt memory and we possibly crash
  691. # later).
  692. self.wait_for_pending_cleanups()
  693. self.assertEqual(sys.getrefcount(MyGreenlet), initial_refs)
  694. def test_falling_off_end_switches_to_unstarted_parent_raises_error(self):
  695. def no_args():
  696. return 13
  697. parent_never_started = RawGreenlet(no_args)
  698. def leaf():
  699. return 42
  700. child = RawGreenlet(leaf, parent_never_started)
  701. # Because the run function takes to arguments
  702. with self.assertRaises(TypeError):
  703. child.switch()
  704. def test_falling_off_end_switches_to_unstarted_parent_works(self):
  705. def one_arg(x):
  706. return (x, 24)
  707. parent_never_started = RawGreenlet(one_arg)
  708. def leaf():
  709. return 42
  710. child = RawGreenlet(leaf, parent_never_started)
  711. result = child.switch()
  712. self.assertEqual(result, (42, 24))
  713. def test_switch_to_dead_greenlet_with_unstarted_perverse_parent(self):
  714. class Parent(RawGreenlet):
  715. def __getattribute__(self, name):
  716. if name == 'run':
  717. raise SomeError
  718. parent_never_started = Parent()
  719. seen = []
  720. child = RawGreenlet(lambda: seen.append(42), parent_never_started)
  721. # Because we automatically start the parent when the child is
  722. # finished
  723. with self.assertRaises(SomeError):
  724. child.switch()
  725. self.assertEqual(seen, [42])
  726. with self.assertRaises(SomeError):
  727. child.switch()
  728. self.assertEqual(seen, [42])
  729. def test_switch_to_dead_greenlet_reparent(self):
  730. seen = []
  731. parent_never_started = RawGreenlet(lambda: seen.append(24))
  732. child = RawGreenlet(lambda: seen.append(42))
  733. child.switch()
  734. self.assertEqual(seen, [42])
  735. child.parent = parent_never_started
  736. # This actually is the same as switching to the parent.
  737. result = child.switch()
  738. self.assertIsNone(result)
  739. self.assertEqual(seen, [42, 24])
  740. def test_can_access_f_back_of_suspended_greenlet(self):
  741. # This tests our frame rewriting to work around Python 3.12+ having
  742. # some interpreter frames on the C stack. It will crash in the absence
  743. # of that logic.
  744. main = greenlet.getcurrent()
  745. def outer():
  746. inner()
  747. def inner():
  748. main.switch(sys._getframe(0))
  749. hub = RawGreenlet(outer)
  750. # start it
  751. hub.switch()
  752. # start another greenlet to make sure we aren't relying on
  753. # anything in `hub` still being on the C stack
  754. unrelated = RawGreenlet(lambda: None)
  755. unrelated.switch()
  756. # now it is suspended
  757. self.assertIsNotNone(hub.gr_frame)
  758. self.assertEqual(hub.gr_frame.f_code.co_name, "inner")
  759. self.assertIsNotNone(hub.gr_frame.f_back)
  760. self.assertEqual(hub.gr_frame.f_back.f_code.co_name, "outer")
  761. # The next line is what would crash
  762. self.assertIsNone(hub.gr_frame.f_back.f_back)
  763. def test_get_stack_with_nested_c_calls(self):
  764. from functools import partial
  765. from . import _test_extension_cpp
  766. def recurse(v):
  767. if v > 0:
  768. return v * _test_extension_cpp.test_call(partial(recurse, v - 1))
  769. return greenlet.getcurrent().parent.switch()
  770. gr = RawGreenlet(recurse)
  771. gr.switch(5)
  772. frame = gr.gr_frame
  773. for i in range(5):
  774. self.assertEqual(frame.f_locals["v"], i)
  775. frame = frame.f_back
  776. self.assertEqual(frame.f_locals["v"], 5)
  777. self.assertIsNone(frame.f_back)
  778. self.assertEqual(gr.switch(10), 1200) # 1200 = 5! * 10
  779. def test_frames_always_exposed(self):
  780. # On Python 3.12 this will crash if we don't set the
  781. # gr_frames_always_exposed attribute. More background:
  782. # https://github.com/python-greenlet/greenlet/issues/388
  783. main = greenlet.getcurrent()
  784. def outer():
  785. inner(sys._getframe(0))
  786. def inner(frame):
  787. main.switch(frame)
  788. gr = RawGreenlet(outer)
  789. frame = gr.switch()
  790. # Do something else to clobber the part of the C stack used by `gr`,
  791. # so we can't skate by on "it just happened to still be there"
  792. unrelated = RawGreenlet(lambda: None)
  793. unrelated.switch()
  794. self.assertEqual(frame.f_code.co_name, "outer")
  795. # The next line crashes on 3.12 if we haven't exposed the frames.
  796. self.assertIsNone(frame.f_back)
  797. class TestGreenletSetParentErrors(TestCase):
  798. def test_threaded_reparent(self):
  799. data = {}
  800. created_event = threading.Event()
  801. done_event = threading.Event()
  802. def run():
  803. data['g'] = RawGreenlet(lambda: None)
  804. created_event.set()
  805. done_event.wait(10)
  806. def blank():
  807. greenlet.getcurrent().parent.switch()
  808. thread = threading.Thread(target=run)
  809. thread.start()
  810. created_event.wait(10)
  811. g = RawGreenlet(blank)
  812. g.switch()
  813. with self.assertRaises(ValueError) as exc:
  814. g.parent = data['g']
  815. done_event.set()
  816. thread.join(10)
  817. self.assertEqual(str(exc.exception), "parent cannot be on a different thread")
  818. def test_unexpected_reparenting(self):
  819. another = []
  820. def worker():
  821. g = RawGreenlet(lambda: None)
  822. another.append(g)
  823. g.switch()
  824. t = threading.Thread(target=worker)
  825. t.start()
  826. t.join(10)
  827. # The first time we switch (running g_initialstub(), which is
  828. # when we look up the run attribute) we attempt to change the
  829. # parent to one from another thread (which also happens to be
  830. # dead). ``g_initialstub()`` should detect this and raise a
  831. # greenlet error.
  832. #
  833. # EXCEPT: With the fix for #252, this is actually detected
  834. # sooner, when setting the parent itself. Prior to that fix,
  835. # the main greenlet from the background thread kept a valid
  836. # value for ``run_info``, and appeared to be a valid parent
  837. # until we actually started the greenlet. But now that it's
  838. # cleared, this test is catching whether ``green_setparent``
  839. # can detect the dead thread.
  840. #
  841. # Further refactoring once again changes this back to a greenlet.error
  842. #
  843. # We need to wait for the cleanup to happen, but we're
  844. # deliberately leaking a main greenlet here.
  845. self.wait_for_pending_cleanups(initial_main_greenlets=self.main_greenlets_before_test + 1)
  846. class convoluted(RawGreenlet):
  847. def __getattribute__(self, name):
  848. if name == 'run':
  849. self.parent = another[0] # pylint:disable=attribute-defined-outside-init
  850. return RawGreenlet.__getattribute__(self, name)
  851. g = convoluted(lambda: None)
  852. with self.assertRaises(greenlet.error) as exc:
  853. g.switch()
  854. self.assertEqual(str(exc.exception),
  855. "cannot switch to a different thread (which happens to have exited)")
  856. del another[:]
  857. def test_unexpected_reparenting_thread_running(self):
  858. # Like ``test_unexpected_reparenting``, except the background thread is
  859. # actually still alive.
  860. another = []
  861. switched_to_greenlet = threading.Event()
  862. keep_main_alive = threading.Event()
  863. def worker():
  864. g = RawGreenlet(lambda: None)
  865. another.append(g)
  866. g.switch()
  867. switched_to_greenlet.set()
  868. keep_main_alive.wait(10)
  869. class convoluted(RawGreenlet):
  870. def __getattribute__(self, name):
  871. if name == 'run':
  872. self.parent = another[0] # pylint:disable=attribute-defined-outside-init
  873. return RawGreenlet.__getattribute__(self, name)
  874. t = threading.Thread(target=worker)
  875. t.start()
  876. switched_to_greenlet.wait(10)
  877. try:
  878. g = convoluted(lambda: None)
  879. with self.assertRaises(greenlet.error) as exc:
  880. g.switch()
  881. self.assertIn("Cannot switch to a different thread", str(exc.exception))
  882. self.assertIn("Expected", str(exc.exception))
  883. self.assertIn("Current", str(exc.exception))
  884. finally:
  885. keep_main_alive.set()
  886. t.join(10)
  887. # XXX: Should handle this automatically.
  888. del another[:]
  889. def test_cannot_delete_parent(self):
  890. worker = RawGreenlet(lambda: None)
  891. self.assertIs(worker.parent, greenlet.getcurrent())
  892. with self.assertRaises(AttributeError) as exc:
  893. del worker.parent
  894. self.assertEqual(str(exc.exception), "can't delete attribute")
  895. def test_cannot_delete_parent_of_main(self):
  896. with self.assertRaises(AttributeError) as exc:
  897. del greenlet.getcurrent().parent
  898. self.assertEqual(str(exc.exception), "can't delete attribute")
  899. def test_main_greenlet_parent_is_none(self):
  900. # assuming we're in a main greenlet here.
  901. self.assertIsNone(greenlet.getcurrent().parent)
  902. def test_set_parent_wrong_types(self):
  903. def bg():
  904. # Go back to main.
  905. greenlet.getcurrent().parent.switch()
  906. def check(glet):
  907. for p in None, 1, self, "42":
  908. with self.assertRaises(TypeError) as exc:
  909. glet.parent = p
  910. self.assertEqual(
  911. str(exc.exception),
  912. "GreenletChecker: Expected any type of greenlet, not " + type(p).__name__)
  913. # First, not running
  914. g = RawGreenlet(bg)
  915. self.assertFalse(g)
  916. check(g)
  917. # Then when running.
  918. g.switch()
  919. self.assertTrue(g)
  920. check(g)
  921. # Let it finish
  922. g.switch()
  923. def test_trivial_cycle(self):
  924. glet = RawGreenlet(lambda: None)
  925. with self.assertRaises(ValueError) as exc:
  926. glet.parent = glet
  927. self.assertEqual(str(exc.exception), "cyclic parent chain")
  928. def test_trivial_cycle_main(self):
  929. # This used to produce a ValueError, but we catch it earlier than that now.
  930. with self.assertRaises(AttributeError) as exc:
  931. greenlet.getcurrent().parent = greenlet.getcurrent()
  932. self.assertEqual(str(exc.exception), "cannot set the parent of a main greenlet")
  933. def test_deeper_cycle(self):
  934. g1 = RawGreenlet(lambda: None)
  935. g2 = RawGreenlet(lambda: None)
  936. g3 = RawGreenlet(lambda: None)
  937. g1.parent = g2
  938. g2.parent = g3
  939. with self.assertRaises(ValueError) as exc:
  940. g3.parent = g1
  941. self.assertEqual(str(exc.exception), "cyclic parent chain")
  942. class TestRepr(TestCase):
  943. def assertEndsWith(self, got, suffix):
  944. self.assertTrue(got.endswith(suffix), (got, suffix))
  945. def test_main_while_running(self):
  946. r = repr(greenlet.getcurrent())
  947. self.assertEndsWith(r, " current active started main>")
  948. def test_main_in_background(self):
  949. main = greenlet.getcurrent()
  950. def run():
  951. return repr(main)
  952. g = RawGreenlet(run)
  953. r = g.switch()
  954. self.assertEndsWith(r, ' suspended active started main>')
  955. def test_initial(self):
  956. r = repr(RawGreenlet())
  957. self.assertEndsWith(r, ' pending>')
  958. def test_main_from_other_thread(self):
  959. main = greenlet.getcurrent()
  960. class T(threading.Thread):
  961. original_main = thread_main = None
  962. main_glet = None
  963. def run(self):
  964. self.original_main = repr(main)
  965. self.main_glet = greenlet.getcurrent()
  966. self.thread_main = repr(self.main_glet)
  967. t = T()
  968. t.start()
  969. t.join(10)
  970. self.assertEndsWith(t.original_main, ' suspended active started main>')
  971. self.assertEndsWith(t.thread_main, ' current active started main>')
  972. # give the machinery time to notice the death of the thread,
  973. # and clean it up. Note that we don't use
  974. # ``expect_greenlet_leak`` or wait_for_pending_cleanups,
  975. # because at this point we know we have an extra greenlet
  976. # still reachable.
  977. for _ in range(3):
  978. time.sleep(0.001)
  979. # In the past, main greenlets, even from dead threads, never
  980. # really appear dead. We have fixed that, and we also report
  981. # that the thread is dead in the repr. (Do this multiple times
  982. # to make sure that we don't self-modify and forget our state
  983. # in the C++ code).
  984. for _ in range(3):
  985. self.assertTrue(t.main_glet.dead)
  986. r = repr(t.main_glet)
  987. self.assertEndsWith(r, ' (thread exited) dead>')
  988. def test_dead(self):
  989. g = RawGreenlet(lambda: None)
  990. g.switch()
  991. self.assertEndsWith(repr(g), ' dead>')
  992. self.assertNotIn('suspended', repr(g))
  993. self.assertNotIn('started', repr(g))
  994. self.assertNotIn('active', repr(g))
  995. def test_formatting_produces_native_str(self):
  996. # https://github.com/python-greenlet/greenlet/issues/218
  997. # %s formatting on Python 2 was producing unicode, not str.
  998. g_dead = RawGreenlet(lambda: None)
  999. g_not_started = RawGreenlet(lambda: None)
  1000. g_cur = greenlet.getcurrent()
  1001. for g in g_dead, g_not_started, g_cur:
  1002. self.assertIsInstance(
  1003. '%s' % (g,),
  1004. str
  1005. )
  1006. self.assertIsInstance(
  1007. '%r' % (g,),
  1008. str,
  1009. )
  1010. class TestMainGreenlet(TestCase):
  1011. # Tests some implementation details, and relies on some
  1012. # implementation details.
  1013. def _check_current_is_main(self):
  1014. # implementation detail
  1015. assert 'main' in repr(greenlet.getcurrent())
  1016. t = type(greenlet.getcurrent())
  1017. assert 'main' not in repr(t)
  1018. return t
  1019. def test_main_greenlet_type_can_be_subclassed(self):
  1020. main_type = self._check_current_is_main()
  1021. subclass = type('subclass', (main_type,), {})
  1022. self.assertIsNotNone(subclass)
  1023. def test_main_greenlet_is_greenlet(self):
  1024. self._check_current_is_main()
  1025. self.assertIsInstance(greenlet.getcurrent(), RawGreenlet)
  1026. class TestBrokenGreenlets(TestCase):
  1027. # Tests for things that used to, or still do, terminate the interpreter.
  1028. # This often means doing unsavory things.
  1029. def test_failed_to_initialstub(self):
  1030. def func():
  1031. raise AssertionError("Never get here")
  1032. g = greenlet._greenlet.UnswitchableGreenlet(func)
  1033. g.force_switch_error = True
  1034. with self.assertRaisesRegex(SystemError,
  1035. "Failed to switch stacks into a greenlet for the first time."):
  1036. g.switch()
  1037. def test_failed_to_switch_into_running(self):
  1038. runs = []
  1039. def func():
  1040. runs.append(1)
  1041. greenlet.getcurrent().parent.switch()
  1042. runs.append(2)
  1043. greenlet.getcurrent().parent.switch()
  1044. runs.append(3) # pragma: no cover
  1045. g = greenlet._greenlet.UnswitchableGreenlet(func)
  1046. g.switch()
  1047. self.assertEqual(runs, [1])
  1048. g.switch()
  1049. self.assertEqual(runs, [1, 2])
  1050. g.force_switch_error = True
  1051. with self.assertRaisesRegex(SystemError,
  1052. "Failed to switch stacks into a running greenlet."):
  1053. g.switch()
  1054. # If we stopped here, we would fail the leakcheck, because we've left
  1055. # the ``inner_bootstrap()`` C frame and its descendents hanging around,
  1056. # which have a bunch of Python references. They'll never get cleaned up
  1057. # if we don't let the greenlet finish.
  1058. g.force_switch_error = False
  1059. g.switch()
  1060. self.assertEqual(runs, [1, 2, 3])
  1061. def test_failed_to_slp_switch_into_running(self):
  1062. ex = self.assertScriptRaises('fail_slp_switch.py')
  1063. self.assertIn('fail_slp_switch is running', ex.output)
  1064. self.assertIn(ex.returncode, self.get_expected_returncodes_for_aborted_process())
  1065. def test_reentrant_switch_two_greenlets(self):
  1066. # Before we started capturing the arguments in g_switch_finish, this could crash.
  1067. output = self.run_script('fail_switch_two_greenlets.py')
  1068. self.assertIn('In g1_run', output)
  1069. self.assertIn('TRACE', output)
  1070. self.assertIn('LEAVE TRACE', output)
  1071. self.assertIn('Falling off end of main', output)
  1072. self.assertIn('Falling off end of g1_run', output)
  1073. self.assertIn('Falling off end of g2', output)
  1074. def test_reentrant_switch_three_greenlets(self):
  1075. # On debug builds of greenlet, this used to crash with an assertion error;
  1076. # on non-debug versions, it ran fine (which it should not do!).
  1077. # Now it always crashes correctly with a TypeError
  1078. ex = self.assertScriptRaises('fail_switch_three_greenlets.py', exitcodes=(1,))
  1079. self.assertIn('TypeError', ex.output)
  1080. self.assertIn('positional arguments', ex.output)
  1081. def test_reentrant_switch_three_greenlets2(self):
  1082. # This actually passed on debug and non-debug builds. It
  1083. # should probably have been triggering some debug assertions
  1084. # but it didn't.
  1085. #
  1086. # I think the fixes for the above test also kicked in here.
  1087. output = self.run_script('fail_switch_three_greenlets2.py')
  1088. self.assertIn(
  1089. "RESULTS: [('trace', 'switch'), "
  1090. "('trace', 'switch'), ('g2 arg', 'g2 from tracefunc'), "
  1091. "('trace', 'switch'), ('main g1', 'from g2_run'), ('trace', 'switch'), "
  1092. "('g1 arg', 'g1 from main'), ('trace', 'switch'), ('main g2', 'from g1_run'), "
  1093. "('trace', 'switch'), ('g1 from parent', 'g1 from main 2'), ('trace', 'switch'), "
  1094. "('main g1.2', 'g1 done'), ('trace', 'switch'), ('g2 from parent', ()), "
  1095. "('trace', 'switch'), ('main g2.2', 'g2 done')]",
  1096. output
  1097. )
  1098. def test_reentrant_switch_GreenletAlreadyStartedInPython(self):
  1099. output = self.run_script('fail_initialstub_already_started.py')
  1100. self.assertIn(
  1101. "RESULTS: ['Begin C', 'Switch to b from B.__getattribute__ in C', "
  1102. "('Begin B', ()), '_B_run switching to main', ('main from c', 'From B'), "
  1103. "'B.__getattribute__ back from main in C', ('Begin A', (None,)), "
  1104. "('A dead?', True, 'B dead?', True, 'C dead?', False), "
  1105. "'C done', ('main from c.2', None)]",
  1106. output
  1107. )
  1108. def test_reentrant_switch_run_callable_has_del(self):
  1109. output = self.run_script('fail_clearing_run_switches.py')
  1110. self.assertIn(
  1111. "RESULTS ["
  1112. "('G.__getattribute__', 'run'), ('RunCallable', '__del__'), "
  1113. "('main: g.switch()', 'from RunCallable'), ('run_func', 'enter')"
  1114. "]",
  1115. output
  1116. )
  1117. if __name__ == '__main__':
  1118. unittest.main()