blob: ae2fa4d7fe4da4790990d5404fe2446c94b65346 [file] [log] [blame]
Tim Peters400cbc32006-02-28 18:44:41 +00001#!/usr/bin/env python
2
3"""Unit tests for the with statement specified in PEP 343."""
4
Thomas Wouters34aa7ba2006-02-28 19:02:24 +00005
Tim Peters400cbc32006-02-28 18:44:41 +00006__author__ = "Mike Bland"
7__email__ = "mbland at acm dot org"
8
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00009import sys
Tim Peters400cbc32006-02-28 18:44:41 +000010import unittest
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000011from collections import deque
12from contextlib import GeneratorContextManager, contextmanager
Benjamin Petersonee8712c2008-05-20 21:35:26 +000013from test.support import run_unittest
Tim Peters400cbc32006-02-28 18:44:41 +000014
15
16class MockContextManager(GeneratorContextManager):
17 def __init__(self, gen):
18 GeneratorContextManager.__init__(self, gen)
Tim Peters400cbc32006-02-28 18:44:41 +000019 self.enter_called = False
20 self.exit_called = False
21 self.exit_args = None
22
Tim Peters400cbc32006-02-28 18:44:41 +000023 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 Wouters477c8d52006-05-27 19:21:47 +000030 return GeneratorContextManager.__exit__(self, type,
31 value, traceback)
Tim Peters400cbc32006-02-28 18:44:41 +000032
33
34def mock_contextmanager(func):
35 def helper(*args, **kwds):
36 return MockContextManager(func(*args, **kwds))
37 return helper
38
39
40class MockResource(object):
41 def __init__(self):
42 self.yielded = False
43 self.stopped = False
44
45
46@mock_contextmanager
47def 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 Rossum1a5e21e2006-02-28 21:57:43 +000056class Nested(object):
57
Thomas Wouters477c8d52006-05-27 19:21:47 +000058 def __init__(self, *managers):
59 self.managers = managers
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000060 self.entered = None
61
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000062 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 Wouters477c8d52006-05-27 19:21:47 +000068 for mgr in self.managers:
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000069 vars.append(mgr.__enter__())
70 self.entered.appendleft(mgr)
71 except:
Guido van Rossumf6694362006-03-10 02:28:35 +000072 if not self.__exit__(*sys.exc_info()):
73 raise
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000074 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 Rossumf6694362006-03-10 02:28:35 +000083 if mgr.__exit__(*ex):
84 ex = (None, None, None)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000085 except:
86 ex = sys.exc_info()
87 self.entered = None
88 if ex is not exc_info:
Collin Winter828f04a2007-08-31 00:04:24 +000089 raise ex[0](ex[1]).with_traceback(ex[2])
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000090
91
92class MockNested(Nested):
Thomas Wouters477c8d52006-05-27 19:21:47 +000093 def __init__(self, *managers):
94 Nested.__init__(self, *managers)
Tim Peters400cbc32006-02-28 18:44:41 +000095 self.enter_called = False
96 self.exit_called = False
97 self.exit_args = None
98
Tim Peters400cbc32006-02-28 18:44:41 +000099 def __enter__(self):
100 self.enter_called = True
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000101 return Nested.__enter__(self)
Tim Peters400cbc32006-02-28 18:44:41 +0000102
103 def __exit__(self, *exc_info):
104 self.exit_called = True
105 self.exit_args = exc_info
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000106 return Nested.__exit__(self, *exc_info)
Tim Peters400cbc32006-02-28 18:44:41 +0000107
108
109class FailureTestCase(unittest.TestCase):
110 def testNameError(self):
111 def fooNotDeclared():
112 with foo: pass
113 self.assertRaises(NameError, fooNotDeclared)
114
Tim Peters400cbc32006-02-28 18:44:41 +0000115 def testEnterAttributeError(self):
116 class LacksEnter(object):
Tim Peters400cbc32006-02-28 18:44:41 +0000117 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 Peters400cbc32006-02-28 18:44:41 +0000127 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 Peters400cbc32006-02-28 18:44:41 +0000162 def testEnterThrows(self):
163 class EnterThrows(object):
Tim Peters400cbc32006-02-28 18:44:41 +0000164 def __enter__(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000165 raise RuntimeError("Enter threw")
Tim Peters400cbc32006-02-28 18:44:41 +0000166 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 Peters400cbc32006-02-28 18:44:41 +0000179 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
188class ContextmanagerAssertionMixin(object):
Collin Winterba21f612007-09-01 20:29:04 +0000189
190 def setUp(self):
191 self.TEST_EXCEPTION = RuntimeError("test exception")
Tim Peters400cbc32006-02-28 18:44:41 +0000192
193 def assertInWithManagerInvariants(self, mock_manager):
Tim Peters400cbc32006-02-28 18:44:41 +0000194 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 Peters400cbc32006-02-28 18:44:41 +0000199 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 Peters400cbc32006-02-28 18:44:41 +0000219 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
229class 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
282class NestedNonexceptionalTestCase(unittest.TestCase,
283 ContextmanagerAssertionMixin):
284 def testSingleArgInlineGeneratorSyntax(self):
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000285 with Nested(mock_contextmanager_generator()):
Tim Peters400cbc32006-02-28 18:44:41 +0000286 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 Rossum1a5e21e2006-02-28 21:57:43 +0000301 with Nested(m) as foo:
Tim Peters400cbc32006-02-28 18:44:41 +0000302 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 Rossum1a5e21e2006-02-28 21:57:43 +0000309 with Nested(m) as (foo):
Tim Peters400cbc32006-02-28 18:44:41 +0000310 self.assertInWithManagerInvariants(m)
311 self.assertAfterWithManagerInvariantsNoError(m)
312
313 def testSingleArgBoundToMultipleElementTupleError(self):
314 def shouldThrowValueError():
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000315 with Nested(mock_contextmanager_generator()) as (foo, bar):
Tim Peters400cbc32006-02-28 18:44:41 +0000316 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 Winterba21f612007-09-01 20:29:04 +0000357class ExceptionalTestCase(ContextmanagerAssertionMixin, unittest.TestCase):
Tim Peters400cbc32006-02-28 18:44:41 +0000358 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 Peters400cbc32006-02-28 18:44:41 +0000422 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 Wouters49fd7fa2006-04-21 10:40:58 +0000443 def testRaisedStopIteration1(self):
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000444 # From bug 1462485
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000445 @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 Rossum2cc30da2007-11-02 23:46:40 +0000456 # From bug 1462485
Thomas Wouters477c8d52006-05-27 19:21:47 +0000457 class cm(object):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000458 def __enter__(self):
459 pass
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000460 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 Rossum2cc30da2007-11-02 23:46:40 +0000469 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 Wouters49fd7fa2006-04-21 10:40:58 +0000482 def testRaisedGeneratorExit1(self):
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000483 # From bug 1462485
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000484 @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 Rossum2cc30da2007-11-02 23:46:40 +0000495 # From bug 1462485
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000496 class cm (object):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000497 def __enter__(self):
498 pass
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000499 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'Arc10b24e82008-12-10 23:49:33 +0000508 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 Peters400cbc32006-02-28 18:44:41 +0000538
539class 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
596class 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 Rossum87b63952007-02-11 07:05:21 +0000601 self.assertEqual(list(targets.keys()), [1])
Tim Peters400cbc32006-02-28 18:44:41 +0000602 self.assertEqual(targets[1][0].__class__, MockResource)
Guido van Rossum87b63952007-02-11 07:05:21 +0000603 with mock_contextmanager_generator() as list(targets.values())[0][1]:
604 self.assertEqual(list(targets.keys()), [1])
Tim Peters400cbc32006-02-28 18:44:41 +0000605 self.assertEqual(targets[1][1].__class__, MockResource)
606 with mock_contextmanager_generator() as targets[2]:
Guido van Rossum87b63952007-02-11 07:05:21 +0000607 keys = list(targets.keys())
Tim Peters400cbc32006-02-28 18:44:41 +0000608 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 Peters400cbc32006-02-28 18:44:41 +0000617 def __enter__(self): return 1, 2, 3
Guido van Rossumf6694362006-03-10 02:28:35 +0000618 def __exit__(self, t, v, tb): pass
Tim Peters400cbc32006-02-28 18:44:41 +0000619 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 Rossum87b63952007-02-11 07:05:21 +0000622 with C() as (list(targets.values())[0][2], list(targets.values())[0][1], list(targets.values())[0][0]):
Tim Peters400cbc32006-02-28 18:44:41 +0000623 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 Rossum1a5e21e2006-02-28 21:57:43 +0000634class ExitSwallowsExceptionTestCase(unittest.TestCase):
635
Guido van Rossumf6694362006-03-10 02:28:35 +0000636 def testExitTrueSwallowsException(self):
637 class AfricanSwallow:
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000638 def __enter__(self): pass
Guido van Rossumf6694362006-03-10 02:28:35 +0000639 def __exit__(self, t, v, tb): return True
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000640 try:
Guido van Rossumf6694362006-03-10 02:28:35 +0000641 with AfricanSwallow():
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000642 1/0
643 except ZeroDivisionError:
644 self.fail("ZeroDivisionError should have been swallowed")
645
Guido van Rossumf6694362006-03-10 02:28:35 +0000646 def testExitFalseDoesntSwallowException(self):
647 class EuropeanSwallow:
Guido van Rossumf6694362006-03-10 02:28:35 +0000648 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 Rossum1a5e21e2006-02-28 21:57:43 +0000658
Georg Brandl0c315622009-05-25 21:10:36 +0000659class 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 Brandl3cfdd9c2009-06-04 10:21:10 +0000680 class InitRaises(object):
Georg Brandl0c315622009-05-25 21:10:36 +0000681 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 Brandl3cfdd9c2009-06-04 10:21:10 +0000700 with self.Dummy() as a, self.InitRaises():
Georg Brandl0c315622009-05-25 21:10:36 +0000701 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 Peters400cbc32006-02-28 18:44:41 +0000734def test_main():
735 run_unittest(FailureTestCase, NonexceptionalTestCase,
736 NestedNonexceptionalTestCase, ExceptionalTestCase,
737 NonLocalFlowControlTestCase,
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000738 AssignmentTargetTestCase,
Georg Brandl0c315622009-05-25 21:10:36 +0000739 ExitSwallowsExceptionTestCase,
740 NestedWith)
Tim Peters400cbc32006-02-28 18:44:41 +0000741
742
743if __name__ == '__main__':
744 test_main()