Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 1 | """Unit tests for contextlib.py, and other context managers.""" |
| 2 | |
Raymond Hettinger | 088cbf2 | 2013-10-10 00:46:57 -0700 | [diff] [blame] | 3 | import io |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 4 | import sys |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 5 | import tempfile |
Antoine Pitrou | a6a4dc8 | 2017-09-07 18:56:24 +0200 | [diff] [blame] | 6 | import threading |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 7 | import unittest |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 8 | from contextlib import * # Tests __all__ |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 9 | from test import support |
Hai Shi | 96a6a6d | 2020-07-09 21:25:10 +0800 | [diff] [blame] | 10 | from test.support import os_helper |
Martin Teichmann | dd0e087 | 2018-01-28 05:17:46 +0100 | [diff] [blame] | 11 | import weakref |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 12 | |
Florent Xicluna | 41fe615 | 2010-04-02 18:52:12 +0000 | [diff] [blame] | 13 | |
Brett Cannon | 9e080e0 | 2016-04-08 12:15:27 -0700 | [diff] [blame] | 14 | class TestAbstractContextManager(unittest.TestCase): |
| 15 | |
| 16 | def test_enter(self): |
| 17 | class DefaultEnter(AbstractContextManager): |
| 18 | def __exit__(self, *args): |
| 19 | super().__exit__(*args) |
| 20 | |
| 21 | manager = DefaultEnter() |
| 22 | self.assertIs(manager.__enter__(), manager) |
| 23 | |
| 24 | def test_exit_is_abstract(self): |
| 25 | class MissingExit(AbstractContextManager): |
| 26 | pass |
| 27 | |
| 28 | with self.assertRaises(TypeError): |
| 29 | MissingExit() |
| 30 | |
| 31 | def test_structural_subclassing(self): |
| 32 | class ManagerFromScratch: |
| 33 | def __enter__(self): |
| 34 | return self |
| 35 | def __exit__(self, exc_type, exc_value, traceback): |
| 36 | return None |
| 37 | |
| 38 | self.assertTrue(issubclass(ManagerFromScratch, AbstractContextManager)) |
| 39 | |
| 40 | class DefaultEnter(AbstractContextManager): |
| 41 | def __exit__(self, *args): |
| 42 | super().__exit__(*args) |
| 43 | |
| 44 | self.assertTrue(issubclass(DefaultEnter, AbstractContextManager)) |
| 45 | |
Jelle Zijlstra | 57161aa | 2017-06-09 08:21:47 -0700 | [diff] [blame] | 46 | class NoEnter(ManagerFromScratch): |
| 47 | __enter__ = None |
| 48 | |
| 49 | self.assertFalse(issubclass(NoEnter, AbstractContextManager)) |
| 50 | |
| 51 | class NoExit(ManagerFromScratch): |
| 52 | __exit__ = None |
| 53 | |
| 54 | self.assertFalse(issubclass(NoExit, AbstractContextManager)) |
| 55 | |
Brett Cannon | 9e080e0 | 2016-04-08 12:15:27 -0700 | [diff] [blame] | 56 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 57 | class ContextManagerTestCase(unittest.TestCase): |
| 58 | |
| 59 | def test_contextmanager_plain(self): |
| 60 | state = [] |
| 61 | @contextmanager |
| 62 | def woohoo(): |
| 63 | state.append(1) |
| 64 | yield 42 |
| 65 | state.append(999) |
| 66 | with woohoo() as x: |
| 67 | self.assertEqual(state, [1]) |
| 68 | self.assertEqual(x, 42) |
| 69 | state.append(x) |
| 70 | self.assertEqual(state, [1, 42, 999]) |
| 71 | |
| 72 | def test_contextmanager_finally(self): |
| 73 | state = [] |
| 74 | @contextmanager |
| 75 | def woohoo(): |
| 76 | state.append(1) |
| 77 | try: |
| 78 | yield 42 |
| 79 | finally: |
| 80 | state.append(999) |
Florent Xicluna | 41fe615 | 2010-04-02 18:52:12 +0000 | [diff] [blame] | 81 | with self.assertRaises(ZeroDivisionError): |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 82 | with woohoo() as x: |
| 83 | self.assertEqual(state, [1]) |
| 84 | self.assertEqual(x, 42) |
| 85 | state.append(x) |
| 86 | raise ZeroDivisionError() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 87 | self.assertEqual(state, [1, 42, 999]) |
| 88 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 89 | def test_contextmanager_no_reraise(self): |
| 90 | @contextmanager |
| 91 | def whee(): |
| 92 | yield |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 93 | ctx = whee() |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 94 | ctx.__enter__() |
| 95 | # Calling __exit__ should not result in an exception |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 96 | self.assertFalse(ctx.__exit__(TypeError, TypeError("foo"), None)) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 97 | |
| 98 | def test_contextmanager_trap_yield_after_throw(self): |
| 99 | @contextmanager |
| 100 | def whoo(): |
| 101 | try: |
| 102 | yield |
| 103 | except: |
| 104 | yield |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 105 | ctx = whoo() |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 106 | ctx.__enter__() |
| 107 | self.assertRaises( |
| 108 | RuntimeError, ctx.__exit__, TypeError, TypeError("foo"), None |
| 109 | ) |
| 110 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 111 | def test_contextmanager_except(self): |
| 112 | state = [] |
| 113 | @contextmanager |
| 114 | def woohoo(): |
| 115 | state.append(1) |
| 116 | try: |
| 117 | yield 42 |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 118 | except ZeroDivisionError as e: |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 119 | state.append(e.args[0]) |
| 120 | self.assertEqual(state, [1, 42, 999]) |
| 121 | with woohoo() as x: |
| 122 | self.assertEqual(state, [1]) |
| 123 | self.assertEqual(x, 42) |
| 124 | state.append(x) |
| 125 | raise ZeroDivisionError(999) |
| 126 | self.assertEqual(state, [1, 42, 999]) |
| 127 | |
Yury Selivanov | 8170e8c | 2015-05-09 11:44:30 -0400 | [diff] [blame] | 128 | def test_contextmanager_except_stopiter(self): |
Yury Selivanov | 8170e8c | 2015-05-09 11:44:30 -0400 | [diff] [blame] | 129 | @contextmanager |
| 130 | def woohoo(): |
| 131 | yield |
Miss Islington (bot) | 68b4690 | 2021-07-20 12:12:47 -0700 | [diff] [blame] | 132 | |
| 133 | class StopIterationSubclass(StopIteration): |
| 134 | pass |
| 135 | |
| 136 | for stop_exc in (StopIteration('spam'), StopIterationSubclass('spam')): |
| 137 | with self.subTest(type=type(stop_exc)): |
| 138 | try: |
| 139 | with woohoo(): |
| 140 | raise stop_exc |
| 141 | except Exception as ex: |
| 142 | self.assertIs(ex, stop_exc) |
| 143 | else: |
| 144 | self.fail(f'{stop_exc} was suppressed') |
Yury Selivanov | 8170e8c | 2015-05-09 11:44:30 -0400 | [diff] [blame] | 145 | |
| 146 | def test_contextmanager_except_pep479(self): |
| 147 | code = """\ |
| 148 | from __future__ import generator_stop |
| 149 | from contextlib import contextmanager |
| 150 | @contextmanager |
| 151 | def woohoo(): |
| 152 | yield |
| 153 | """ |
| 154 | locals = {} |
| 155 | exec(code, locals, locals) |
| 156 | woohoo = locals['woohoo'] |
| 157 | |
| 158 | stop_exc = StopIteration('spam') |
| 159 | try: |
| 160 | with woohoo(): |
| 161 | raise stop_exc |
| 162 | except Exception as ex: |
| 163 | self.assertIs(ex, stop_exc) |
| 164 | else: |
| 165 | self.fail('StopIteration was suppressed') |
| 166 | |
svelankar | 00c75e9 | 2017-04-11 05:11:13 -0400 | [diff] [blame] | 167 | def test_contextmanager_do_not_unchain_non_stopiteration_exceptions(self): |
| 168 | @contextmanager |
| 169 | def test_issue29692(): |
| 170 | try: |
| 171 | yield |
| 172 | except Exception as exc: |
| 173 | raise RuntimeError('issue29692:Chained') from exc |
| 174 | try: |
| 175 | with test_issue29692(): |
| 176 | raise ZeroDivisionError |
| 177 | except Exception as ex: |
| 178 | self.assertIs(type(ex), RuntimeError) |
| 179 | self.assertEqual(ex.args[0], 'issue29692:Chained') |
| 180 | self.assertIsInstance(ex.__cause__, ZeroDivisionError) |
| 181 | |
| 182 | try: |
| 183 | with test_issue29692(): |
| 184 | raise StopIteration('issue29692:Unchained') |
| 185 | except Exception as ex: |
| 186 | self.assertIs(type(ex), StopIteration) |
| 187 | self.assertEqual(ex.args[0], 'issue29692:Unchained') |
| 188 | self.assertIsNone(ex.__cause__) |
| 189 | |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 190 | def _create_contextmanager_attribs(self): |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 191 | def attribs(**kw): |
| 192 | def decorate(func): |
| 193 | for k,v in kw.items(): |
| 194 | setattr(func,k,v) |
| 195 | return func |
| 196 | return decorate |
| 197 | @contextmanager |
| 198 | @attribs(foo='bar') |
| 199 | def baz(spam): |
| 200 | """Whee!""" |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 201 | return baz |
| 202 | |
| 203 | def test_contextmanager_attribs(self): |
| 204 | baz = self._create_contextmanager_attribs() |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 205 | self.assertEqual(baz.__name__,'baz') |
| 206 | self.assertEqual(baz.foo, 'bar') |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 207 | |
Nick Coghlan | 561eb5c | 2013-10-26 22:20:43 +1000 | [diff] [blame] | 208 | @support.requires_docstrings |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 209 | def test_contextmanager_doc_attrib(self): |
| 210 | baz = self._create_contextmanager_attribs() |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 211 | self.assertEqual(baz.__doc__, "Whee!") |
| 212 | |
Nick Coghlan | 561eb5c | 2013-10-26 22:20:43 +1000 | [diff] [blame] | 213 | @support.requires_docstrings |
| 214 | def test_instance_docstring_given_cm_docstring(self): |
| 215 | baz = self._create_contextmanager_attribs()(None) |
| 216 | self.assertEqual(baz.__doc__, "Whee!") |
| 217 | |
Serhiy Storchaka | 101ff35 | 2015-06-28 17:06:07 +0300 | [diff] [blame] | 218 | def test_keywords(self): |
| 219 | # Ensure no keyword arguments are inhibited |
| 220 | @contextmanager |
| 221 | def woohoo(self, func, args, kwds): |
| 222 | yield (self, func, args, kwds) |
| 223 | with woohoo(self=11, func=22, args=33, kwds=44) as target: |
| 224 | self.assertEqual(target, (11, 22, 33, 44)) |
| 225 | |
Martin Teichmann | dd0e087 | 2018-01-28 05:17:46 +0100 | [diff] [blame] | 226 | def test_nokeepref(self): |
| 227 | class A: |
| 228 | pass |
| 229 | |
| 230 | @contextmanager |
| 231 | def woohoo(a, b): |
| 232 | a = weakref.ref(a) |
| 233 | b = weakref.ref(b) |
Miss Islington (bot) | 0ea5e0d | 2021-07-26 14:21:36 -0700 | [diff] [blame] | 234 | # Allow test to work with a non-refcounted GC |
| 235 | support.gc_collect() |
Martin Teichmann | dd0e087 | 2018-01-28 05:17:46 +0100 | [diff] [blame] | 236 | self.assertIsNone(a()) |
| 237 | self.assertIsNone(b()) |
| 238 | yield |
| 239 | |
| 240 | with woohoo(A(), b=A()): |
| 241 | pass |
| 242 | |
| 243 | def test_param_errors(self): |
| 244 | @contextmanager |
| 245 | def woohoo(a, *, b): |
| 246 | yield |
| 247 | |
| 248 | with self.assertRaises(TypeError): |
| 249 | woohoo() |
| 250 | with self.assertRaises(TypeError): |
| 251 | woohoo(3, 5) |
| 252 | with self.assertRaises(TypeError): |
| 253 | woohoo(b=3) |
| 254 | |
| 255 | def test_recursive(self): |
| 256 | depth = 0 |
| 257 | @contextmanager |
| 258 | def woohoo(): |
| 259 | nonlocal depth |
| 260 | before = depth |
| 261 | depth += 1 |
| 262 | yield |
| 263 | depth -= 1 |
| 264 | self.assertEqual(depth, before) |
| 265 | |
| 266 | @woohoo() |
| 267 | def recursive(): |
| 268 | if depth < 10: |
| 269 | recursive() |
| 270 | |
| 271 | recursive() |
| 272 | self.assertEqual(depth, 0) |
| 273 | |
Nick Coghlan | 561eb5c | 2013-10-26 22:20:43 +1000 | [diff] [blame] | 274 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 275 | class ClosingTestCase(unittest.TestCase): |
| 276 | |
Nick Coghlan | 561eb5c | 2013-10-26 22:20:43 +1000 | [diff] [blame] | 277 | @support.requires_docstrings |
Nick Coghlan | 059def5 | 2013-10-26 18:08:15 +1000 | [diff] [blame] | 278 | def test_instance_docs(self): |
| 279 | # Issue 19330: ensure context manager instances have good docstrings |
| 280 | cm_docstring = closing.__doc__ |
| 281 | obj = closing(None) |
| 282 | self.assertEqual(obj.__doc__, cm_docstring) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 283 | |
| 284 | def test_closing(self): |
| 285 | state = [] |
| 286 | class C: |
| 287 | def close(self): |
| 288 | state.append(1) |
| 289 | x = C() |
| 290 | self.assertEqual(state, []) |
| 291 | with closing(x) as y: |
| 292 | self.assertEqual(x, y) |
| 293 | self.assertEqual(state, [1]) |
| 294 | |
| 295 | def test_closing_error(self): |
| 296 | state = [] |
| 297 | class C: |
| 298 | def close(self): |
| 299 | state.append(1) |
| 300 | x = C() |
| 301 | self.assertEqual(state, []) |
Florent Xicluna | 41fe615 | 2010-04-02 18:52:12 +0000 | [diff] [blame] | 302 | with self.assertRaises(ZeroDivisionError): |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 303 | with closing(x) as y: |
| 304 | self.assertEqual(x, y) |
Florent Xicluna | 41fe615 | 2010-04-02 18:52:12 +0000 | [diff] [blame] | 305 | 1 / 0 |
| 306 | self.assertEqual(state, [1]) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 307 | |
Jesse-Bakker | 0784a2e | 2017-11-23 01:23:28 +0100 | [diff] [blame] | 308 | |
| 309 | class NullcontextTestCase(unittest.TestCase): |
| 310 | def test_nullcontext(self): |
| 311 | class C: |
| 312 | pass |
| 313 | c = C() |
| 314 | with nullcontext(c) as c_in: |
| 315 | self.assertIs(c_in, c) |
| 316 | |
| 317 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 318 | class FileContextTestCase(unittest.TestCase): |
| 319 | |
| 320 | def testWithOpen(self): |
| 321 | tfn = tempfile.mktemp() |
| 322 | try: |
| 323 | f = None |
Inada Naoki | 35715d1 | 2021-04-04 09:01:23 +0900 | [diff] [blame] | 324 | with open(tfn, "w", encoding="utf-8") as f: |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 325 | self.assertFalse(f.closed) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 326 | f.write("Booh\n") |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 327 | self.assertTrue(f.closed) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 328 | f = None |
Florent Xicluna | 41fe615 | 2010-04-02 18:52:12 +0000 | [diff] [blame] | 329 | with self.assertRaises(ZeroDivisionError): |
Inada Naoki | 35715d1 | 2021-04-04 09:01:23 +0900 | [diff] [blame] | 330 | with open(tfn, "r", encoding="utf-8") as f: |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 331 | self.assertFalse(f.closed) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 332 | self.assertEqual(f.read(), "Booh\n") |
Florent Xicluna | 41fe615 | 2010-04-02 18:52:12 +0000 | [diff] [blame] | 333 | 1 / 0 |
| 334 | self.assertTrue(f.closed) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 335 | finally: |
Hai Shi | 96a6a6d | 2020-07-09 21:25:10 +0800 | [diff] [blame] | 336 | os_helper.unlink(tfn) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 337 | |
| 338 | class LockContextTestCase(unittest.TestCase): |
| 339 | |
| 340 | def boilerPlate(self, lock, locked): |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 341 | self.assertFalse(locked()) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 342 | with lock: |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 343 | self.assertTrue(locked()) |
| 344 | self.assertFalse(locked()) |
Florent Xicluna | 41fe615 | 2010-04-02 18:52:12 +0000 | [diff] [blame] | 345 | with self.assertRaises(ZeroDivisionError): |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 346 | with lock: |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 347 | self.assertTrue(locked()) |
Florent Xicluna | 41fe615 | 2010-04-02 18:52:12 +0000 | [diff] [blame] | 348 | 1 / 0 |
| 349 | self.assertFalse(locked()) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 350 | |
| 351 | def testWithLock(self): |
| 352 | lock = threading.Lock() |
| 353 | self.boilerPlate(lock, lock.locked) |
| 354 | |
| 355 | def testWithRLock(self): |
| 356 | lock = threading.RLock() |
| 357 | self.boilerPlate(lock, lock._is_owned) |
| 358 | |
| 359 | def testWithCondition(self): |
| 360 | lock = threading.Condition() |
| 361 | def locked(): |
| 362 | return lock._is_owned() |
| 363 | self.boilerPlate(lock, locked) |
| 364 | |
| 365 | def testWithSemaphore(self): |
| 366 | lock = threading.Semaphore() |
| 367 | def locked(): |
| 368 | if lock.acquire(False): |
| 369 | lock.release() |
| 370 | return False |
| 371 | else: |
| 372 | return True |
| 373 | self.boilerPlate(lock, locked) |
| 374 | |
| 375 | def testWithBoundedSemaphore(self): |
| 376 | lock = threading.BoundedSemaphore() |
| 377 | def locked(): |
| 378 | if lock.acquire(False): |
| 379 | lock.release() |
| 380 | return False |
| 381 | else: |
| 382 | return True |
| 383 | self.boilerPlate(lock, locked) |
| 384 | |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 385 | |
| 386 | class mycontext(ContextDecorator): |
Nick Coghlan | 059def5 | 2013-10-26 18:08:15 +1000 | [diff] [blame] | 387 | """Example decoration-compatible context manager for testing""" |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 388 | started = False |
| 389 | exc = None |
| 390 | catch = False |
| 391 | |
| 392 | def __enter__(self): |
| 393 | self.started = True |
| 394 | return self |
| 395 | |
| 396 | def __exit__(self, *exc): |
| 397 | self.exc = exc |
| 398 | return self.catch |
| 399 | |
| 400 | |
| 401 | class TestContextDecorator(unittest.TestCase): |
| 402 | |
Nick Coghlan | 561eb5c | 2013-10-26 22:20:43 +1000 | [diff] [blame] | 403 | @support.requires_docstrings |
Nick Coghlan | 059def5 | 2013-10-26 18:08:15 +1000 | [diff] [blame] | 404 | def test_instance_docs(self): |
| 405 | # Issue 19330: ensure context manager instances have good docstrings |
| 406 | cm_docstring = mycontext.__doc__ |
| 407 | obj = mycontext() |
| 408 | self.assertEqual(obj.__doc__, cm_docstring) |
| 409 | |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 410 | def test_contextdecorator(self): |
| 411 | context = mycontext() |
| 412 | with context as result: |
| 413 | self.assertIs(result, context) |
| 414 | self.assertTrue(context.started) |
| 415 | |
| 416 | self.assertEqual(context.exc, (None, None, None)) |
| 417 | |
| 418 | |
| 419 | def test_contextdecorator_with_exception(self): |
| 420 | context = mycontext() |
| 421 | |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 422 | with self.assertRaisesRegex(NameError, 'foo'): |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 423 | with context: |
| 424 | raise NameError('foo') |
| 425 | self.assertIsNotNone(context.exc) |
| 426 | self.assertIs(context.exc[0], NameError) |
| 427 | |
| 428 | context = mycontext() |
| 429 | context.catch = True |
| 430 | with context: |
| 431 | raise NameError('foo') |
| 432 | self.assertIsNotNone(context.exc) |
| 433 | self.assertIs(context.exc[0], NameError) |
| 434 | |
| 435 | |
| 436 | def test_decorator(self): |
| 437 | context = mycontext() |
| 438 | |
| 439 | @context |
| 440 | def test(): |
| 441 | self.assertIsNone(context.exc) |
| 442 | self.assertTrue(context.started) |
| 443 | test() |
| 444 | self.assertEqual(context.exc, (None, None, None)) |
| 445 | |
| 446 | |
| 447 | def test_decorator_with_exception(self): |
| 448 | context = mycontext() |
| 449 | |
| 450 | @context |
| 451 | def test(): |
| 452 | self.assertIsNone(context.exc) |
| 453 | self.assertTrue(context.started) |
| 454 | raise NameError('foo') |
| 455 | |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 456 | with self.assertRaisesRegex(NameError, 'foo'): |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 457 | test() |
| 458 | self.assertIsNotNone(context.exc) |
| 459 | self.assertIs(context.exc[0], NameError) |
| 460 | |
| 461 | |
| 462 | def test_decorating_method(self): |
| 463 | context = mycontext() |
| 464 | |
| 465 | class Test(object): |
| 466 | |
| 467 | @context |
| 468 | def method(self, a, b, c=None): |
| 469 | self.a = a |
| 470 | self.b = b |
| 471 | self.c = c |
| 472 | |
| 473 | # these tests are for argument passing when used as a decorator |
| 474 | test = Test() |
| 475 | test.method(1, 2) |
| 476 | self.assertEqual(test.a, 1) |
| 477 | self.assertEqual(test.b, 2) |
| 478 | self.assertEqual(test.c, None) |
| 479 | |
| 480 | test = Test() |
| 481 | test.method('a', 'b', 'c') |
| 482 | self.assertEqual(test.a, 'a') |
| 483 | self.assertEqual(test.b, 'b') |
| 484 | self.assertEqual(test.c, 'c') |
| 485 | |
| 486 | test = Test() |
| 487 | test.method(a=1, b=2) |
| 488 | self.assertEqual(test.a, 1) |
| 489 | self.assertEqual(test.b, 2) |
| 490 | |
| 491 | |
| 492 | def test_typo_enter(self): |
| 493 | class mycontext(ContextDecorator): |
| 494 | def __unter__(self): |
| 495 | pass |
| 496 | def __exit__(self, *exc): |
| 497 | pass |
| 498 | |
| 499 | with self.assertRaises(AttributeError): |
| 500 | with mycontext(): |
| 501 | pass |
| 502 | |
| 503 | |
| 504 | def test_typo_exit(self): |
| 505 | class mycontext(ContextDecorator): |
| 506 | def __enter__(self): |
| 507 | pass |
| 508 | def __uxit__(self, *exc): |
| 509 | pass |
| 510 | |
| 511 | with self.assertRaises(AttributeError): |
| 512 | with mycontext(): |
| 513 | pass |
| 514 | |
| 515 | |
| 516 | def test_contextdecorator_as_mixin(self): |
| 517 | class somecontext(object): |
| 518 | started = False |
| 519 | exc = None |
| 520 | |
| 521 | def __enter__(self): |
| 522 | self.started = True |
| 523 | return self |
| 524 | |
| 525 | def __exit__(self, *exc): |
| 526 | self.exc = exc |
| 527 | |
| 528 | class mycontext(somecontext, ContextDecorator): |
| 529 | pass |
| 530 | |
| 531 | context = mycontext() |
| 532 | @context |
| 533 | def test(): |
| 534 | self.assertIsNone(context.exc) |
| 535 | self.assertTrue(context.started) |
| 536 | test() |
| 537 | self.assertEqual(context.exc, (None, None, None)) |
| 538 | |
| 539 | |
| 540 | def test_contextmanager_as_decorator(self): |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 541 | @contextmanager |
| 542 | def woohoo(y): |
| 543 | state.append(y) |
| 544 | yield |
| 545 | state.append(999) |
| 546 | |
Nick Coghlan | 0ded3e3 | 2011-05-05 23:49:25 +1000 | [diff] [blame] | 547 | state = [] |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 548 | @woohoo(1) |
| 549 | def test(x): |
| 550 | self.assertEqual(state, [1]) |
| 551 | state.append(x) |
| 552 | test('something') |
| 553 | self.assertEqual(state, [1, 'something', 999]) |
| 554 | |
Nick Coghlan | 0ded3e3 | 2011-05-05 23:49:25 +1000 | [diff] [blame] | 555 | # Issue #11647: Ensure the decorated function is 'reusable' |
| 556 | state = [] |
| 557 | test('something else') |
| 558 | self.assertEqual(state, [1, 'something else', 999]) |
| 559 | |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 560 | |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 561 | class TestBaseExitStack: |
| 562 | exit_stack = None |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 563 | |
Nick Coghlan | 561eb5c | 2013-10-26 22:20:43 +1000 | [diff] [blame] | 564 | @support.requires_docstrings |
Nick Coghlan | 059def5 | 2013-10-26 18:08:15 +1000 | [diff] [blame] | 565 | def test_instance_docs(self): |
| 566 | # Issue 19330: ensure context manager instances have good docstrings |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 567 | cm_docstring = self.exit_stack.__doc__ |
| 568 | obj = self.exit_stack() |
Nick Coghlan | 059def5 | 2013-10-26 18:08:15 +1000 | [diff] [blame] | 569 | self.assertEqual(obj.__doc__, cm_docstring) |
| 570 | |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 571 | def test_no_resources(self): |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 572 | with self.exit_stack(): |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 573 | pass |
| 574 | |
| 575 | def test_callback(self): |
| 576 | expected = [ |
| 577 | ((), {}), |
| 578 | ((1,), {}), |
| 579 | ((1,2), {}), |
| 580 | ((), dict(example=1)), |
| 581 | ((1,), dict(example=1)), |
| 582 | ((1,2), dict(example=1)), |
Serhiy Storchaka | 42a139e | 2019-04-01 09:16:35 +0300 | [diff] [blame] | 583 | ((1,2), dict(self=3, callback=4)), |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 584 | ] |
| 585 | result = [] |
| 586 | def _exit(*args, **kwds): |
| 587 | """Test metadata propagation""" |
| 588 | result.append((args, kwds)) |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 589 | with self.exit_stack() as stack: |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 590 | for args, kwds in reversed(expected): |
| 591 | if args and kwds: |
| 592 | f = stack.callback(_exit, *args, **kwds) |
| 593 | elif args: |
| 594 | f = stack.callback(_exit, *args) |
| 595 | elif kwds: |
| 596 | f = stack.callback(_exit, **kwds) |
| 597 | else: |
| 598 | f = stack.callback(_exit) |
| 599 | self.assertIs(f, _exit) |
| 600 | for wrapper in stack._exit_callbacks: |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 601 | self.assertIs(wrapper[1].__wrapped__, _exit) |
| 602 | self.assertNotEqual(wrapper[1].__name__, _exit.__name__) |
| 603 | self.assertIsNone(wrapper[1].__doc__, _exit.__doc__) |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 604 | self.assertEqual(result, expected) |
| 605 | |
Serhiy Storchaka | 42a139e | 2019-04-01 09:16:35 +0300 | [diff] [blame] | 606 | result = [] |
| 607 | with self.exit_stack() as stack: |
| 608 | with self.assertRaises(TypeError): |
| 609 | stack.callback(arg=1) |
| 610 | with self.assertRaises(TypeError): |
| 611 | self.exit_stack.callback(arg=2) |
Serhiy Storchaka | 142566c | 2019-06-05 18:22:31 +0300 | [diff] [blame] | 612 | with self.assertRaises(TypeError): |
Serhiy Storchaka | 42a139e | 2019-04-01 09:16:35 +0300 | [diff] [blame] | 613 | stack.callback(callback=_exit, arg=3) |
Serhiy Storchaka | 142566c | 2019-06-05 18:22:31 +0300 | [diff] [blame] | 614 | self.assertEqual(result, []) |
Serhiy Storchaka | 42a139e | 2019-04-01 09:16:35 +0300 | [diff] [blame] | 615 | |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 616 | def test_push(self): |
| 617 | exc_raised = ZeroDivisionError |
| 618 | def _expect_exc(exc_type, exc, exc_tb): |
| 619 | self.assertIs(exc_type, exc_raised) |
| 620 | def _suppress_exc(*exc_details): |
| 621 | return True |
| 622 | def _expect_ok(exc_type, exc, exc_tb): |
| 623 | self.assertIsNone(exc_type) |
| 624 | self.assertIsNone(exc) |
| 625 | self.assertIsNone(exc_tb) |
| 626 | class ExitCM(object): |
| 627 | def __init__(self, check_exc): |
| 628 | self.check_exc = check_exc |
| 629 | def __enter__(self): |
| 630 | self.fail("Should not be called!") |
| 631 | def __exit__(self, *exc_details): |
| 632 | self.check_exc(*exc_details) |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 633 | with self.exit_stack() as stack: |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 634 | stack.push(_expect_ok) |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 635 | self.assertIs(stack._exit_callbacks[-1][1], _expect_ok) |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 636 | cm = ExitCM(_expect_ok) |
| 637 | stack.push(cm) |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 638 | self.assertIs(stack._exit_callbacks[-1][1].__self__, cm) |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 639 | stack.push(_suppress_exc) |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 640 | self.assertIs(stack._exit_callbacks[-1][1], _suppress_exc) |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 641 | cm = ExitCM(_expect_exc) |
| 642 | stack.push(cm) |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 643 | self.assertIs(stack._exit_callbacks[-1][1].__self__, cm) |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 644 | stack.push(_expect_exc) |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 645 | self.assertIs(stack._exit_callbacks[-1][1], _expect_exc) |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 646 | stack.push(_expect_exc) |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 647 | self.assertIs(stack._exit_callbacks[-1][1], _expect_exc) |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 648 | 1/0 |
| 649 | |
| 650 | def test_enter_context(self): |
| 651 | class TestCM(object): |
| 652 | def __enter__(self): |
| 653 | result.append(1) |
| 654 | def __exit__(self, *exc_details): |
| 655 | result.append(3) |
| 656 | |
| 657 | result = [] |
| 658 | cm = TestCM() |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 659 | with self.exit_stack() as stack: |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 660 | @stack.callback # Registered first => cleaned up last |
| 661 | def _exit(): |
| 662 | result.append(4) |
| 663 | self.assertIsNotNone(_exit) |
| 664 | stack.enter_context(cm) |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 665 | self.assertIs(stack._exit_callbacks[-1][1].__self__, cm) |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 666 | result.append(2) |
| 667 | self.assertEqual(result, [1, 2, 3, 4]) |
| 668 | |
| 669 | def test_close(self): |
| 670 | result = [] |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 671 | with self.exit_stack() as stack: |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 672 | @stack.callback |
| 673 | def _exit(): |
| 674 | result.append(1) |
| 675 | self.assertIsNotNone(_exit) |
| 676 | stack.close() |
| 677 | result.append(2) |
| 678 | self.assertEqual(result, [1, 2]) |
| 679 | |
| 680 | def test_pop_all(self): |
| 681 | result = [] |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 682 | with self.exit_stack() as stack: |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 683 | @stack.callback |
| 684 | def _exit(): |
| 685 | result.append(3) |
| 686 | self.assertIsNotNone(_exit) |
| 687 | new_stack = stack.pop_all() |
| 688 | result.append(1) |
| 689 | result.append(2) |
| 690 | new_stack.close() |
| 691 | self.assertEqual(result, [1, 2, 3]) |
| 692 | |
Nick Coghlan | c73e8c2 | 2012-05-31 23:49:26 +1000 | [diff] [blame] | 693 | def test_exit_raise(self): |
| 694 | with self.assertRaises(ZeroDivisionError): |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 695 | with self.exit_stack() as stack: |
Nick Coghlan | c73e8c2 | 2012-05-31 23:49:26 +1000 | [diff] [blame] | 696 | stack.push(lambda *exc: False) |
| 697 | 1/0 |
| 698 | |
| 699 | def test_exit_suppress(self): |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 700 | with self.exit_stack() as stack: |
Nick Coghlan | c73e8c2 | 2012-05-31 23:49:26 +1000 | [diff] [blame] | 701 | stack.push(lambda *exc: True) |
| 702 | 1/0 |
| 703 | |
| 704 | def test_exit_exception_chaining_reference(self): |
| 705 | # Sanity check to make sure that ExitStack chaining matches |
| 706 | # actual nested with statements |
| 707 | class RaiseExc: |
| 708 | def __init__(self, exc): |
| 709 | self.exc = exc |
| 710 | def __enter__(self): |
| 711 | return self |
| 712 | def __exit__(self, *exc_details): |
| 713 | raise self.exc |
| 714 | |
Nick Coghlan | 77452fc | 2012-06-01 22:48:32 +1000 | [diff] [blame] | 715 | class RaiseExcWithContext: |
| 716 | def __init__(self, outer, inner): |
| 717 | self.outer = outer |
| 718 | self.inner = inner |
| 719 | def __enter__(self): |
| 720 | return self |
| 721 | def __exit__(self, *exc_details): |
| 722 | try: |
| 723 | raise self.inner |
| 724 | except: |
| 725 | raise self.outer |
| 726 | |
Nick Coghlan | c73e8c2 | 2012-05-31 23:49:26 +1000 | [diff] [blame] | 727 | class SuppressExc: |
| 728 | def __enter__(self): |
| 729 | return self |
| 730 | def __exit__(self, *exc_details): |
| 731 | type(self).saved_details = exc_details |
| 732 | return True |
| 733 | |
| 734 | try: |
| 735 | with RaiseExc(IndexError): |
Nick Coghlan | 77452fc | 2012-06-01 22:48:32 +1000 | [diff] [blame] | 736 | with RaiseExcWithContext(KeyError, AttributeError): |
| 737 | with SuppressExc(): |
| 738 | with RaiseExc(ValueError): |
| 739 | 1 / 0 |
Nick Coghlan | c73e8c2 | 2012-05-31 23:49:26 +1000 | [diff] [blame] | 740 | except IndexError as exc: |
| 741 | self.assertIsInstance(exc.__context__, KeyError) |
| 742 | self.assertIsInstance(exc.__context__.__context__, AttributeError) |
| 743 | # Inner exceptions were suppressed |
| 744 | self.assertIsNone(exc.__context__.__context__.__context__) |
| 745 | else: |
| 746 | self.fail("Expected IndexError, but no exception was raised") |
| 747 | # Check the inner exceptions |
| 748 | inner_exc = SuppressExc.saved_details[1] |
| 749 | self.assertIsInstance(inner_exc, ValueError) |
| 750 | self.assertIsInstance(inner_exc.__context__, ZeroDivisionError) |
| 751 | |
| 752 | def test_exit_exception_chaining(self): |
| 753 | # Ensure exception chaining matches the reference behaviour |
| 754 | def raise_exc(exc): |
| 755 | raise exc |
| 756 | |
| 757 | saved_details = None |
| 758 | def suppress_exc(*exc_details): |
| 759 | nonlocal saved_details |
| 760 | saved_details = exc_details |
| 761 | return True |
| 762 | |
| 763 | try: |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 764 | with self.exit_stack() as stack: |
Nick Coghlan | c73e8c2 | 2012-05-31 23:49:26 +1000 | [diff] [blame] | 765 | stack.callback(raise_exc, IndexError) |
| 766 | stack.callback(raise_exc, KeyError) |
| 767 | stack.callback(raise_exc, AttributeError) |
| 768 | stack.push(suppress_exc) |
| 769 | stack.callback(raise_exc, ValueError) |
| 770 | 1 / 0 |
| 771 | except IndexError as exc: |
| 772 | self.assertIsInstance(exc.__context__, KeyError) |
| 773 | self.assertIsInstance(exc.__context__.__context__, AttributeError) |
Nick Coghlan | 77452fc | 2012-06-01 22:48:32 +1000 | [diff] [blame] | 774 | # Inner exceptions were suppressed |
| 775 | self.assertIsNone(exc.__context__.__context__.__context__) |
Nick Coghlan | c73e8c2 | 2012-05-31 23:49:26 +1000 | [diff] [blame] | 776 | else: |
| 777 | self.fail("Expected IndexError, but no exception was raised") |
| 778 | # Check the inner exceptions |
| 779 | inner_exc = saved_details[1] |
| 780 | self.assertIsInstance(inner_exc, ValueError) |
| 781 | self.assertIsInstance(inner_exc.__context__, ZeroDivisionError) |
| 782 | |
Nick Coghlan | 1a33b2f | 2013-10-01 23:24:56 +1000 | [diff] [blame] | 783 | def test_exit_exception_non_suppressing(self): |
| 784 | # http://bugs.python.org/issue19092 |
| 785 | def raise_exc(exc): |
| 786 | raise exc |
| 787 | |
| 788 | def suppress_exc(*exc_details): |
| 789 | return True |
| 790 | |
| 791 | try: |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 792 | with self.exit_stack() as stack: |
Nick Coghlan | 1a33b2f | 2013-10-01 23:24:56 +1000 | [diff] [blame] | 793 | stack.callback(lambda: None) |
| 794 | stack.callback(raise_exc, IndexError) |
| 795 | except Exception as exc: |
| 796 | self.assertIsInstance(exc, IndexError) |
| 797 | else: |
| 798 | self.fail("Expected IndexError, but no exception was raised") |
| 799 | |
| 800 | try: |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 801 | with self.exit_stack() as stack: |
Nick Coghlan | 1a33b2f | 2013-10-01 23:24:56 +1000 | [diff] [blame] | 802 | stack.callback(raise_exc, KeyError) |
| 803 | stack.push(suppress_exc) |
| 804 | stack.callback(raise_exc, IndexError) |
| 805 | except Exception as exc: |
| 806 | self.assertIsInstance(exc, KeyError) |
| 807 | else: |
| 808 | self.fail("Expected KeyError, but no exception was raised") |
| 809 | |
Nick Coghlan | 09761e7 | 2014-01-22 22:24:46 +1000 | [diff] [blame] | 810 | def test_exit_exception_with_correct_context(self): |
| 811 | # http://bugs.python.org/issue20317 |
| 812 | @contextmanager |
Nick Coghlan | add94c9 | 2014-01-24 23:05:45 +1000 | [diff] [blame] | 813 | def gets_the_context_right(exc): |
Nick Coghlan | 09761e7 | 2014-01-22 22:24:46 +1000 | [diff] [blame] | 814 | try: |
Nick Coghlan | add94c9 | 2014-01-24 23:05:45 +1000 | [diff] [blame] | 815 | yield |
Nick Coghlan | 09761e7 | 2014-01-22 22:24:46 +1000 | [diff] [blame] | 816 | finally: |
Nick Coghlan | add94c9 | 2014-01-24 23:05:45 +1000 | [diff] [blame] | 817 | raise exc |
| 818 | |
| 819 | exc1 = Exception(1) |
| 820 | exc2 = Exception(2) |
| 821 | exc3 = Exception(3) |
| 822 | exc4 = Exception(4) |
Nick Coghlan | 09761e7 | 2014-01-22 22:24:46 +1000 | [diff] [blame] | 823 | |
| 824 | # The contextmanager already fixes the context, so prior to the |
| 825 | # fix, ExitStack would try to fix it *again* and get into an |
| 826 | # infinite self-referential loop |
| 827 | try: |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 828 | with self.exit_stack() as stack: |
Nick Coghlan | add94c9 | 2014-01-24 23:05:45 +1000 | [diff] [blame] | 829 | stack.enter_context(gets_the_context_right(exc4)) |
| 830 | stack.enter_context(gets_the_context_right(exc3)) |
| 831 | stack.enter_context(gets_the_context_right(exc2)) |
| 832 | raise exc1 |
| 833 | except Exception as exc: |
| 834 | self.assertIs(exc, exc4) |
| 835 | self.assertIs(exc.__context__, exc3) |
| 836 | self.assertIs(exc.__context__.__context__, exc2) |
| 837 | self.assertIs(exc.__context__.__context__.__context__, exc1) |
| 838 | self.assertIsNone( |
| 839 | exc.__context__.__context__.__context__.__context__) |
| 840 | |
| 841 | def test_exit_exception_with_existing_context(self): |
| 842 | # Addresses a lack of test coverage discovered after checking in a |
| 843 | # fix for issue 20317 that still contained debugging code. |
| 844 | def raise_nested(inner_exc, outer_exc): |
| 845 | try: |
| 846 | raise inner_exc |
| 847 | finally: |
| 848 | raise outer_exc |
| 849 | exc1 = Exception(1) |
| 850 | exc2 = Exception(2) |
| 851 | exc3 = Exception(3) |
| 852 | exc4 = Exception(4) |
| 853 | exc5 = Exception(5) |
| 854 | try: |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 855 | with self.exit_stack() as stack: |
Nick Coghlan | add94c9 | 2014-01-24 23:05:45 +1000 | [diff] [blame] | 856 | stack.callback(raise_nested, exc4, exc5) |
| 857 | stack.callback(raise_nested, exc2, exc3) |
| 858 | raise exc1 |
| 859 | except Exception as exc: |
| 860 | self.assertIs(exc, exc5) |
| 861 | self.assertIs(exc.__context__, exc4) |
| 862 | self.assertIs(exc.__context__.__context__, exc3) |
| 863 | self.assertIs(exc.__context__.__context__.__context__, exc2) |
| 864 | self.assertIs( |
| 865 | exc.__context__.__context__.__context__.__context__, exc1) |
| 866 | self.assertIsNone( |
| 867 | exc.__context__.__context__.__context__.__context__.__context__) |
| 868 | |
Nick Coghlan | 1a33b2f | 2013-10-01 23:24:56 +1000 | [diff] [blame] | 869 | def test_body_exception_suppress(self): |
| 870 | def suppress_exc(*exc_details): |
| 871 | return True |
| 872 | try: |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 873 | with self.exit_stack() as stack: |
Nick Coghlan | 1a33b2f | 2013-10-01 23:24:56 +1000 | [diff] [blame] | 874 | stack.push(suppress_exc) |
| 875 | 1/0 |
| 876 | except IndexError as exc: |
| 877 | self.fail("Expected no exception, got IndexError") |
| 878 | |
Nick Coghlan | c73e8c2 | 2012-05-31 23:49:26 +1000 | [diff] [blame] | 879 | def test_exit_exception_chaining_suppress(self): |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 880 | with self.exit_stack() as stack: |
Nick Coghlan | c73e8c2 | 2012-05-31 23:49:26 +1000 | [diff] [blame] | 881 | stack.push(lambda *exc: True) |
| 882 | stack.push(lambda *exc: 1/0) |
| 883 | stack.push(lambda *exc: {}[1]) |
| 884 | |
Nick Coghlan | a5bd2a1 | 2012-06-01 00:00:38 +1000 | [diff] [blame] | 885 | def test_excessive_nesting(self): |
| 886 | # The original implementation would die with RecursionError here |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 887 | with self.exit_stack() as stack: |
Nick Coghlan | a5bd2a1 | 2012-06-01 00:00:38 +1000 | [diff] [blame] | 888 | for i in range(10000): |
| 889 | stack.callback(int) |
| 890 | |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 891 | def test_instance_bypass(self): |
| 892 | class Example(object): pass |
| 893 | cm = Example() |
| 894 | cm.__exit__ = object() |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 895 | stack = self.exit_stack() |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 896 | self.assertRaises(AttributeError, stack.enter_context, cm) |
| 897 | stack.push(cm) |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 898 | self.assertIs(stack._exit_callbacks[-1][1], cm) |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 899 | |
Gregory P. Smith | ba2ecd6 | 2016-06-14 09:19:20 -0700 | [diff] [blame] | 900 | def test_dont_reraise_RuntimeError(self): |
Serhiy Storchaka | ce1a9f3 | 2016-06-20 05:29:54 +0300 | [diff] [blame] | 901 | # https://bugs.python.org/issue27122 |
Gregory P. Smith | ba2ecd6 | 2016-06-14 09:19:20 -0700 | [diff] [blame] | 902 | class UniqueException(Exception): pass |
Serhiy Storchaka | ce1a9f3 | 2016-06-20 05:29:54 +0300 | [diff] [blame] | 903 | class UniqueRuntimeError(RuntimeError): pass |
Gregory P. Smith | ba2ecd6 | 2016-06-14 09:19:20 -0700 | [diff] [blame] | 904 | |
| 905 | @contextmanager |
| 906 | def second(): |
| 907 | try: |
| 908 | yield 1 |
| 909 | except Exception as exc: |
| 910 | raise UniqueException("new exception") from exc |
| 911 | |
| 912 | @contextmanager |
| 913 | def first(): |
| 914 | try: |
| 915 | yield 1 |
| 916 | except Exception as exc: |
| 917 | raise exc |
| 918 | |
Serhiy Storchaka | ce1a9f3 | 2016-06-20 05:29:54 +0300 | [diff] [blame] | 919 | # The UniqueRuntimeError should be caught by second()'s exception |
Gregory P. Smith | ba2ecd6 | 2016-06-14 09:19:20 -0700 | [diff] [blame] | 920 | # handler which chain raised a new UniqueException. |
| 921 | with self.assertRaises(UniqueException) as err_ctx: |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 922 | with self.exit_stack() as es_ctx: |
Gregory P. Smith | ba2ecd6 | 2016-06-14 09:19:20 -0700 | [diff] [blame] | 923 | es_ctx.enter_context(second()) |
| 924 | es_ctx.enter_context(first()) |
Serhiy Storchaka | ce1a9f3 | 2016-06-20 05:29:54 +0300 | [diff] [blame] | 925 | raise UniqueRuntimeError("please no infinite loop.") |
Gregory P. Smith | ba2ecd6 | 2016-06-14 09:19:20 -0700 | [diff] [blame] | 926 | |
Serhiy Storchaka | ce1a9f3 | 2016-06-20 05:29:54 +0300 | [diff] [blame] | 927 | exc = err_ctx.exception |
| 928 | self.assertIsInstance(exc, UniqueException) |
| 929 | self.assertIsInstance(exc.__context__, UniqueRuntimeError) |
| 930 | self.assertIsNone(exc.__context__.__context__) |
| 931 | self.assertIsNone(exc.__context__.__cause__) |
| 932 | self.assertIs(exc.__cause__, exc.__context__) |
Gregory P. Smith | ba2ecd6 | 2016-06-14 09:19:20 -0700 | [diff] [blame] | 933 | |
Berker Peksag | bb44fe0 | 2014-11-28 23:28:06 +0200 | [diff] [blame] | 934 | |
Ilya Kulakov | 1aa094f | 2018-01-25 12:51:18 -0800 | [diff] [blame] | 935 | class TestExitStack(TestBaseExitStack, unittest.TestCase): |
| 936 | exit_stack = ExitStack |
| 937 | |
| 938 | |
Berker Peksag | bb44fe0 | 2014-11-28 23:28:06 +0200 | [diff] [blame] | 939 | class TestRedirectStream: |
| 940 | |
| 941 | redirect_stream = None |
| 942 | orig_stream = None |
Raymond Hettinger | 088cbf2 | 2013-10-10 00:46:57 -0700 | [diff] [blame] | 943 | |
Nick Coghlan | 561eb5c | 2013-10-26 22:20:43 +1000 | [diff] [blame] | 944 | @support.requires_docstrings |
Nick Coghlan | 059def5 | 2013-10-26 18:08:15 +1000 | [diff] [blame] | 945 | def test_instance_docs(self): |
| 946 | # Issue 19330: ensure context manager instances have good docstrings |
Berker Peksag | bb44fe0 | 2014-11-28 23:28:06 +0200 | [diff] [blame] | 947 | cm_docstring = self.redirect_stream.__doc__ |
| 948 | obj = self.redirect_stream(None) |
Nick Coghlan | 059def5 | 2013-10-26 18:08:15 +1000 | [diff] [blame] | 949 | self.assertEqual(obj.__doc__, cm_docstring) |
| 950 | |
Nick Coghlan | 8e113b4 | 2013-11-03 17:00:51 +1000 | [diff] [blame] | 951 | def test_no_redirect_in_init(self): |
Berker Peksag | bb44fe0 | 2014-11-28 23:28:06 +0200 | [diff] [blame] | 952 | orig_stdout = getattr(sys, self.orig_stream) |
| 953 | self.redirect_stream(None) |
| 954 | self.assertIs(getattr(sys, self.orig_stream), orig_stdout) |
Nick Coghlan | 8e113b4 | 2013-11-03 17:00:51 +1000 | [diff] [blame] | 955 | |
Raymond Hettinger | 088cbf2 | 2013-10-10 00:46:57 -0700 | [diff] [blame] | 956 | def test_redirect_to_string_io(self): |
| 957 | f = io.StringIO() |
Nick Coghlan | 0ddaed3 | 2013-10-26 16:37:47 +1000 | [diff] [blame] | 958 | msg = "Consider an API like help(), which prints directly to stdout" |
Berker Peksag | bb44fe0 | 2014-11-28 23:28:06 +0200 | [diff] [blame] | 959 | orig_stdout = getattr(sys, self.orig_stream) |
| 960 | with self.redirect_stream(f): |
| 961 | print(msg, file=getattr(sys, self.orig_stream)) |
| 962 | self.assertIs(getattr(sys, self.orig_stream), orig_stdout) |
Nick Coghlan | 0ddaed3 | 2013-10-26 16:37:47 +1000 | [diff] [blame] | 963 | s = f.getvalue().strip() |
| 964 | self.assertEqual(s, msg) |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 965 | |
Nick Coghlan | 8608d26 | 2013-10-20 00:30:51 +1000 | [diff] [blame] | 966 | def test_enter_result_is_target(self): |
| 967 | f = io.StringIO() |
Berker Peksag | bb44fe0 | 2014-11-28 23:28:06 +0200 | [diff] [blame] | 968 | with self.redirect_stream(f) as enter_result: |
Nick Coghlan | 8608d26 | 2013-10-20 00:30:51 +1000 | [diff] [blame] | 969 | self.assertIs(enter_result, f) |
| 970 | |
| 971 | def test_cm_is_reusable(self): |
| 972 | f = io.StringIO() |
Berker Peksag | bb44fe0 | 2014-11-28 23:28:06 +0200 | [diff] [blame] | 973 | write_to_f = self.redirect_stream(f) |
| 974 | orig_stdout = getattr(sys, self.orig_stream) |
Nick Coghlan | 8608d26 | 2013-10-20 00:30:51 +1000 | [diff] [blame] | 975 | with write_to_f: |
Berker Peksag | bb44fe0 | 2014-11-28 23:28:06 +0200 | [diff] [blame] | 976 | print("Hello", end=" ", file=getattr(sys, self.orig_stream)) |
Nick Coghlan | 8608d26 | 2013-10-20 00:30:51 +1000 | [diff] [blame] | 977 | with write_to_f: |
Berker Peksag | bb44fe0 | 2014-11-28 23:28:06 +0200 | [diff] [blame] | 978 | print("World!", file=getattr(sys, self.orig_stream)) |
| 979 | self.assertIs(getattr(sys, self.orig_stream), orig_stdout) |
Nick Coghlan | 8608d26 | 2013-10-20 00:30:51 +1000 | [diff] [blame] | 980 | s = f.getvalue() |
| 981 | self.assertEqual(s, "Hello World!\n") |
| 982 | |
Nick Coghlan | 8e113b4 | 2013-11-03 17:00:51 +1000 | [diff] [blame] | 983 | def test_cm_is_reentrant(self): |
Nick Coghlan | 8608d26 | 2013-10-20 00:30:51 +1000 | [diff] [blame] | 984 | f = io.StringIO() |
Berker Peksag | bb44fe0 | 2014-11-28 23:28:06 +0200 | [diff] [blame] | 985 | write_to_f = self.redirect_stream(f) |
| 986 | orig_stdout = getattr(sys, self.orig_stream) |
Nick Coghlan | 8e113b4 | 2013-11-03 17:00:51 +1000 | [diff] [blame] | 987 | with write_to_f: |
Berker Peksag | bb44fe0 | 2014-11-28 23:28:06 +0200 | [diff] [blame] | 988 | print("Hello", end=" ", file=getattr(sys, self.orig_stream)) |
Nick Coghlan | 8608d26 | 2013-10-20 00:30:51 +1000 | [diff] [blame] | 989 | with write_to_f: |
Berker Peksag | bb44fe0 | 2014-11-28 23:28:06 +0200 | [diff] [blame] | 990 | print("World!", file=getattr(sys, self.orig_stream)) |
| 991 | self.assertIs(getattr(sys, self.orig_stream), orig_stdout) |
Nick Coghlan | 8e113b4 | 2013-11-03 17:00:51 +1000 | [diff] [blame] | 992 | s = f.getvalue() |
| 993 | self.assertEqual(s, "Hello World!\n") |
Nick Coghlan | 8608d26 | 2013-10-20 00:30:51 +1000 | [diff] [blame] | 994 | |
| 995 | |
Berker Peksag | bb44fe0 | 2014-11-28 23:28:06 +0200 | [diff] [blame] | 996 | class TestRedirectStdout(TestRedirectStream, unittest.TestCase): |
| 997 | |
| 998 | redirect_stream = redirect_stdout |
| 999 | orig_stream = "stdout" |
| 1000 | |
| 1001 | |
| 1002 | class TestRedirectStderr(TestRedirectStream, unittest.TestCase): |
| 1003 | |
| 1004 | redirect_stream = redirect_stderr |
| 1005 | orig_stream = "stderr" |
| 1006 | |
| 1007 | |
Nick Coghlan | 240f86d | 2013-10-17 23:40:57 +1000 | [diff] [blame] | 1008 | class TestSuppress(unittest.TestCase): |
| 1009 | |
Nick Coghlan | 561eb5c | 2013-10-26 22:20:43 +1000 | [diff] [blame] | 1010 | @support.requires_docstrings |
Nick Coghlan | 059def5 | 2013-10-26 18:08:15 +1000 | [diff] [blame] | 1011 | def test_instance_docs(self): |
| 1012 | # Issue 19330: ensure context manager instances have good docstrings |
| 1013 | cm_docstring = suppress.__doc__ |
| 1014 | obj = suppress() |
| 1015 | self.assertEqual(obj.__doc__, cm_docstring) |
| 1016 | |
Nick Coghlan | 8608d26 | 2013-10-20 00:30:51 +1000 | [diff] [blame] | 1017 | def test_no_result_from_enter(self): |
| 1018 | with suppress(ValueError) as enter_result: |
| 1019 | self.assertIsNone(enter_result) |
Nick Coghlan | 240f86d | 2013-10-17 23:40:57 +1000 | [diff] [blame] | 1020 | |
Nick Coghlan | 8608d26 | 2013-10-20 00:30:51 +1000 | [diff] [blame] | 1021 | def test_no_exception(self): |
Nick Coghlan | 240f86d | 2013-10-17 23:40:57 +1000 | [diff] [blame] | 1022 | with suppress(ValueError): |
| 1023 | self.assertEqual(pow(2, 5), 32) |
| 1024 | |
| 1025 | def test_exact_exception(self): |
Nick Coghlan | 240f86d | 2013-10-17 23:40:57 +1000 | [diff] [blame] | 1026 | with suppress(TypeError): |
| 1027 | len(5) |
| 1028 | |
Nick Coghlan | 059def5 | 2013-10-26 18:08:15 +1000 | [diff] [blame] | 1029 | def test_exception_hierarchy(self): |
| 1030 | with suppress(LookupError): |
| 1031 | 'Hello'[50] |
| 1032 | |
| 1033 | def test_other_exception(self): |
| 1034 | with self.assertRaises(ZeroDivisionError): |
| 1035 | with suppress(TypeError): |
| 1036 | 1/0 |
| 1037 | |
| 1038 | def test_no_args(self): |
| 1039 | with self.assertRaises(ZeroDivisionError): |
| 1040 | with suppress(): |
| 1041 | 1/0 |
| 1042 | |
Nick Coghlan | 240f86d | 2013-10-17 23:40:57 +1000 | [diff] [blame] | 1043 | def test_multiple_exception_args(self): |
Nick Coghlan | 8608d26 | 2013-10-20 00:30:51 +1000 | [diff] [blame] | 1044 | with suppress(ZeroDivisionError, TypeError): |
| 1045 | 1/0 |
Nick Coghlan | 240f86d | 2013-10-17 23:40:57 +1000 | [diff] [blame] | 1046 | with suppress(ZeroDivisionError, TypeError): |
| 1047 | len(5) |
| 1048 | |
Nick Coghlan | 8608d26 | 2013-10-20 00:30:51 +1000 | [diff] [blame] | 1049 | def test_cm_is_reentrant(self): |
| 1050 | ignore_exceptions = suppress(Exception) |
| 1051 | with ignore_exceptions: |
| 1052 | pass |
| 1053 | with ignore_exceptions: |
| 1054 | len(5) |
| 1055 | with ignore_exceptions: |
Nick Coghlan | 8608d26 | 2013-10-20 00:30:51 +1000 | [diff] [blame] | 1056 | with ignore_exceptions: # Check nested usage |
| 1057 | len(5) |
Martin Panter | 7c6420a | 2015-10-10 11:04:44 +0000 | [diff] [blame] | 1058 | outer_continued = True |
| 1059 | 1/0 |
| 1060 | self.assertTrue(outer_continued) |
Nick Coghlan | 8608d26 | 2013-10-20 00:30:51 +1000 | [diff] [blame] | 1061 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 1062 | if __name__ == "__main__": |
Brett Cannon | 3e9a9ae | 2013-06-12 21:25:59 -0400 | [diff] [blame] | 1063 | unittest.main() |