Skip to content

Commit 7213fc2

Browse files
[3.11] Synchronize test_contextlib with test_contextlib_async (GH-111000) (GH-111115)
(cherry picked from commit ff4e53c) Co-authored-by: Serhiy Storchaka <[email protected]>
1 parent 69bcaf7 commit 7213fc2

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Lib/test/test_contextlib.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,15 @@ def whoo():
162162
# The "gen" attribute is an implementation detail.
163163
self.assertFalse(ctx.gen.gi_suspended)
164164

165+
def test_contextmanager_trap_no_yield(self):
166+
@contextmanager
167+
def whoo():
168+
if False:
169+
yield
170+
ctx = whoo()
171+
with self.assertRaises(RuntimeError):
172+
ctx.__enter__()
173+
165174
def test_contextmanager_trap_second_yield(self):
166175
@contextmanager
167176
def whoo():
@@ -175,6 +184,19 @@ def whoo():
175184
# The "gen" attribute is an implementation detail.
176185
self.assertFalse(ctx.gen.gi_suspended)
177186

187+
def test_contextmanager_non_normalised(self):
188+
@contextmanager
189+
def whoo():
190+
try:
191+
yield
192+
except RuntimeError:
193+
raise SyntaxError
194+
195+
ctx = whoo()
196+
ctx.__enter__()
197+
with self.assertRaises(SyntaxError):
198+
ctx.__exit__(RuntimeError, None, None)
199+
178200
def test_contextmanager_except(self):
179201
state = []
180202
@contextmanager
@@ -254,6 +276,25 @@ def test_issue29692():
254276
self.assertEqual(ex.args[0], 'issue29692:Unchained')
255277
self.assertIsNone(ex.__cause__)
256278

279+
def test_contextmanager_wrap_runtimeerror(self):
280+
@contextmanager
281+
def woohoo():
282+
try:
283+
yield
284+
except Exception as exc:
285+
raise RuntimeError(f'caught {exc}') from exc
286+
287+
with self.assertRaises(RuntimeError):
288+
with woohoo():
289+
1 / 0
290+
291+
# If the context manager wrapped StopIteration in a RuntimeError,
292+
# we also unwrap it, because we can't tell whether the wrapping was
293+
# done by the generator machinery or by the generator itself.
294+
with self.assertRaises(StopIteration):
295+
with woohoo():
296+
raise StopIteration
297+
257298
def _create_contextmanager_attribs(self):
258299
def attribs(**kw):
259300
def decorate(func):
@@ -265,6 +306,7 @@ def decorate(func):
265306
@attribs(foo='bar')
266307
def baz(spam):
267308
"""Whee!"""
309+
yield
268310
return baz
269311

270312
def test_contextmanager_attribs(self):
@@ -321,8 +363,11 @@ def woohoo(a, *, b):
321363

322364
def test_recursive(self):
323365
depth = 0
366+
ncols = 0
324367
@contextmanager
325368
def woohoo():
369+
nonlocal ncols
370+
ncols += 1
326371
nonlocal depth
327372
before = depth
328373
depth += 1
@@ -336,6 +381,7 @@ def recursive():
336381
recursive()
337382

338383
recursive()
384+
self.assertEqual(ncols, 10)
339385
self.assertEqual(depth, 0)
340386

341387

0 commit comments

Comments
 (0)