test_throw.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import sys
  2. import unittest
  3. from greenlet import greenlet
  4. def switch(*args):
  5. return greenlet.getcurrent().parent.switch(*args)
  6. class ThrowTests(unittest.TestCase):
  7. def test_class(self):
  8. def f():
  9. try:
  10. switch("ok")
  11. except RuntimeError:
  12. switch("ok")
  13. return
  14. switch("fail")
  15. g = greenlet(f)
  16. res = g.switch()
  17. self.assertEqual(res, "ok")
  18. res = g.throw(RuntimeError)
  19. self.assertEqual(res, "ok")
  20. def test_val(self):
  21. def f():
  22. try:
  23. switch("ok")
  24. except RuntimeError:
  25. val = sys.exc_info()[1]
  26. if str(val) == "ciao":
  27. switch("ok")
  28. return
  29. switch("fail")
  30. g = greenlet(f)
  31. res = g.switch()
  32. self.assertEqual(res, "ok")
  33. res = g.throw(RuntimeError("ciao"))
  34. self.assertEqual(res, "ok")
  35. g = greenlet(f)
  36. res = g.switch()
  37. self.assertEqual(res, "ok")
  38. res = g.throw(RuntimeError, "ciao")
  39. self.assertEqual(res, "ok")
  40. def test_kill(self):
  41. def f():
  42. switch("ok")
  43. switch("fail")
  44. g = greenlet(f)
  45. res = g.switch()
  46. self.assertEqual(res, "ok")
  47. res = g.throw()
  48. self.assertTrue(isinstance(res, greenlet.GreenletExit))
  49. self.assertTrue(g.dead)
  50. res = g.throw() # immediately eaten by the already-dead greenlet
  51. self.assertTrue(isinstance(res, greenlet.GreenletExit))
  52. def test_throw_goes_to_original_parent(self):
  53. main = greenlet.getcurrent()
  54. def f1():
  55. try:
  56. main.switch("f1 ready to catch")
  57. except IndexError:
  58. return "caught"
  59. else:
  60. return "normal exit"
  61. def f2():
  62. main.switch("from f2")
  63. g1 = greenlet(f1)
  64. g2 = greenlet(f2, parent=g1)
  65. self.assertRaises(IndexError, g2.throw, IndexError)
  66. self.assertTrue(g2.dead)
  67. self.assertTrue(g1.dead)
  68. g1 = greenlet(f1)
  69. g2 = greenlet(f2, parent=g1)
  70. res = g1.switch()
  71. self.assertEqual(res, "f1 ready to catch")
  72. res = g2.throw(IndexError)
  73. self.assertEqual(res, "caught")
  74. self.assertTrue(g2.dead)
  75. self.assertTrue(g1.dead)
  76. g1 = greenlet(f1)
  77. g2 = greenlet(f2, parent=g1)
  78. res = g1.switch()
  79. self.assertEqual(res, "f1 ready to catch")
  80. res = g2.switch()
  81. self.assertEqual(res, "from f2")
  82. res = g2.throw(IndexError)
  83. self.assertEqual(res, "caught")
  84. self.assertTrue(g2.dead)
  85. self.assertTrue(g1.dead)