test_extension_interface.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. from __future__ import print_function
  2. from __future__ import absolute_import
  3. import sys
  4. import unittest
  5. import greenlet
  6. from . import _test_extension
  7. class CAPITests(unittest.TestCase):
  8. def test_switch(self):
  9. self.assertEqual(
  10. 50, _test_extension.test_switch(greenlet.greenlet(lambda: 50)))
  11. def test_switch_kwargs(self):
  12. def foo(x, y):
  13. return x * y
  14. g = greenlet.greenlet(foo)
  15. self.assertEqual(6, _test_extension.test_switch_kwargs(g, x=3, y=2))
  16. def test_setparent(self):
  17. def foo():
  18. def bar():
  19. greenlet.getcurrent().parent.switch()
  20. # This final switch should go back to the main greenlet, since
  21. # the test_setparent() function in the C extension should have
  22. # reparented this greenlet.
  23. greenlet.getcurrent().parent.switch()
  24. raise AssertionError("Should never have reached this code")
  25. child = greenlet.greenlet(bar)
  26. child.switch()
  27. greenlet.getcurrent().parent.switch(child)
  28. greenlet.getcurrent().parent.throw(
  29. AssertionError("Should never reach this code"))
  30. foo_child = greenlet.greenlet(foo).switch()
  31. self.assertEqual(None, _test_extension.test_setparent(foo_child))
  32. def test_getcurrent(self):
  33. _test_extension.test_getcurrent()
  34. def test_new_greenlet(self):
  35. self.assertEqual(-15, _test_extension.test_new_greenlet(lambda: -15))
  36. def test_raise_greenlet_dead(self):
  37. self.assertRaises(
  38. greenlet.GreenletExit, _test_extension.test_raise_dead_greenlet)
  39. def test_raise_greenlet_error(self):
  40. self.assertRaises(
  41. greenlet.error, _test_extension.test_raise_greenlet_error)
  42. def test_throw(self):
  43. seen = []
  44. def foo():
  45. try:
  46. greenlet.getcurrent().parent.switch()
  47. except ValueError:
  48. seen.append(sys.exc_info()[1])
  49. except greenlet.GreenletExit:
  50. raise AssertionError
  51. g = greenlet.greenlet(foo)
  52. g.switch()
  53. _test_extension.test_throw(g)
  54. self.assertEqual(len(seen), 1)
  55. self.assertTrue(
  56. isinstance(seen[0], ValueError),
  57. "ValueError was not raised in foo()")
  58. self.assertEqual(
  59. str(seen[0]),
  60. 'take that sucka!',
  61. "message doesn't match")
  62. if __name__ == '__main__':
  63. unittest.main()