2015-10-20 21:18:58 +00:00
|
|
|
import unittest
|
|
|
|
from ucontextlib import contextmanager
|
|
|
|
|
|
|
|
|
|
|
|
class ContextManagerTestCase(unittest.TestCase):
|
|
|
|
def setUp(self):
|
|
|
|
self._history = []
|
|
|
|
|
|
|
|
@contextmanager
|
|
|
|
def manager(x):
|
2021-05-27 05:50:04 +00:00
|
|
|
self._history.append("start")
|
2015-10-20 21:18:58 +00:00
|
|
|
try:
|
|
|
|
yield x
|
|
|
|
finally:
|
2021-05-27 05:50:04 +00:00
|
|
|
self._history.append("finish")
|
2015-10-20 21:18:58 +00:00
|
|
|
|
|
|
|
self._manager = manager
|
|
|
|
|
|
|
|
def test_context_manager(self):
|
|
|
|
with self._manager(123) as x:
|
|
|
|
self.assertEqual(x, 123)
|
2021-05-27 05:50:04 +00:00
|
|
|
self.assertEqual(self._history, ["start", "finish"])
|
2015-10-20 21:18:58 +00:00
|
|
|
|
|
|
|
def test_context_manager_on_error(self):
|
|
|
|
exc = Exception()
|
|
|
|
try:
|
2024-05-14 05:05:35 +00:00
|
|
|
with self._manager(123):
|
2015-10-20 21:18:58 +00:00
|
|
|
raise exc
|
|
|
|
except Exception as e:
|
|
|
|
self.assertEqual(exc, e)
|
2021-05-27 05:50:04 +00:00
|
|
|
self.assertEqual(self._history, ["start", "finish"])
|
2015-10-20 21:18:58 +00:00
|
|
|
|
|
|
|
|
2021-05-27 05:50:04 +00:00
|
|
|
if __name__ == "__main__":
|
2015-10-20 21:18:58 +00:00
|
|
|
unittest.main()
|