test_greenlet.py 47 KB

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