Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | |
| 3 | """Unit tests for the with statement specified in PEP 343.""" |
| 4 | |
Thomas Wouters | 34aa7ba | 2006-02-28 19:02:24 +0000 | [diff] [blame] | 5 | |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 6 | __author__ = "Mike Bland" |
| 7 | __email__ = "mbland at acm dot org" |
| 8 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 9 | import sys |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 10 | import unittest |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 11 | from collections import deque |
| 12 | from contextlib import GeneratorContextManager, contextmanager |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 13 | from test.support import run_unittest |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 14 | |
| 15 | |
| 16 | class MockContextManager(GeneratorContextManager): |
| 17 | def __init__(self, gen): |
| 18 | GeneratorContextManager.__init__(self, gen) |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 19 | self.enter_called = False |
| 20 | self.exit_called = False |
| 21 | self.exit_args = None |
| 22 | |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 23 | def __enter__(self): |
| 24 | self.enter_called = True |
| 25 | return GeneratorContextManager.__enter__(self) |
| 26 | |
| 27 | def __exit__(self, type, value, traceback): |
| 28 | self.exit_called = True |
| 29 | self.exit_args = (type, value, traceback) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 30 | return GeneratorContextManager.__exit__(self, type, |
| 31 | value, traceback) |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 32 | |
| 33 | |
| 34 | def mock_contextmanager(func): |
| 35 | def helper(*args, **kwds): |
| 36 | return MockContextManager(func(*args, **kwds)) |
| 37 | return helper |
| 38 | |
| 39 | |
| 40 | class MockResource(object): |
| 41 | def __init__(self): |
| 42 | self.yielded = False |
| 43 | self.stopped = False |
| 44 | |
| 45 | |
| 46 | @mock_contextmanager |
| 47 | def mock_contextmanager_generator(): |
| 48 | mock = MockResource() |
| 49 | try: |
| 50 | mock.yielded = True |
| 51 | yield mock |
| 52 | finally: |
| 53 | mock.stopped = True |
| 54 | |
| 55 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 56 | class Nested(object): |
| 57 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 58 | def __init__(self, *managers): |
| 59 | self.managers = managers |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 60 | self.entered = None |
| 61 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 62 | def __enter__(self): |
| 63 | if self.entered is not None: |
| 64 | raise RuntimeError("Context is not reentrant") |
| 65 | self.entered = deque() |
| 66 | vars = [] |
| 67 | try: |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 68 | for mgr in self.managers: |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 69 | vars.append(mgr.__enter__()) |
| 70 | self.entered.appendleft(mgr) |
| 71 | except: |
Guido van Rossum | f669436 | 2006-03-10 02:28:35 +0000 | [diff] [blame] | 72 | if not self.__exit__(*sys.exc_info()): |
| 73 | raise |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 74 | return vars |
| 75 | |
| 76 | def __exit__(self, *exc_info): |
| 77 | # Behave like nested with statements |
| 78 | # first in, last out |
| 79 | # New exceptions override old ones |
| 80 | ex = exc_info |
| 81 | for mgr in self.entered: |
| 82 | try: |
Guido van Rossum | f669436 | 2006-03-10 02:28:35 +0000 | [diff] [blame] | 83 | if mgr.__exit__(*ex): |
| 84 | ex = (None, None, None) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 85 | except: |
| 86 | ex = sys.exc_info() |
| 87 | self.entered = None |
| 88 | if ex is not exc_info: |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 89 | raise ex[0](ex[1]).with_traceback(ex[2]) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 90 | |
| 91 | |
| 92 | class MockNested(Nested): |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 93 | def __init__(self, *managers): |
| 94 | Nested.__init__(self, *managers) |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 95 | self.enter_called = False |
| 96 | self.exit_called = False |
| 97 | self.exit_args = None |
| 98 | |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 99 | def __enter__(self): |
| 100 | self.enter_called = True |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 101 | return Nested.__enter__(self) |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 102 | |
| 103 | def __exit__(self, *exc_info): |
| 104 | self.exit_called = True |
| 105 | self.exit_args = exc_info |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 106 | return Nested.__exit__(self, *exc_info) |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 107 | |
| 108 | |
| 109 | class FailureTestCase(unittest.TestCase): |
| 110 | def testNameError(self): |
| 111 | def fooNotDeclared(): |
| 112 | with foo: pass |
| 113 | self.assertRaises(NameError, fooNotDeclared) |
| 114 | |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 115 | def testEnterAttributeError(self): |
| 116 | class LacksEnter(object): |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 117 | def __exit__(self, type, value, traceback): |
| 118 | pass |
| 119 | |
| 120 | def fooLacksEnter(): |
| 121 | foo = LacksEnter() |
| 122 | with foo: pass |
| 123 | self.assertRaises(AttributeError, fooLacksEnter) |
| 124 | |
| 125 | def testExitAttributeError(self): |
| 126 | class LacksExit(object): |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 127 | def __enter__(self): |
| 128 | pass |
| 129 | |
| 130 | def fooLacksExit(): |
| 131 | foo = LacksExit() |
| 132 | with foo: pass |
| 133 | self.assertRaises(AttributeError, fooLacksExit) |
| 134 | |
| 135 | def assertRaisesSyntaxError(self, codestr): |
| 136 | def shouldRaiseSyntaxError(s): |
| 137 | compile(s, '', 'single') |
| 138 | self.assertRaises(SyntaxError, shouldRaiseSyntaxError, codestr) |
| 139 | |
| 140 | def testAssignmentToNoneError(self): |
| 141 | self.assertRaisesSyntaxError('with mock as None:\n pass') |
| 142 | self.assertRaisesSyntaxError( |
| 143 | 'with mock as (None):\n' |
| 144 | ' pass') |
| 145 | |
| 146 | def testAssignmentToEmptyTupleError(self): |
| 147 | self.assertRaisesSyntaxError( |
| 148 | 'with mock as ():\n' |
| 149 | ' pass') |
| 150 | |
| 151 | def testAssignmentToTupleOnlyContainingNoneError(self): |
| 152 | self.assertRaisesSyntaxError('with mock as None,:\n pass') |
| 153 | self.assertRaisesSyntaxError( |
| 154 | 'with mock as (None,):\n' |
| 155 | ' pass') |
| 156 | |
| 157 | def testAssignmentToTupleContainingNoneError(self): |
| 158 | self.assertRaisesSyntaxError( |
| 159 | 'with mock as (foo, None, bar):\n' |
| 160 | ' pass') |
| 161 | |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 162 | def testEnterThrows(self): |
| 163 | class EnterThrows(object): |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 164 | def __enter__(self): |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 165 | raise RuntimeError("Enter threw") |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 166 | def __exit__(self, *args): |
| 167 | pass |
| 168 | |
| 169 | def shouldThrow(): |
| 170 | ct = EnterThrows() |
| 171 | self.foo = None |
| 172 | with ct as self.foo: |
| 173 | pass |
| 174 | self.assertRaises(RuntimeError, shouldThrow) |
| 175 | self.assertEqual(self.foo, None) |
| 176 | |
| 177 | def testExitThrows(self): |
| 178 | class ExitThrows(object): |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 179 | def __enter__(self): |
| 180 | return |
| 181 | def __exit__(self, *args): |
| 182 | raise RuntimeError(42) |
| 183 | def shouldThrow(): |
| 184 | with ExitThrows(): |
| 185 | pass |
| 186 | self.assertRaises(RuntimeError, shouldThrow) |
| 187 | |
| 188 | class ContextmanagerAssertionMixin(object): |
Collin Winter | ba21f61 | 2007-09-01 20:29:04 +0000 | [diff] [blame] | 189 | |
| 190 | def setUp(self): |
| 191 | self.TEST_EXCEPTION = RuntimeError("test exception") |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 192 | |
| 193 | def assertInWithManagerInvariants(self, mock_manager): |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 194 | self.assertTrue(mock_manager.enter_called) |
| 195 | self.assertFalse(mock_manager.exit_called) |
| 196 | self.assertEqual(mock_manager.exit_args, None) |
| 197 | |
| 198 | def assertAfterWithManagerInvariants(self, mock_manager, exit_args): |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 199 | self.assertTrue(mock_manager.enter_called) |
| 200 | self.assertTrue(mock_manager.exit_called) |
| 201 | self.assertEqual(mock_manager.exit_args, exit_args) |
| 202 | |
| 203 | def assertAfterWithManagerInvariantsNoError(self, mock_manager): |
| 204 | self.assertAfterWithManagerInvariants(mock_manager, |
| 205 | (None, None, None)) |
| 206 | |
| 207 | def assertInWithGeneratorInvariants(self, mock_generator): |
| 208 | self.assertTrue(mock_generator.yielded) |
| 209 | self.assertFalse(mock_generator.stopped) |
| 210 | |
| 211 | def assertAfterWithGeneratorInvariantsNoError(self, mock_generator): |
| 212 | self.assertTrue(mock_generator.yielded) |
| 213 | self.assertTrue(mock_generator.stopped) |
| 214 | |
| 215 | def raiseTestException(self): |
| 216 | raise self.TEST_EXCEPTION |
| 217 | |
| 218 | def assertAfterWithManagerInvariantsWithError(self, mock_manager): |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 219 | self.assertTrue(mock_manager.enter_called) |
| 220 | self.assertTrue(mock_manager.exit_called) |
| 221 | self.assertEqual(mock_manager.exit_args[0], RuntimeError) |
| 222 | self.assertEqual(mock_manager.exit_args[1], self.TEST_EXCEPTION) |
| 223 | |
| 224 | def assertAfterWithGeneratorInvariantsWithError(self, mock_generator): |
| 225 | self.assertTrue(mock_generator.yielded) |
| 226 | self.assertTrue(mock_generator.stopped) |
| 227 | |
| 228 | |
| 229 | class NonexceptionalTestCase(unittest.TestCase, ContextmanagerAssertionMixin): |
| 230 | def testInlineGeneratorSyntax(self): |
| 231 | with mock_contextmanager_generator(): |
| 232 | pass |
| 233 | |
| 234 | def testUnboundGenerator(self): |
| 235 | mock = mock_contextmanager_generator() |
| 236 | with mock: |
| 237 | pass |
| 238 | self.assertAfterWithManagerInvariantsNoError(mock) |
| 239 | |
| 240 | def testInlineGeneratorBoundSyntax(self): |
| 241 | with mock_contextmanager_generator() as foo: |
| 242 | self.assertInWithGeneratorInvariants(foo) |
| 243 | # FIXME: In the future, we'll try to keep the bound names from leaking |
| 244 | self.assertAfterWithGeneratorInvariantsNoError(foo) |
| 245 | |
| 246 | def testInlineGeneratorBoundToExistingVariable(self): |
| 247 | foo = None |
| 248 | with mock_contextmanager_generator() as foo: |
| 249 | self.assertInWithGeneratorInvariants(foo) |
| 250 | self.assertAfterWithGeneratorInvariantsNoError(foo) |
| 251 | |
| 252 | def testInlineGeneratorBoundToDottedVariable(self): |
| 253 | with mock_contextmanager_generator() as self.foo: |
| 254 | self.assertInWithGeneratorInvariants(self.foo) |
| 255 | self.assertAfterWithGeneratorInvariantsNoError(self.foo) |
| 256 | |
| 257 | def testBoundGenerator(self): |
| 258 | mock = mock_contextmanager_generator() |
| 259 | with mock as foo: |
| 260 | self.assertInWithGeneratorInvariants(foo) |
| 261 | self.assertInWithManagerInvariants(mock) |
| 262 | self.assertAfterWithGeneratorInvariantsNoError(foo) |
| 263 | self.assertAfterWithManagerInvariantsNoError(mock) |
| 264 | |
| 265 | def testNestedSingleStatements(self): |
| 266 | mock_a = mock_contextmanager_generator() |
| 267 | with mock_a as foo: |
| 268 | mock_b = mock_contextmanager_generator() |
| 269 | with mock_b as bar: |
| 270 | self.assertInWithManagerInvariants(mock_a) |
| 271 | self.assertInWithManagerInvariants(mock_b) |
| 272 | self.assertInWithGeneratorInvariants(foo) |
| 273 | self.assertInWithGeneratorInvariants(bar) |
| 274 | self.assertAfterWithManagerInvariantsNoError(mock_b) |
| 275 | self.assertAfterWithGeneratorInvariantsNoError(bar) |
| 276 | self.assertInWithManagerInvariants(mock_a) |
| 277 | self.assertInWithGeneratorInvariants(foo) |
| 278 | self.assertAfterWithManagerInvariantsNoError(mock_a) |
| 279 | self.assertAfterWithGeneratorInvariantsNoError(foo) |
| 280 | |
| 281 | |
| 282 | class NestedNonexceptionalTestCase(unittest.TestCase, |
| 283 | ContextmanagerAssertionMixin): |
| 284 | def testSingleArgInlineGeneratorSyntax(self): |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 285 | with Nested(mock_contextmanager_generator()): |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 286 | pass |
| 287 | |
| 288 | def testSingleArgUnbound(self): |
| 289 | mock_contextmanager = mock_contextmanager_generator() |
| 290 | mock_nested = MockNested(mock_contextmanager) |
| 291 | with mock_nested: |
| 292 | self.assertInWithManagerInvariants(mock_contextmanager) |
| 293 | self.assertInWithManagerInvariants(mock_nested) |
| 294 | self.assertAfterWithManagerInvariantsNoError(mock_contextmanager) |
| 295 | self.assertAfterWithManagerInvariantsNoError(mock_nested) |
| 296 | |
| 297 | def testSingleArgBoundToNonTuple(self): |
| 298 | m = mock_contextmanager_generator() |
| 299 | # This will bind all the arguments to nested() into a single list |
| 300 | # assigned to foo. |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 301 | with Nested(m) as foo: |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 302 | self.assertInWithManagerInvariants(m) |
| 303 | self.assertAfterWithManagerInvariantsNoError(m) |
| 304 | |
| 305 | def testSingleArgBoundToSingleElementParenthesizedList(self): |
| 306 | m = mock_contextmanager_generator() |
| 307 | # This will bind all the arguments to nested() into a single list |
| 308 | # assigned to foo. |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 309 | with Nested(m) as (foo): |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 310 | self.assertInWithManagerInvariants(m) |
| 311 | self.assertAfterWithManagerInvariantsNoError(m) |
| 312 | |
| 313 | def testSingleArgBoundToMultipleElementTupleError(self): |
| 314 | def shouldThrowValueError(): |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 315 | with Nested(mock_contextmanager_generator()) as (foo, bar): |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 316 | pass |
| 317 | self.assertRaises(ValueError, shouldThrowValueError) |
| 318 | |
| 319 | def testSingleArgUnbound(self): |
| 320 | mock_contextmanager = mock_contextmanager_generator() |
| 321 | mock_nested = MockNested(mock_contextmanager) |
| 322 | with mock_nested: |
| 323 | self.assertInWithManagerInvariants(mock_contextmanager) |
| 324 | self.assertInWithManagerInvariants(mock_nested) |
| 325 | self.assertAfterWithManagerInvariantsNoError(mock_contextmanager) |
| 326 | self.assertAfterWithManagerInvariantsNoError(mock_nested) |
| 327 | |
| 328 | def testMultipleArgUnbound(self): |
| 329 | m = mock_contextmanager_generator() |
| 330 | n = mock_contextmanager_generator() |
| 331 | o = mock_contextmanager_generator() |
| 332 | mock_nested = MockNested(m, n, o) |
| 333 | with mock_nested: |
| 334 | self.assertInWithManagerInvariants(m) |
| 335 | self.assertInWithManagerInvariants(n) |
| 336 | self.assertInWithManagerInvariants(o) |
| 337 | self.assertInWithManagerInvariants(mock_nested) |
| 338 | self.assertAfterWithManagerInvariantsNoError(m) |
| 339 | self.assertAfterWithManagerInvariantsNoError(n) |
| 340 | self.assertAfterWithManagerInvariantsNoError(o) |
| 341 | self.assertAfterWithManagerInvariantsNoError(mock_nested) |
| 342 | |
| 343 | def testMultipleArgBound(self): |
| 344 | mock_nested = MockNested(mock_contextmanager_generator(), |
| 345 | mock_contextmanager_generator(), mock_contextmanager_generator()) |
| 346 | with mock_nested as (m, n, o): |
| 347 | self.assertInWithGeneratorInvariants(m) |
| 348 | self.assertInWithGeneratorInvariants(n) |
| 349 | self.assertInWithGeneratorInvariants(o) |
| 350 | self.assertInWithManagerInvariants(mock_nested) |
| 351 | self.assertAfterWithGeneratorInvariantsNoError(m) |
| 352 | self.assertAfterWithGeneratorInvariantsNoError(n) |
| 353 | self.assertAfterWithGeneratorInvariantsNoError(o) |
| 354 | self.assertAfterWithManagerInvariantsNoError(mock_nested) |
| 355 | |
| 356 | |
Collin Winter | ba21f61 | 2007-09-01 20:29:04 +0000 | [diff] [blame] | 357 | class ExceptionalTestCase(ContextmanagerAssertionMixin, unittest.TestCase): |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 358 | def testSingleResource(self): |
| 359 | cm = mock_contextmanager_generator() |
| 360 | def shouldThrow(): |
| 361 | with cm as self.resource: |
| 362 | self.assertInWithManagerInvariants(cm) |
| 363 | self.assertInWithGeneratorInvariants(self.resource) |
| 364 | self.raiseTestException() |
| 365 | self.assertRaises(RuntimeError, shouldThrow) |
| 366 | self.assertAfterWithManagerInvariantsWithError(cm) |
| 367 | self.assertAfterWithGeneratorInvariantsWithError(self.resource) |
| 368 | |
| 369 | def testNestedSingleStatements(self): |
| 370 | mock_a = mock_contextmanager_generator() |
| 371 | mock_b = mock_contextmanager_generator() |
| 372 | def shouldThrow(): |
| 373 | with mock_a as self.foo: |
| 374 | with mock_b as self.bar: |
| 375 | self.assertInWithManagerInvariants(mock_a) |
| 376 | self.assertInWithManagerInvariants(mock_b) |
| 377 | self.assertInWithGeneratorInvariants(self.foo) |
| 378 | self.assertInWithGeneratorInvariants(self.bar) |
| 379 | self.raiseTestException() |
| 380 | self.assertRaises(RuntimeError, shouldThrow) |
| 381 | self.assertAfterWithManagerInvariantsWithError(mock_a) |
| 382 | self.assertAfterWithManagerInvariantsWithError(mock_b) |
| 383 | self.assertAfterWithGeneratorInvariantsWithError(self.foo) |
| 384 | self.assertAfterWithGeneratorInvariantsWithError(self.bar) |
| 385 | |
| 386 | def testMultipleResourcesInSingleStatement(self): |
| 387 | cm_a = mock_contextmanager_generator() |
| 388 | cm_b = mock_contextmanager_generator() |
| 389 | mock_nested = MockNested(cm_a, cm_b) |
| 390 | def shouldThrow(): |
| 391 | with mock_nested as (self.resource_a, self.resource_b): |
| 392 | self.assertInWithManagerInvariants(cm_a) |
| 393 | self.assertInWithManagerInvariants(cm_b) |
| 394 | self.assertInWithManagerInvariants(mock_nested) |
| 395 | self.assertInWithGeneratorInvariants(self.resource_a) |
| 396 | self.assertInWithGeneratorInvariants(self.resource_b) |
| 397 | self.raiseTestException() |
| 398 | self.assertRaises(RuntimeError, shouldThrow) |
| 399 | self.assertAfterWithManagerInvariantsWithError(cm_a) |
| 400 | self.assertAfterWithManagerInvariantsWithError(cm_b) |
| 401 | self.assertAfterWithManagerInvariantsWithError(mock_nested) |
| 402 | self.assertAfterWithGeneratorInvariantsWithError(self.resource_a) |
| 403 | self.assertAfterWithGeneratorInvariantsWithError(self.resource_b) |
| 404 | |
| 405 | def testNestedExceptionBeforeInnerStatement(self): |
| 406 | mock_a = mock_contextmanager_generator() |
| 407 | mock_b = mock_contextmanager_generator() |
| 408 | self.bar = None |
| 409 | def shouldThrow(): |
| 410 | with mock_a as self.foo: |
| 411 | self.assertInWithManagerInvariants(mock_a) |
| 412 | self.assertInWithGeneratorInvariants(self.foo) |
| 413 | self.raiseTestException() |
| 414 | with mock_b as self.bar: |
| 415 | pass |
| 416 | self.assertRaises(RuntimeError, shouldThrow) |
| 417 | self.assertAfterWithManagerInvariantsWithError(mock_a) |
| 418 | self.assertAfterWithGeneratorInvariantsWithError(self.foo) |
| 419 | |
| 420 | # The inner statement stuff should never have been touched |
| 421 | self.assertEqual(self.bar, None) |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 422 | self.assertFalse(mock_b.enter_called) |
| 423 | self.assertFalse(mock_b.exit_called) |
| 424 | self.assertEqual(mock_b.exit_args, None) |
| 425 | |
| 426 | def testNestedExceptionAfterInnerStatement(self): |
| 427 | mock_a = mock_contextmanager_generator() |
| 428 | mock_b = mock_contextmanager_generator() |
| 429 | def shouldThrow(): |
| 430 | with mock_a as self.foo: |
| 431 | with mock_b as self.bar: |
| 432 | self.assertInWithManagerInvariants(mock_a) |
| 433 | self.assertInWithManagerInvariants(mock_b) |
| 434 | self.assertInWithGeneratorInvariants(self.foo) |
| 435 | self.assertInWithGeneratorInvariants(self.bar) |
| 436 | self.raiseTestException() |
| 437 | self.assertRaises(RuntimeError, shouldThrow) |
| 438 | self.assertAfterWithManagerInvariantsWithError(mock_a) |
| 439 | self.assertAfterWithManagerInvariantsNoError(mock_b) |
| 440 | self.assertAfterWithGeneratorInvariantsWithError(self.foo) |
| 441 | self.assertAfterWithGeneratorInvariantsNoError(self.bar) |
| 442 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 443 | def testRaisedStopIteration1(self): |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 444 | # From bug 1462485 |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 445 | @contextmanager |
| 446 | def cm(): |
| 447 | yield |
| 448 | |
| 449 | def shouldThrow(): |
| 450 | with cm(): |
| 451 | raise StopIteration("from with") |
| 452 | |
| 453 | self.assertRaises(StopIteration, shouldThrow) |
| 454 | |
| 455 | def testRaisedStopIteration2(self): |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 456 | # From bug 1462485 |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 457 | class cm(object): |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 458 | def __enter__(self): |
| 459 | pass |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 460 | def __exit__(self, type, value, traceback): |
| 461 | pass |
| 462 | |
| 463 | def shouldThrow(): |
| 464 | with cm(): |
| 465 | raise StopIteration("from with") |
| 466 | |
| 467 | self.assertRaises(StopIteration, shouldThrow) |
| 468 | |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 469 | def testRaisedStopIteration3(self): |
| 470 | # Another variant where the exception hasn't been instantiated |
| 471 | # From bug 1705170 |
| 472 | @contextmanager |
| 473 | def cm(): |
| 474 | yield |
| 475 | |
| 476 | def shouldThrow(): |
| 477 | with cm(): |
| 478 | raise next(iter([])) |
| 479 | |
| 480 | self.assertRaises(StopIteration, shouldThrow) |
| 481 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 482 | def testRaisedGeneratorExit1(self): |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 483 | # From bug 1462485 |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 484 | @contextmanager |
| 485 | def cm(): |
| 486 | yield |
| 487 | |
| 488 | def shouldThrow(): |
| 489 | with cm(): |
| 490 | raise GeneratorExit("from with") |
| 491 | |
| 492 | self.assertRaises(GeneratorExit, shouldThrow) |
| 493 | |
| 494 | def testRaisedGeneratorExit2(self): |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 495 | # From bug 1462485 |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 496 | class cm (object): |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 497 | def __enter__(self): |
| 498 | pass |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 499 | def __exit__(self, type, value, traceback): |
| 500 | pass |
| 501 | |
| 502 | def shouldThrow(): |
| 503 | with cm(): |
| 504 | raise GeneratorExit("from with") |
| 505 | |
| 506 | self.assertRaises(GeneratorExit, shouldThrow) |
| 507 | |
Amaury Forgeot d'Arc | 10b24e8 | 2008-12-10 23:49:33 +0000 | [diff] [blame] | 508 | def testErrorsInBool(self): |
| 509 | # issue4589: __exit__ return code may raise an exception |
| 510 | # when looking at its truth value. |
| 511 | |
| 512 | class cm(object): |
| 513 | def __init__(self, bool_conversion): |
| 514 | class Bool: |
| 515 | def __bool__(self): |
| 516 | return bool_conversion() |
| 517 | self.exit_result = Bool() |
| 518 | def __enter__(self): |
| 519 | return 3 |
| 520 | def __exit__(self, a, b, c): |
| 521 | return self.exit_result |
| 522 | |
| 523 | def trueAsBool(): |
| 524 | with cm(lambda: True): |
| 525 | self.fail("Should NOT see this") |
| 526 | trueAsBool() |
| 527 | |
| 528 | def falseAsBool(): |
| 529 | with cm(lambda: False): |
| 530 | self.fail("Should raise") |
| 531 | self.assertRaises(AssertionError, falseAsBool) |
| 532 | |
| 533 | def failAsBool(): |
| 534 | with cm(lambda: 1//0): |
| 535 | self.fail("Should NOT see this") |
| 536 | self.assertRaises(ZeroDivisionError, failAsBool) |
| 537 | |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 538 | |
| 539 | class NonLocalFlowControlTestCase(unittest.TestCase): |
| 540 | |
| 541 | def testWithBreak(self): |
| 542 | counter = 0 |
| 543 | while True: |
| 544 | counter += 1 |
| 545 | with mock_contextmanager_generator(): |
| 546 | counter += 10 |
| 547 | break |
| 548 | counter += 100 # Not reached |
| 549 | self.assertEqual(counter, 11) |
| 550 | |
| 551 | def testWithContinue(self): |
| 552 | counter = 0 |
| 553 | while True: |
| 554 | counter += 1 |
| 555 | if counter > 2: |
| 556 | break |
| 557 | with mock_contextmanager_generator(): |
| 558 | counter += 10 |
| 559 | continue |
| 560 | counter += 100 # Not reached |
| 561 | self.assertEqual(counter, 12) |
| 562 | |
| 563 | def testWithReturn(self): |
| 564 | def foo(): |
| 565 | counter = 0 |
| 566 | while True: |
| 567 | counter += 1 |
| 568 | with mock_contextmanager_generator(): |
| 569 | counter += 10 |
| 570 | return counter |
| 571 | counter += 100 # Not reached |
| 572 | self.assertEqual(foo(), 11) |
| 573 | |
| 574 | def testWithYield(self): |
| 575 | def gen(): |
| 576 | with mock_contextmanager_generator(): |
| 577 | yield 12 |
| 578 | yield 13 |
| 579 | x = list(gen()) |
| 580 | self.assertEqual(x, [12, 13]) |
| 581 | |
| 582 | def testWithRaise(self): |
| 583 | counter = 0 |
| 584 | try: |
| 585 | counter += 1 |
| 586 | with mock_contextmanager_generator(): |
| 587 | counter += 10 |
| 588 | raise RuntimeError |
| 589 | counter += 100 # Not reached |
| 590 | except RuntimeError: |
| 591 | self.assertEqual(counter, 11) |
| 592 | else: |
| 593 | self.fail("Didn't raise RuntimeError") |
| 594 | |
| 595 | |
| 596 | class AssignmentTargetTestCase(unittest.TestCase): |
| 597 | |
| 598 | def testSingleComplexTarget(self): |
| 599 | targets = {1: [0, 1, 2]} |
| 600 | with mock_contextmanager_generator() as targets[1][0]: |
Guido van Rossum | 87b6395 | 2007-02-11 07:05:21 +0000 | [diff] [blame] | 601 | self.assertEqual(list(targets.keys()), [1]) |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 602 | self.assertEqual(targets[1][0].__class__, MockResource) |
Guido van Rossum | 87b6395 | 2007-02-11 07:05:21 +0000 | [diff] [blame] | 603 | with mock_contextmanager_generator() as list(targets.values())[0][1]: |
| 604 | self.assertEqual(list(targets.keys()), [1]) |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 605 | self.assertEqual(targets[1][1].__class__, MockResource) |
| 606 | with mock_contextmanager_generator() as targets[2]: |
Guido van Rossum | 87b6395 | 2007-02-11 07:05:21 +0000 | [diff] [blame] | 607 | keys = list(targets.keys()) |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 608 | keys.sort() |
| 609 | self.assertEqual(keys, [1, 2]) |
| 610 | class C: pass |
| 611 | blah = C() |
| 612 | with mock_contextmanager_generator() as blah.foo: |
| 613 | self.assertEqual(hasattr(blah, "foo"), True) |
| 614 | |
| 615 | def testMultipleComplexTargets(self): |
| 616 | class C: |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 617 | def __enter__(self): return 1, 2, 3 |
Guido van Rossum | f669436 | 2006-03-10 02:28:35 +0000 | [diff] [blame] | 618 | def __exit__(self, t, v, tb): pass |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 619 | targets = {1: [0, 1, 2]} |
| 620 | with C() as (targets[1][0], targets[1][1], targets[1][2]): |
| 621 | self.assertEqual(targets, {1: [1, 2, 3]}) |
Guido van Rossum | 87b6395 | 2007-02-11 07:05:21 +0000 | [diff] [blame] | 622 | with C() as (list(targets.values())[0][2], list(targets.values())[0][1], list(targets.values())[0][0]): |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 623 | self.assertEqual(targets, {1: [3, 2, 1]}) |
| 624 | with C() as (targets[1], targets[2], targets[3]): |
| 625 | self.assertEqual(targets, {1: 1, 2: 2, 3: 3}) |
| 626 | class B: pass |
| 627 | blah = B() |
| 628 | with C() as (blah.one, blah.two, blah.three): |
| 629 | self.assertEqual(blah.one, 1) |
| 630 | self.assertEqual(blah.two, 2) |
| 631 | self.assertEqual(blah.three, 3) |
| 632 | |
| 633 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 634 | class ExitSwallowsExceptionTestCase(unittest.TestCase): |
| 635 | |
Guido van Rossum | f669436 | 2006-03-10 02:28:35 +0000 | [diff] [blame] | 636 | def testExitTrueSwallowsException(self): |
| 637 | class AfricanSwallow: |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 638 | def __enter__(self): pass |
Guido van Rossum | f669436 | 2006-03-10 02:28:35 +0000 | [diff] [blame] | 639 | def __exit__(self, t, v, tb): return True |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 640 | try: |
Guido van Rossum | f669436 | 2006-03-10 02:28:35 +0000 | [diff] [blame] | 641 | with AfricanSwallow(): |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 642 | 1/0 |
| 643 | except ZeroDivisionError: |
| 644 | self.fail("ZeroDivisionError should have been swallowed") |
| 645 | |
Guido van Rossum | f669436 | 2006-03-10 02:28:35 +0000 | [diff] [blame] | 646 | def testExitFalseDoesntSwallowException(self): |
| 647 | class EuropeanSwallow: |
Guido van Rossum | f669436 | 2006-03-10 02:28:35 +0000 | [diff] [blame] | 648 | def __enter__(self): pass |
| 649 | def __exit__(self, t, v, tb): return False |
| 650 | try: |
| 651 | with EuropeanSwallow(): |
| 652 | 1/0 |
| 653 | except ZeroDivisionError: |
| 654 | pass |
| 655 | else: |
| 656 | self.fail("ZeroDivisionError should have been raised") |
| 657 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 658 | |
Georg Brandl | 0c31562 | 2009-05-25 21:10:36 +0000 | [diff] [blame] | 659 | class NestedWith(unittest.TestCase): |
| 660 | |
| 661 | class Dummy(object): |
| 662 | def __init__(self, value=None, gobble=False): |
| 663 | if value is None: |
| 664 | value = self |
| 665 | self.value = value |
| 666 | self.gobble = gobble |
| 667 | self.enter_called = False |
| 668 | self.exit_called = False |
| 669 | |
| 670 | def __enter__(self): |
| 671 | self.enter_called = True |
| 672 | return self.value |
| 673 | |
| 674 | def __exit__(self, *exc_info): |
| 675 | self.exit_called = True |
| 676 | self.exc_info = exc_info |
| 677 | if self.gobble: |
| 678 | return True |
| 679 | |
Georg Brandl | 3cfdd9c | 2009-06-04 10:21:10 +0000 | [diff] [blame] | 680 | class InitRaises(object): |
Georg Brandl | 0c31562 | 2009-05-25 21:10:36 +0000 | [diff] [blame] | 681 | def __init__(self): raise RuntimeError() |
| 682 | |
| 683 | class EnterRaises(object): |
| 684 | def __enter__(self): raise RuntimeError() |
| 685 | def __exit__(self, *exc_info): pass |
| 686 | |
| 687 | class ExitRaises(object): |
| 688 | def __enter__(self): pass |
| 689 | def __exit__(self, *exc_info): raise RuntimeError() |
| 690 | |
| 691 | def testNoExceptions(self): |
| 692 | with self.Dummy() as a, self.Dummy() as b: |
| 693 | self.assertTrue(a.enter_called) |
| 694 | self.assertTrue(b.enter_called) |
| 695 | self.assertTrue(a.exit_called) |
| 696 | self.assertTrue(b.exit_called) |
| 697 | |
| 698 | def testExceptionInExprList(self): |
| 699 | try: |
Georg Brandl | 3cfdd9c | 2009-06-04 10:21:10 +0000 | [diff] [blame] | 700 | with self.Dummy() as a, self.InitRaises(): |
Georg Brandl | 0c31562 | 2009-05-25 21:10:36 +0000 | [diff] [blame] | 701 | pass |
| 702 | except: |
| 703 | pass |
| 704 | self.assertTrue(a.enter_called) |
| 705 | self.assertTrue(a.exit_called) |
| 706 | |
| 707 | def testExceptionInEnter(self): |
| 708 | try: |
| 709 | with self.Dummy() as a, self.EnterRaises(): |
| 710 | self.fail('body of bad with executed') |
| 711 | except RuntimeError: |
| 712 | pass |
| 713 | else: |
| 714 | self.fail('RuntimeError not reraised') |
| 715 | self.assertTrue(a.enter_called) |
| 716 | self.assertTrue(a.exit_called) |
| 717 | |
| 718 | def testExceptionInExit(self): |
| 719 | body_executed = False |
| 720 | with self.Dummy(gobble=True) as a, self.ExitRaises(): |
| 721 | body_executed = True |
| 722 | self.assertTrue(a.enter_called) |
| 723 | self.assertTrue(a.exit_called) |
| 724 | self.assertNotEqual(a.exc_info[0], None) |
| 725 | |
| 726 | def testEnterReturnsTuple(self): |
| 727 | with self.Dummy(value=(1,2)) as (a1, a2), \ |
| 728 | self.Dummy(value=(10, 20)) as (b1, b2): |
| 729 | self.assertEquals(1, a1) |
| 730 | self.assertEquals(2, a2) |
| 731 | self.assertEquals(10, b1) |
| 732 | self.assertEquals(20, b2) |
| 733 | |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 734 | def test_main(): |
| 735 | run_unittest(FailureTestCase, NonexceptionalTestCase, |
| 736 | NestedNonexceptionalTestCase, ExceptionalTestCase, |
| 737 | NonLocalFlowControlTestCase, |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 738 | AssignmentTargetTestCase, |
Georg Brandl | 0c31562 | 2009-05-25 21:10:36 +0000 | [diff] [blame] | 739 | ExitSwallowsExceptionTestCase, |
| 740 | NestedWith) |
Tim Peters | 400cbc3 | 2006-02-28 18:44:41 +0000 | [diff] [blame] | 741 | |
| 742 | |
| 743 | if __name__ == '__main__': |
| 744 | test_main() |