PageRenderTime 42ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/edk2/AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_contextlib.py

https://gitlab.com/envieidoc/Clover
Python | 326 lines | 284 code | 35 blank | 7 comment | 49 complexity | 9011846542dcdf71970c35efc0779a03 MD5 | raw file
  1. """Unit tests for contextlib.py, and other context managers."""
  2. import sys
  3. import tempfile
  4. import unittest
  5. from contextlib import * # Tests __all__
  6. from test import test_support
  7. try:
  8. import threading
  9. except ImportError:
  10. threading = None
  11. class ContextManagerTestCase(unittest.TestCase):
  12. def test_contextmanager_plain(self):
  13. state = []
  14. @contextmanager
  15. def woohoo():
  16. state.append(1)
  17. yield 42
  18. state.append(999)
  19. with woohoo() as x:
  20. self.assertEqual(state, [1])
  21. self.assertEqual(x, 42)
  22. state.append(x)
  23. self.assertEqual(state, [1, 42, 999])
  24. def test_contextmanager_finally(self):
  25. state = []
  26. @contextmanager
  27. def woohoo():
  28. state.append(1)
  29. try:
  30. yield 42
  31. finally:
  32. state.append(999)
  33. with self.assertRaises(ZeroDivisionError):
  34. with woohoo() as x:
  35. self.assertEqual(state, [1])
  36. self.assertEqual(x, 42)
  37. state.append(x)
  38. raise ZeroDivisionError()
  39. self.assertEqual(state, [1, 42, 999])
  40. def test_contextmanager_no_reraise(self):
  41. @contextmanager
  42. def whee():
  43. yield
  44. ctx = whee()
  45. ctx.__enter__()
  46. # Calling __exit__ should not result in an exception
  47. self.assertFalse(ctx.__exit__(TypeError, TypeError("foo"), None))
  48. def test_contextmanager_trap_yield_after_throw(self):
  49. @contextmanager
  50. def whoo():
  51. try:
  52. yield
  53. except:
  54. yield
  55. ctx = whoo()
  56. ctx.__enter__()
  57. self.assertRaises(
  58. RuntimeError, ctx.__exit__, TypeError, TypeError("foo"), None
  59. )
  60. def test_contextmanager_except(self):
  61. state = []
  62. @contextmanager
  63. def woohoo():
  64. state.append(1)
  65. try:
  66. yield 42
  67. except ZeroDivisionError, e:
  68. state.append(e.args[0])
  69. self.assertEqual(state, [1, 42, 999])
  70. with woohoo() as x:
  71. self.assertEqual(state, [1])
  72. self.assertEqual(x, 42)
  73. state.append(x)
  74. raise ZeroDivisionError(999)
  75. self.assertEqual(state, [1, 42, 999])
  76. def _create_contextmanager_attribs(self):
  77. def attribs(**kw):
  78. def decorate(func):
  79. for k,v in kw.items():
  80. setattr(func,k,v)
  81. return func
  82. return decorate
  83. @contextmanager
  84. @attribs(foo='bar')
  85. def baz(spam):
  86. """Whee!"""
  87. return baz
  88. def test_contextmanager_attribs(self):
  89. baz = self._create_contextmanager_attribs()
  90. self.assertEqual(baz.__name__,'baz')
  91. self.assertEqual(baz.foo, 'bar')
  92. @unittest.skipIf(sys.flags.optimize >= 2,
  93. "Docstrings are omitted with -O2 and above")
  94. def test_contextmanager_doc_attrib(self):
  95. baz = self._create_contextmanager_attribs()
  96. self.assertEqual(baz.__doc__, "Whee!")
  97. class NestedTestCase(unittest.TestCase):
  98. # XXX This needs more work
  99. def test_nested(self):
  100. @contextmanager
  101. def a():
  102. yield 1
  103. @contextmanager
  104. def b():
  105. yield 2
  106. @contextmanager
  107. def c():
  108. yield 3
  109. with nested(a(), b(), c()) as (x, y, z):
  110. self.assertEqual(x, 1)
  111. self.assertEqual(y, 2)
  112. self.assertEqual(z, 3)
  113. def test_nested_cleanup(self):
  114. state = []
  115. @contextmanager
  116. def a():
  117. state.append(1)
  118. try:
  119. yield 2
  120. finally:
  121. state.append(3)
  122. @contextmanager
  123. def b():
  124. state.append(4)
  125. try:
  126. yield 5
  127. finally:
  128. state.append(6)
  129. with self.assertRaises(ZeroDivisionError):
  130. with nested(a(), b()) as (x, y):
  131. state.append(x)
  132. state.append(y)
  133. 1 // 0
  134. self.assertEqual(state, [1, 4, 2, 5, 6, 3])
  135. def test_nested_right_exception(self):
  136. @contextmanager
  137. def a():
  138. yield 1
  139. class b(object):
  140. def __enter__(self):
  141. return 2
  142. def __exit__(self, *exc_info):
  143. try:
  144. raise Exception()
  145. except:
  146. pass
  147. with self.assertRaises(ZeroDivisionError):
  148. with nested(a(), b()) as (x, y):
  149. 1 // 0
  150. self.assertEqual((x, y), (1, 2))
  151. def test_nested_b_swallows(self):
  152. @contextmanager
  153. def a():
  154. yield
  155. @contextmanager
  156. def b():
  157. try:
  158. yield
  159. except:
  160. # Swallow the exception
  161. pass
  162. try:
  163. with nested(a(), b()):
  164. 1 // 0
  165. except ZeroDivisionError:
  166. self.fail("Didn't swallow ZeroDivisionError")
  167. def test_nested_break(self):
  168. @contextmanager
  169. def a():
  170. yield
  171. state = 0
  172. while True:
  173. state += 1
  174. with nested(a(), a()):
  175. break
  176. state += 10
  177. self.assertEqual(state, 1)
  178. def test_nested_continue(self):
  179. @contextmanager
  180. def a():
  181. yield
  182. state = 0
  183. while state < 3:
  184. state += 1
  185. with nested(a(), a()):
  186. continue
  187. state += 10
  188. self.assertEqual(state, 3)
  189. def test_nested_return(self):
  190. @contextmanager
  191. def a():
  192. try:
  193. yield
  194. except:
  195. pass
  196. def foo():
  197. with nested(a(), a()):
  198. return 1
  199. return 10
  200. self.assertEqual(foo(), 1)
  201. class ClosingTestCase(unittest.TestCase):
  202. # XXX This needs more work
  203. def test_closing(self):
  204. state = []
  205. class C:
  206. def close(self):
  207. state.append(1)
  208. x = C()
  209. self.assertEqual(state, [])
  210. with closing(x) as y:
  211. self.assertEqual(x, y)
  212. self.assertEqual(state, [1])
  213. def test_closing_error(self):
  214. state = []
  215. class C:
  216. def close(self):
  217. state.append(1)
  218. x = C()
  219. self.assertEqual(state, [])
  220. with self.assertRaises(ZeroDivisionError):
  221. with closing(x) as y:
  222. self.assertEqual(x, y)
  223. 1 // 0
  224. self.assertEqual(state, [1])
  225. class FileContextTestCase(unittest.TestCase):
  226. def testWithOpen(self):
  227. tfn = tempfile.mktemp()
  228. try:
  229. f = None
  230. with open(tfn, "w") as f:
  231. self.assertFalse(f.closed)
  232. f.write("Booh\n")
  233. self.assertTrue(f.closed)
  234. f = None
  235. with self.assertRaises(ZeroDivisionError):
  236. with open(tfn, "r") as f:
  237. self.assertFalse(f.closed)
  238. self.assertEqual(f.read(), "Booh\n")
  239. 1 // 0
  240. self.assertTrue(f.closed)
  241. finally:
  242. test_support.unlink(tfn)
  243. @unittest.skipUnless(threading, 'Threading required for this test.')
  244. class LockContextTestCase(unittest.TestCase):
  245. def boilerPlate(self, lock, locked):
  246. self.assertFalse(locked())
  247. with lock:
  248. self.assertTrue(locked())
  249. self.assertFalse(locked())
  250. with self.assertRaises(ZeroDivisionError):
  251. with lock:
  252. self.assertTrue(locked())
  253. 1 // 0
  254. self.assertFalse(locked())
  255. def testWithLock(self):
  256. lock = threading.Lock()
  257. self.boilerPlate(lock, lock.locked)
  258. def testWithRLock(self):
  259. lock = threading.RLock()
  260. self.boilerPlate(lock, lock._is_owned)
  261. def testWithCondition(self):
  262. lock = threading.Condition()
  263. def locked():
  264. return lock._is_owned()
  265. self.boilerPlate(lock, locked)
  266. def testWithSemaphore(self):
  267. lock = threading.Semaphore()
  268. def locked():
  269. if lock.acquire(False):
  270. lock.release()
  271. return False
  272. else:
  273. return True
  274. self.boilerPlate(lock, locked)
  275. def testWithBoundedSemaphore(self):
  276. lock = threading.BoundedSemaphore()
  277. def locked():
  278. if lock.acquire(False):
  279. lock.release()
  280. return False
  281. else:
  282. return True
  283. self.boilerPlate(lock, locked)
  284. # This is needed to make the test actually run under regrtest.py!
  285. def test_main():
  286. with test_support.check_warnings(("With-statements now directly support "
  287. "multiple context managers",
  288. DeprecationWarning)):
  289. test_support.run_unittest(__name__)
  290. if __name__ == "__main__":
  291. test_main()