]> granicus.if.org Git - python/commitdiff
Fix SF#1462485: StopIteration raised in body of 'with' statement suppressed
authorPhillip J. Eby <pje@telecommunity.com>
Mon, 3 Apr 2006 20:05:05 +0000 (20:05 +0000)
committerPhillip J. Eby <pje@telecommunity.com>
Mon, 3 Apr 2006 20:05:05 +0000 (20:05 +0000)
Lib/contextlib.py
Lib/test/test_with.py

index 9c00ef0777dab262d2560d5ee421157d25f34ce3..c26e27e924faa5098c0955cf938294d7dc957018 100644 (file)
@@ -32,7 +32,9 @@ class GeneratorContextManager(object):
                 self.gen.throw(type, value, traceback)
                 raise RuntimeError("generator didn't stop after throw()")
             except StopIteration:
-                return True
+                # Supress the exception unless it's the same exception the
+                # was passed to throw().
+                return sys.exc_info()[1] is not value
             except:
                 # only re-raise if it's *not* the exception that was
                 # passed to throw(), because __exit__() must not raise
index 4854436a642f1e6b5371c452cfc1f54950edf848..48e00f43e6c7559c03866475615028311d9d2c6d 100644 (file)
@@ -494,6 +494,62 @@ class ExceptionalTestCase(unittest.TestCase, ContextmanagerAssertionMixin):
         self.assertAfterWithGeneratorInvariantsWithError(self.foo)
         self.assertAfterWithGeneratorInvariantsNoError(self.bar)
 
+    def testRaisedStopIteration1(self):
+        @contextmanager
+        def cm():
+            yield
+
+        def shouldThrow():
+            with cm():
+                raise StopIteration("from with")
+
+        self.assertRaises(StopIteration, shouldThrow)
+
+    def testRaisedStopIteration2(self):
+        class cm (object):
+            def __context__(self):
+                return self
+
+            def __enter__(self):
+                pass
+
+            def __exit__(self, type, value, traceback):
+                pass
+
+        def shouldThrow():
+            with cm():
+                raise StopIteration("from with")
+
+        self.assertRaises(StopIteration, shouldThrow)
+
+    def testRaisedGeneratorExit1(self):
+        @contextmanager
+        def cm():
+            yield
+
+        def shouldThrow():
+            with cm():
+                raise GeneratorExit("from with")
+
+        self.assertRaises(GeneratorExit, shouldThrow)
+
+    def testRaisedGeneratorExit2(self):
+        class cm (object):
+            def __context__(self):
+                return self
+
+            def __enter__(self):
+                pass
+
+            def __exit__(self, type, value, traceback):
+                pass
+
+        def shouldThrow():
+            with cm():
+                raise GeneratorExit("from with")
+
+        self.assertRaises(GeneratorExit, shouldThrow)
+
 
 class NonLocalFlowControlTestCase(unittest.TestCase):