| 1 |
"""Unit tests for the 'with/async with' statements specified in PEP 343/492.""" |
| 2 |
|
| 3 |
|
| 4 |
__author__ = "Mike Bland" |
| 5 |
__email__ = "mbland at acm dot org" |
| 6 |
|
| 7 |
import re |
| 8 |
import sys |
| 9 |
import traceback |
| 10 |
import unittest |
| 11 |
from collections import deque |
| 12 |
from contextlib import _GeneratorContextManager, contextmanager, nullcontext |
| 13 |
|
| 14 |
|
| 15 |
def do_with(obj): |
| 16 |
with obj: |
| 17 |
pass |
| 18 |
|
| 19 |
|
| 20 |
async def do_async_with(obj): |
| 21 |
async with obj: |
| 22 |
pass |
| 23 |
|
| 24 |
|
| 25 |
class MockContextManager(_GeneratorContextManager): |
| 26 |
def __init__(self, *args): |
| 27 |
super().__init__(*args) |
| 28 |
self.enter_called = False |
| 29 |
self.exit_called = False |
| 30 |
self.exit_args = None |
| 31 |
|
| 32 |
def __enter__(self): |
| 33 |
self.enter_called = True |
| 34 |
return _GeneratorContextManager.__enter__(self) |
| 35 |
|
| 36 |
def __exit__(self, type, value, traceback): |
| 37 |
self.exit_called = True |
| 38 |
self.exit_args = (type, value, traceback) |
| 39 |
return _GeneratorContextManager.__exit__(self, type, |
| 40 |
value, traceback) |
| 41 |
|
| 42 |
|
| 43 |
def mock_contextmanager(func): |
| 44 |
def helper(*args, **kwds): |
| 45 |
return MockContextManager(func, args, kwds) |
| 46 |
return helper |
| 47 |
|
| 48 |
|
| 49 |
class MockResource(object): |
| 50 |
def __init__(self): |
| 51 |
self.yielded = False |
| 52 |
self.stopped = False |
| 53 |
|
| 54 |
|
| 55 |
@mock_contextmanager |
| 56 |
def mock_contextmanager_generator(): |
| 57 |
mock = MockResource() |
| 58 |
try: |
| 59 |
mock.yielded = True |
| 60 |
yield mock |
| 61 |
finally: |
| 62 |
mock.stopped = True |
| 63 |
|
| 64 |
|
| 65 |
class Nested(object): |
| 66 |
|
| 67 |
def __init__(self, *managers): |
| 68 |
self.managers = managers |
| 69 |
self.entered = None |
| 70 |
|
| 71 |
def __enter__(self): |
| 72 |
if self.entered is not None: |
| 73 |
raise RuntimeError("Context is not reentrant") |
| 74 |
self.entered = deque() |
| 75 |
vars = [] |
| 76 |
try: |
| 77 |
for mgr in self.managers: |
| 78 |
vars.append(mgr.__enter__()) |
| 79 |
self.entered.appendleft(mgr) |
| 80 |
except: |
| 81 |
if not self.__exit__(*sys.exc_info()): |
| 82 |
raise |
| 83 |
return vars |
| 84 |
|
| 85 |
def __exit__(self, *exc_info): |
| 86 |
# Behave like nested with statements |
| 87 |
# first in, last out |
| 88 |
# New exceptions override old ones |
| 89 |
ex = exc_info |
| 90 |
for mgr in self.entered: |
| 91 |
try: |
| 92 |
if mgr.__exit__(*ex): |
| 93 |
ex = (None, None, None) |
| 94 |
except BaseException as e: |
| 95 |
ex = (type(e), e, e.__traceback__) |
| 96 |
self.entered = None |
| 97 |
if ex is not exc_info: |
| 98 |
raise ex |
| 99 |
|
| 100 |
|
| 101 |
class MockNested(Nested): |
| 102 |
def __init__(self, *managers): |
| 103 |
Nested.__init__(self, *managers) |
| 104 |
self.enter_called = False |
| 105 |
self.exit_called = False |
| 106 |
self.exit_args = None |
| 107 |
|
| 108 |
def __enter__(self): |
| 109 |
self.enter_called = True |
| 110 |
return Nested.__enter__(self) |
| 111 |
|
| 112 |
def __exit__(self, *exc_info): |
| 113 |
self.exit_called = True |
| 114 |
self.exit_args = exc_info |
| 115 |
return Nested.__exit__(self, *exc_info) |
| 116 |
|
| 117 |
|
| 118 |
class FailureTestCase(unittest.TestCase): |
| 119 |
def testNameError(self): |
| 120 |
def fooNotDeclared(): |
| 121 |
with foo: pass |
| 122 |
self.assertRaises(NameError, fooNotDeclared) |
| 123 |
|
| 124 |
def testEnterAttributeError(self): |
| 125 |
class LacksEnter: |
| 126 |
def __exit__(self, type, value, traceback): ... |
| 127 |
|
| 128 |
with self.assertRaisesRegex(TypeError, re.escape(( |
| 129 |
"object does not support the context manager protocol " |
| 130 |
"(missed __enter__ method)" |
| 131 |
))): |
| 132 |
do_with(LacksEnter()) |
| 133 |
|
| 134 |
def testExitAttributeError(self): |
| 135 |
class LacksExit: |
| 136 |
def __enter__(self): ... |
| 137 |
|
| 138 |
msg = re.escape(( |
| 139 |
"object does not support the context manager protocol " |
| 140 |
"(missed __exit__ method)" |
| 141 |
)) |
| 142 |
# a missing __exit__ is reported missing before a missing __enter__ |
| 143 |
with self.assertRaisesRegex(TypeError, msg): |
| 144 |
do_with(object()) |
| 145 |
with self.assertRaisesRegex(TypeError, msg): |
| 146 |
do_with(LacksExit()) |
| 147 |
|
| 148 |
def testWithForAsyncManager(self): |
| 149 |
class AsyncManager: |
| 150 |
async def __aenter__(self): ... |
| 151 |
async def __aexit__(self, type, value, traceback): ... |
| 152 |
|
| 153 |
with self.assertRaisesRegex(TypeError, re.escape(( |
| 154 |
"object does not support the context manager protocol " |
| 155 |
"(missed __exit__ method) but it supports the asynchronous " |
| 156 |
"context manager protocol. Did you mean to use 'async with'?" |
| 157 |
))): |
| 158 |
do_with(AsyncManager()) |
| 159 |
|
| 160 |
def testAsyncEnterAttributeError(self): |
| 161 |
class LacksAsyncEnter: |
| 162 |
async def __aexit__(self, type, value, traceback): ... |
| 163 |
|
| 164 |
with self.assertRaisesRegex(TypeError, re.escape(( |
| 165 |
"object does not support the asynchronous context manager protocol " |
| 166 |
"(missed __aenter__ method)" |
| 167 |
))): |
| 168 |
do_async_with(LacksAsyncEnter()).send(None) |
| 169 |
|
| 170 |
def testAsyncExitAttributeError(self): |
| 171 |
class LacksAsyncExit: |
| 172 |
async def __aenter__(self): ... |
| 173 |
|
| 174 |
msg = re.escape(( |
| 175 |
"object does not support the asynchronous context manager protocol " |
| 176 |
"(missed __aexit__ method)" |
| 177 |
)) |
| 178 |
# a missing __aexit__ is reported missing before a missing __aenter__ |
| 179 |
with self.assertRaisesRegex(TypeError, msg): |
| 180 |
do_async_with(object()).send(None) |
| 181 |
with self.assertRaisesRegex(TypeError, msg): |
| 182 |
do_async_with(LacksAsyncExit()).send(None) |
| 183 |
|
| 184 |
def testAsyncWithForSyncManager(self): |
| 185 |
class SyncManager: |
| 186 |
def __enter__(self): ... |
| 187 |
def __exit__(self, type, value, traceback): ... |
| 188 |
|
| 189 |
with self.assertRaisesRegex(TypeError, re.escape(( |
| 190 |
"object does not support the asynchronous context manager protocol " |
| 191 |
"(missed __aexit__ method) but it supports the context manager " |
| 192 |
"protocol. Did you mean to use 'with'?" |
| 193 |
))): |
| 194 |
do_async_with(SyncManager()).send(None) |
| 195 |
|
| 196 |
def assertRaisesSyntaxError(self, codestr): |
| 197 |
def shouldRaiseSyntaxError(s): |
| 198 |
compile(s, '', 'single') |
| 199 |
self.assertRaises(SyntaxError, shouldRaiseSyntaxError, codestr) |
| 200 |
|
| 201 |
def testAssignmentToNoneError(self): |
| 202 |
self.assertRaisesSyntaxError('with mock as None:\n pass') |
| 203 |
self.assertRaisesSyntaxError( |
| 204 |
'with mock as (None):\n' |
| 205 |
' pass') |
| 206 |
|
| 207 |
def testAssignmentToTupleOnlyContainingNoneError(self): |
| 208 |
self.assertRaisesSyntaxError('with mock as None,:\n pass') |
| 209 |
self.assertRaisesSyntaxError( |
| 210 |
'with mock as (None,):\n' |
| 211 |
' pass') |
| 212 |
|
| 213 |
def testAssignmentToTupleContainingNoneError(self): |
| 214 |
self.assertRaisesSyntaxError( |
| 215 |
'with mock as (foo, None, bar):\n' |
| 216 |
' pass') |
| 217 |
|
| 218 |
def testEnterThrows(self): |
| 219 |
class EnterThrows(object): |
| 220 |
def __enter__(self): |
| 221 |
raise RuntimeError("Enter threw") |
| 222 |
def __exit__(self, *args): |
| 223 |
pass |
| 224 |
|
| 225 |
def shouldThrow(): |
| 226 |
ct = EnterThrows() |
| 227 |
self.foo = None |
| 228 |
# Ruff complains that we're redefining `self.foo` here, |
| 229 |
# but the whole point of the test is to check that `self.foo` |
| 230 |
# is *not* redefined (because `__enter__` raises) |
| 231 |
with ct as self.foo: # noqa: F811 |
| 232 |
pass |
| 233 |
self.assertRaises(RuntimeError, shouldThrow) |
| 234 |
self.assertEqual(self.foo, None) |
| 235 |
|
| 236 |
def testExitThrows(self): |
| 237 |
class ExitThrows(object): |
| 238 |
def __enter__(self): |
| 239 |
return |
| 240 |
def __exit__(self, *args): |
| 241 |
raise RuntimeError(42) |
| 242 |
def shouldThrow(): |
| 243 |
with ExitThrows(): |
| 244 |
pass |
| 245 |
self.assertRaises(RuntimeError, shouldThrow) |
| 246 |
|
| 247 |
|
| 248 |
class ContextmanagerAssertionMixin(object): |
| 249 |
|
| 250 |
def setUp(self): |
| 251 |
self.TEST_EXCEPTION = RuntimeError("test exception") |
| 252 |
|
| 253 |
def assertInWithManagerInvariants(self, mock_manager): |
| 254 |
self.assertTrue(mock_manager.enter_called) |
| 255 |
self.assertFalse(mock_manager.exit_called) |
| 256 |
self.assertEqual(mock_manager.exit_args, None) |
| 257 |
|
| 258 |
def assertAfterWithManagerInvariants(self, mock_manager, exit_args): |
| 259 |
self.assertTrue(mock_manager.enter_called) |
| 260 |
self.assertTrue(mock_manager.exit_called) |
| 261 |
self.assertEqual(mock_manager.exit_args, exit_args) |
| 262 |
|
| 263 |
def assertAfterWithManagerInvariantsNoError(self, mock_manager): |
| 264 |
self.assertAfterWithManagerInvariants(mock_manager, |
| 265 |
(None, None, None)) |
| 266 |
|
| 267 |
def assertInWithGeneratorInvariants(self, mock_generator): |
| 268 |
self.assertTrue(mock_generator.yielded) |
| 269 |
self.assertFalse(mock_generator.stopped) |
| 270 |
|
| 271 |
def assertAfterWithGeneratorInvariantsNoError(self, mock_generator): |
| 272 |
self.assertTrue(mock_generator.yielded) |
| 273 |
self.assertTrue(mock_generator.stopped) |
| 274 |
|
| 275 |
def raiseTestException(self): |
| 276 |
raise self.TEST_EXCEPTION |
| 277 |
|
| 278 |
def assertAfterWithManagerInvariantsWithError(self, mock_manager, |
| 279 |
exc_type=None): |
| 280 |
self.assertTrue(mock_manager.enter_called) |
| 281 |
self.assertTrue(mock_manager.exit_called) |
| 282 |
if exc_type is None: |
| 283 |
self.assertEqual(mock_manager.exit_args[1], self.TEST_EXCEPTION) |
| 284 |
exc_type = type(self.TEST_EXCEPTION) |
| 285 |
self.assertEqual(mock_manager.exit_args[0], exc_type) |
| 286 |
# Test the __exit__ arguments. Issue #7853 |
| 287 |
self.assertIsInstance(mock_manager.exit_args[1], exc_type) |
| 288 |
self.assertIsNot(mock_manager.exit_args[2], None) |
| 289 |
|
| 290 |
def assertAfterWithGeneratorInvariantsWithError(self, mock_generator): |
| 291 |
self.assertTrue(mock_generator.yielded) |
| 292 |
self.assertTrue(mock_generator.stopped) |
| 293 |
|
| 294 |
|
| 295 |
class NonexceptionalTestCase(unittest.TestCase, ContextmanagerAssertionMixin): |
| 296 |
def testInlineGeneratorSyntax(self): |
| 297 |
with mock_contextmanager_generator(): |
| 298 |
pass |
| 299 |
|
| 300 |
def testUnboundGenerator(self): |
| 301 |
mock = mock_contextmanager_generator() |
| 302 |
with mock: |
| 303 |
pass |
| 304 |
self.assertAfterWithManagerInvariantsNoError(mock) |
| 305 |
|
| 306 |
def testInlineGeneratorBoundSyntax(self): |
| 307 |
with mock_contextmanager_generator() as foo: |
| 308 |
self.assertInWithGeneratorInvariants(foo) |
| 309 |
# FIXME: In the future, we'll try to keep the bound names from leaking |
| 310 |
self.assertAfterWithGeneratorInvariantsNoError(foo) |
| 311 |
|
| 312 |
def testInlineGeneratorBoundToExistingVariable(self): |
| 313 |
with mock_contextmanager_generator() as foo: |
| 314 |
self.assertInWithGeneratorInvariants(foo) |
| 315 |
self.assertAfterWithGeneratorInvariantsNoError(foo) |
| 316 |
|
| 317 |
def testInlineGeneratorBoundToDottedVariable(self): |
| 318 |
with mock_contextmanager_generator() as self.foo: |
| 319 |
self.assertInWithGeneratorInvariants(self.foo) |
| 320 |
self.assertAfterWithGeneratorInvariantsNoError(self.foo) |
| 321 |
|
| 322 |
def testBoundGenerator(self): |
| 323 |
mock = mock_contextmanager_generator() |
| 324 |
with mock as foo: |
| 325 |
self.assertInWithGeneratorInvariants(foo) |
| 326 |
self.assertInWithManagerInvariants(mock) |
| 327 |
self.assertAfterWithGeneratorInvariantsNoError(foo) |
| 328 |
self.assertAfterWithManagerInvariantsNoError(mock) |
| 329 |
|
| 330 |
def testNestedSingleStatements(self): |
| 331 |
mock_a = mock_contextmanager_generator() |
| 332 |
with mock_a as foo: |
| 333 |
mock_b = mock_contextmanager_generator() |
| 334 |
with mock_b as bar: |
| 335 |
self.assertInWithManagerInvariants(mock_a) |
| 336 |
self.assertInWithManagerInvariants(mock_b) |
| 337 |
self.assertInWithGeneratorInvariants(foo) |
| 338 |
self.assertInWithGeneratorInvariants(bar) |
| 339 |
self.assertAfterWithManagerInvariantsNoError(mock_b) |
| 340 |
self.assertAfterWithGeneratorInvariantsNoError(bar) |
| 341 |
self.assertInWithManagerInvariants(mock_a) |
| 342 |
self.assertInWithGeneratorInvariants(foo) |
| 343 |
self.assertAfterWithManagerInvariantsNoError(mock_a) |
| 344 |
self.assertAfterWithGeneratorInvariantsNoError(foo) |
| 345 |
|
| 346 |
|
| 347 |
class NestedNonexceptionalTestCase(unittest.TestCase, |
| 348 |
ContextmanagerAssertionMixin): |
| 349 |
def testSingleArgInlineGeneratorSyntax(self): |
| 350 |
with Nested(mock_contextmanager_generator()): |
| 351 |
pass |
| 352 |
|
| 353 |
def testSingleArgBoundToNonTuple(self): |
| 354 |
m = mock_contextmanager_generator() |
| 355 |
# This will bind all the arguments to nested() into a single list |
| 356 |
# assigned to foo. |
| 357 |
with Nested(m) as foo: |
| 358 |
self.assertInWithManagerInvariants(m) |
| 359 |
self.assertAfterWithManagerInvariantsNoError(m) |
| 360 |
|
| 361 |
def testSingleArgBoundToSingleElementParenthesizedList(self): |
| 362 |
m = mock_contextmanager_generator() |
| 363 |
# This will bind all the arguments to nested() into a single list |
| 364 |
# assigned to foo. |
| 365 |
with Nested(m) as (foo): |
| 366 |
self.assertInWithManagerInvariants(m) |
| 367 |
self.assertAfterWithManagerInvariantsNoError(m) |
| 368 |
|
| 369 |
def testSingleArgBoundToMultipleElementTupleError(self): |
| 370 |
def shouldThrowValueError(): |
| 371 |
with Nested(mock_contextmanager_generator()) as (foo, bar): |
| 372 |
pass |
| 373 |
self.assertRaises(ValueError, shouldThrowValueError) |
| 374 |
|
| 375 |
def testSingleArgUnbound(self): |
| 376 |
mock_contextmanager = mock_contextmanager_generator() |
| 377 |
mock_nested = MockNested(mock_contextmanager) |
| 378 |
with mock_nested: |
| 379 |
self.assertInWithManagerInvariants(mock_contextmanager) |
| 380 |
self.assertInWithManagerInvariants(mock_nested) |
| 381 |
self.assertAfterWithManagerInvariantsNoError(mock_contextmanager) |
| 382 |
self.assertAfterWithManagerInvariantsNoError(mock_nested) |
| 383 |
|
| 384 |
def testMultipleArgUnbound(self): |
| 385 |
m = mock_contextmanager_generator() |
| 386 |
n = mock_contextmanager_generator() |
| 387 |
o = mock_contextmanager_generator() |
| 388 |
mock_nested = MockNested(m, n, o) |
| 389 |
with mock_nested: |
| 390 |
self.assertInWithManagerInvariants(m) |
| 391 |
self.assertInWithManagerInvariants(n) |
| 392 |
self.assertInWithManagerInvariants(o) |
| 393 |
self.assertInWithManagerInvariants(mock_nested) |
| 394 |
self.assertAfterWithManagerInvariantsNoError(m) |
| 395 |
self.assertAfterWithManagerInvariantsNoError(n) |
| 396 |
self.assertAfterWithManagerInvariantsNoError(o) |
| 397 |
self.assertAfterWithManagerInvariantsNoError(mock_nested) |
| 398 |
|
| 399 |
def testMultipleArgBound(self): |
| 400 |
mock_nested = MockNested(mock_contextmanager_generator(), |
| 401 |
mock_contextmanager_generator(), mock_contextmanager_generator()) |
| 402 |
with mock_nested as (m, n, o): |
| 403 |
self.assertInWithGeneratorInvariants(m) |
| 404 |
self.assertInWithGeneratorInvariants(n) |
| 405 |
self.assertInWithGeneratorInvariants(o) |
| 406 |
self.assertInWithManagerInvariants(mock_nested) |
| 407 |
self.assertAfterWithGeneratorInvariantsNoError(m) |
| 408 |
self.assertAfterWithGeneratorInvariantsNoError(n) |
| 409 |
self.assertAfterWithGeneratorInvariantsNoError(o) |
| 410 |
self.assertAfterWithManagerInvariantsNoError(mock_nested) |
| 411 |
|
| 412 |
|
| 413 |
class ExceptionalTestCase(ContextmanagerAssertionMixin, unittest.TestCase): |
| 414 |
def testSingleResource(self): |
| 415 |
cm = mock_contextmanager_generator() |
| 416 |
def shouldThrow(): |
| 417 |
with cm as self.resource: |
| 418 |
self.assertInWithManagerInvariants(cm) |
| 419 |
self.assertInWithGeneratorInvariants(self.resource) |
| 420 |
self.raiseTestException() |
| 421 |
self.assertRaises(RuntimeError, shouldThrow) |
| 422 |
self.assertAfterWithManagerInvariantsWithError(cm) |
| 423 |
self.assertAfterWithGeneratorInvariantsWithError(self.resource) |
| 424 |
|
| 425 |
def testExceptionNormalized(self): |
| 426 |
cm = mock_contextmanager_generator() |
| 427 |
def shouldThrow(): |
| 428 |
with cm as self.resource: |
| 429 |
# Note this relies on the fact that 1 // 0 produces an exception |
| 430 |
# that is not normalized immediately. |
| 431 |
1 // 0 |
| 432 |
self.assertRaises(ZeroDivisionError, shouldThrow) |
| 433 |
self.assertAfterWithManagerInvariantsWithError(cm, ZeroDivisionError) |
| 434 |
|
| 435 |
def testNestedSingleStatements(self): |
| 436 |
mock_a = mock_contextmanager_generator() |
| 437 |
mock_b = mock_contextmanager_generator() |
| 438 |
def shouldThrow(): |
| 439 |
with mock_a as self.foo: |
| 440 |
with mock_b as self.bar: |
| 441 |
self.assertInWithManagerInvariants(mock_a) |
| 442 |
self.assertInWithManagerInvariants(mock_b) |
| 443 |
self.assertInWithGeneratorInvariants(self.foo) |
| 444 |
self.assertInWithGeneratorInvariants(self.bar) |
| 445 |
self.raiseTestException() |
| 446 |
self.assertRaises(RuntimeError, shouldThrow) |
| 447 |
self.assertAfterWithManagerInvariantsWithError(mock_a) |
| 448 |
self.assertAfterWithManagerInvariantsWithError(mock_b) |
| 449 |
self.assertAfterWithGeneratorInvariantsWithError(self.foo) |
| 450 |
self.assertAfterWithGeneratorInvariantsWithError(self.bar) |
| 451 |
|
| 452 |
def testMultipleResourcesInSingleStatement(self): |
| 453 |
cm_a = mock_contextmanager_generator() |
| 454 |
cm_b = mock_contextmanager_generator() |
| 455 |
mock_nested = MockNested(cm_a, cm_b) |
| 456 |
def shouldThrow(): |
| 457 |
with mock_nested as (self.resource_a, self.resource_b): |
| 458 |
self.assertInWithManagerInvariants(cm_a) |
| 459 |
self.assertInWithManagerInvariants(cm_b) |
| 460 |
self.assertInWithManagerInvariants(mock_nested) |
| 461 |
self.assertInWithGeneratorInvariants(self.resource_a) |
| 462 |
self.assertInWithGeneratorInvariants(self.resource_b) |
| 463 |
self.raiseTestException() |
| 464 |
self.assertRaises(RuntimeError, shouldThrow) |
| 465 |
self.assertAfterWithManagerInvariantsWithError(cm_a) |
| 466 |
self.assertAfterWithManagerInvariantsWithError(cm_b) |
| 467 |
self.assertAfterWithManagerInvariantsWithError(mock_nested) |
| 468 |
self.assertAfterWithGeneratorInvariantsWithError(self.resource_a) |
| 469 |
self.assertAfterWithGeneratorInvariantsWithError(self.resource_b) |
| 470 |
|
| 471 |
def testNestedExceptionBeforeInnerStatement(self): |
| 472 |
mock_a = mock_contextmanager_generator() |
| 473 |
mock_b = mock_contextmanager_generator() |
| 474 |
self.bar = None |
| 475 |
def shouldThrow(): |
| 476 |
with mock_a as self.foo: |
| 477 |
self.assertInWithManagerInvariants(mock_a) |
| 478 |
self.assertInWithGeneratorInvariants(self.foo) |
| 479 |
self.raiseTestException() |
| 480 |
with mock_b as self.bar: |
| 481 |
pass |
| 482 |
self.assertRaises(RuntimeError, shouldThrow) |
| 483 |
self.assertAfterWithManagerInvariantsWithError(mock_a) |
| 484 |
self.assertAfterWithGeneratorInvariantsWithError(self.foo) |
| 485 |
|
| 486 |
# The inner statement stuff should never have been touched |
| 487 |
self.assertEqual(self.bar, None) |
| 488 |
self.assertFalse(mock_b.enter_called) |
| 489 |
self.assertFalse(mock_b.exit_called) |
| 490 |
self.assertEqual(mock_b.exit_args, None) |
| 491 |
|
| 492 |
def testNestedExceptionAfterInnerStatement(self): |
| 493 |
mock_a = mock_contextmanager_generator() |
| 494 |
mock_b = mock_contextmanager_generator() |
| 495 |
def shouldThrow(): |
| 496 |
with mock_a as self.foo: |
| 497 |
with mock_b as self.bar: |
| 498 |
self.assertInWithManagerInvariants(mock_a) |
| 499 |
self.assertInWithManagerInvariants(mock_b) |
| 500 |
self.assertInWithGeneratorInvariants(self.foo) |
| 501 |
self.assertInWithGeneratorInvariants(self.bar) |
| 502 |
self.raiseTestException() |
| 503 |
self.assertRaises(RuntimeError, shouldThrow) |
| 504 |
self.assertAfterWithManagerInvariantsWithError(mock_a) |
| 505 |
self.assertAfterWithManagerInvariantsNoError(mock_b) |
| 506 |
self.assertAfterWithGeneratorInvariantsWithError(self.foo) |
| 507 |
self.assertAfterWithGeneratorInvariantsNoError(self.bar) |
| 508 |
|
| 509 |
def testRaisedStopIteration1(self): |
| 510 |
# From bug 1462485 |
| 511 |
@contextmanager |
| 512 |
def cm(): |
| 513 |
yield |
| 514 |
|
| 515 |
def shouldThrow(): |
| 516 |
with cm(): |
| 517 |
raise StopIteration("from with") |
| 518 |
|
| 519 |
with self.assertRaisesRegex(StopIteration, 'from with'): |
| 520 |
shouldThrow() |
| 521 |
|
| 522 |
def testRaisedStopIteration2(self): |
| 523 |
# From bug 1462485 |
| 524 |
class cm(object): |
| 525 |
def __enter__(self): |
| 526 |
pass |
| 527 |
def __exit__(self, type, value, traceback): |
| 528 |
pass |
| 529 |
|
| 530 |
def shouldThrow(): |
| 531 |
with cm(): |
| 532 |
raise StopIteration("from with") |
| 533 |
|
| 534 |
with self.assertRaisesRegex(StopIteration, 'from with'): |
| 535 |
shouldThrow() |
| 536 |
|
| 537 |
def testRaisedStopIteration3(self): |
| 538 |
# Another variant where the exception hasn't been instantiated |
| 539 |
# From bug 1705170 |
| 540 |
@contextmanager |
| 541 |
def cm(): |
| 542 |
yield |
| 543 |
|
| 544 |
def shouldThrow(): |
| 545 |
with cm(): |
| 546 |
raise next(iter([])) |
| 547 |
|
| 548 |
with self.assertRaises(StopIteration): |
| 549 |
shouldThrow() |
| 550 |
|
| 551 |
def testRaisedGeneratorExit1(self): |
| 552 |
# From bug 1462485 |
| 553 |
@contextmanager |
| 554 |
def cm(): |
| 555 |
yield |
| 556 |
|
| 557 |
def shouldThrow(): |
| 558 |
with cm(): |
| 559 |
raise GeneratorExit("from with") |
| 560 |
|
| 561 |
self.assertRaises(GeneratorExit, shouldThrow) |
| 562 |
|
| 563 |
def testRaisedGeneratorExit2(self): |
| 564 |
# From bug 1462485 |
| 565 |
class cm (object): |
| 566 |
def __enter__(self): |
| 567 |
pass |
| 568 |
def __exit__(self, type, value, traceback): |
| 569 |
pass |
| 570 |
|
| 571 |
def shouldThrow(): |
| 572 |
with cm(): |
| 573 |
raise GeneratorExit("from with") |
| 574 |
|
| 575 |
self.assertRaises(GeneratorExit, shouldThrow) |
| 576 |
|
| 577 |
def testErrorsInBool(self): |
| 578 |
# issue4589: __exit__ return code may raise an exception |
| 579 |
# when looking at its truth value. |
| 580 |
|
| 581 |
class cm(object): |
| 582 |
def __init__(self, bool_conversion): |
| 583 |
class Bool: |
| 584 |
def __bool__(self): |
| 585 |
return bool_conversion() |
| 586 |
self.exit_result = Bool() |
| 587 |
def __enter__(self): |
| 588 |
return 3 |
| 589 |
def __exit__(self, a, b, c): |
| 590 |
return self.exit_result |
| 591 |
|
| 592 |
def trueAsBool(): |
| 593 |
with cm(lambda: True): |
| 594 |
self.fail("Should NOT see this") |
| 595 |
trueAsBool() |
| 596 |
|
| 597 |
def falseAsBool(): |
| 598 |
with cm(lambda: False): |
| 599 |
self.fail("Should raise") |
| 600 |
self.assertRaises(AssertionError, falseAsBool) |
| 601 |
|
| 602 |
def failAsBool(): |
| 603 |
with cm(lambda: 1//0): |
| 604 |
self.fail("Should NOT see this") |
| 605 |
self.assertRaises(ZeroDivisionError, failAsBool) |
| 606 |
|
| 607 |
|
| 608 |
class NonLocalFlowControlTestCase(unittest.TestCase): |
| 609 |
|
| 610 |
def testWithBreak(self): |
| 611 |
counter = 0 |
| 612 |
while True: |
| 613 |
counter += 1 |
| 614 |
with mock_contextmanager_generator(): |
| 615 |
counter += 10 |
| 616 |
break |
| 617 |
counter += 100 # Not reached |
| 618 |
self.assertEqual(counter, 11) |
| 619 |
|
| 620 |
def testWithContinue(self): |
| 621 |
counter = 0 |
| 622 |
while True: |
| 623 |
counter += 1 |
| 624 |
if counter > 2: |
| 625 |
break |
| 626 |
with mock_contextmanager_generator(): |
| 627 |
counter += 10 |
| 628 |
continue |
| 629 |
counter += 100 # Not reached |
| 630 |
self.assertEqual(counter, 12) |
| 631 |
|
| 632 |
def testWithReturn(self): |
| 633 |
def foo(): |
| 634 |
counter = 0 |
| 635 |
while True: |
| 636 |
counter += 1 |
| 637 |
with mock_contextmanager_generator(): |
| 638 |
counter += 10 |
| 639 |
return counter |
| 640 |
counter += 100 # Not reached |
| 641 |
self.assertEqual(foo(), 11) |
| 642 |
|
| 643 |
def testWithYield(self): |
| 644 |
def gen(): |
| 645 |
with mock_contextmanager_generator(): |
| 646 |
yield 12 |
| 647 |
yield 13 |
| 648 |
x = list(gen()) |
| 649 |
self.assertEqual(x, [12, 13]) |
| 650 |
|
| 651 |
def testWithRaise(self): |
| 652 |
counter = 0 |
| 653 |
try: |
| 654 |
counter += 1 |
| 655 |
with mock_contextmanager_generator(): |
| 656 |
counter += 10 |
| 657 |
raise RuntimeError |
| 658 |
counter += 100 # Not reached |
| 659 |
except RuntimeError: |
| 660 |
self.assertEqual(counter, 11) |
| 661 |
else: |
| 662 |
self.fail("Didn't raise RuntimeError") |
| 663 |
|
| 664 |
|
| 665 |
class AssignmentTargetTestCase(unittest.TestCase): |
| 666 |
|
| 667 |
def testSingleComplexTarget(self): |
| 668 |
targets = {1: [0, 1, 2]} |
| 669 |
with mock_contextmanager_generator() as targets[1][0]: |
| 670 |
self.assertEqual(list(targets.keys()), [1]) |
| 671 |
self.assertEqual(targets[1][0].__class__, MockResource) |
| 672 |
with mock_contextmanager_generator() as list(targets.values())[0][1]: |
| 673 |
self.assertEqual(list(targets.keys()), [1]) |
| 674 |
self.assertEqual(targets[1][1].__class__, MockResource) |
| 675 |
with mock_contextmanager_generator() as targets[2]: |
| 676 |
keys = list(targets.keys()) |
| 677 |
keys.sort() |
| 678 |
self.assertEqual(keys, [1, 2]) |
| 679 |
class C: pass |
| 680 |
blah = C() |
| 681 |
with mock_contextmanager_generator() as blah.foo: |
| 682 |
self.assertHasAttr(blah, "foo") |
| 683 |
|
| 684 |
def testMultipleComplexTargets(self): |
| 685 |
class C: |
| 686 |
def __enter__(self): return 1, 2, 3 |
| 687 |
def __exit__(self, t, v, tb): pass |
| 688 |
targets = {1: [0, 1, 2]} |
| 689 |
with C() as (targets[1][0], targets[1][1], targets[1][2]): |
| 690 |
self.assertEqual(targets, {1: [1, 2, 3]}) |
| 691 |
with C() as (list(targets.values())[0][2], list(targets.values())[0][1], list(targets.values())[0][0]): |
| 692 |
self.assertEqual(targets, {1: [3, 2, 1]}) |
| 693 |
with C() as (targets[1], targets[2], targets[3]): |
| 694 |
self.assertEqual(targets, {1: 1, 2: 2, 3: 3}) |
| 695 |
class B: pass |
| 696 |
blah = B() |
| 697 |
with C() as (blah.one, blah.two, blah.three): |
| 698 |
self.assertEqual(blah.one, 1) |
| 699 |
self.assertEqual(blah.two, 2) |
| 700 |
self.assertEqual(blah.three, 3) |
| 701 |
|
| 702 |
def testWithExtendedTargets(self): |
| 703 |
with nullcontext(range(1, 5)) as (a, *b, c): |
| 704 |
self.assertEqual(a, 1) |
| 705 |
self.assertEqual(b, [2, 3]) |
| 706 |
self.assertEqual(c, 4) |
| 707 |
|
| 708 |
|
| 709 |
class ExitSwallowsExceptionTestCase(unittest.TestCase): |
| 710 |
|
| 711 |
def testExitTrueSwallowsException(self): |
| 712 |
class AfricanSwallow: |
| 713 |
def __enter__(self): pass |
| 714 |
def __exit__(self, t, v, tb): return True |
| 715 |
try: |
| 716 |
with AfricanSwallow(): |
| 717 |
1/0 |
| 718 |
except ZeroDivisionError: |
| 719 |
self.fail("ZeroDivisionError should have been swallowed") |
| 720 |
|
| 721 |
def testExitFalseDoesntSwallowException(self): |
| 722 |
class EuropeanSwallow: |
| 723 |
def __enter__(self): pass |
| 724 |
def __exit__(self, t, v, tb): return False |
| 725 |
try: |
| 726 |
with EuropeanSwallow(): |
| 727 |
1/0 |
| 728 |
except ZeroDivisionError: |
| 729 |
pass |
| 730 |
else: |
| 731 |
self.fail("ZeroDivisionError should have been raised") |
| 732 |
|
| 733 |
|
| 734 |
class NestedWith(unittest.TestCase): |
| 735 |
|
| 736 |
class Dummy(object): |
| 737 |
def __init__(self, value=None, gobble=False): |
| 738 |
if value is None: |
| 739 |
value = self |
| 740 |
self.value = value |
| 741 |
self.gobble = gobble |
| 742 |
self.enter_called = False |
| 743 |
self.exit_called = False |
| 744 |
|
| 745 |
def __enter__(self): |
| 746 |
self.enter_called = True |
| 747 |
return self.value |
| 748 |
|
| 749 |
def __exit__(self, *exc_info): |
| 750 |
self.exit_called = True |
| 751 |
self.exc_info = exc_info |
| 752 |
if self.gobble: |
| 753 |
return True |
| 754 |
|
| 755 |
class InitRaises(object): |
| 756 |
def __init__(self): raise RuntimeError() |
| 757 |
|
| 758 |
class EnterRaises(object): |
| 759 |
def __enter__(self): raise RuntimeError() |
| 760 |
def __exit__(self, *exc_info): pass |
| 761 |
|
| 762 |
class ExitRaises(object): |
| 763 |
def __enter__(self): pass |
| 764 |
def __exit__(self, *exc_info): raise RuntimeError() |
| 765 |
|
| 766 |
def testNoExceptions(self): |
| 767 |
with self.Dummy() as a, self.Dummy() as b: |
| 768 |
self.assertTrue(a.enter_called) |
| 769 |
self.assertTrue(b.enter_called) |
| 770 |
self.assertTrue(a.exit_called) |
| 771 |
self.assertTrue(b.exit_called) |
| 772 |
|
| 773 |
def testExceptionInExprList(self): |
| 774 |
try: |
| 775 |
with self.Dummy() as a, self.InitRaises(): |
| 776 |
pass |
| 777 |
except RuntimeError: |
| 778 |
pass |
| 779 |
self.assertTrue(a.enter_called) |
| 780 |
self.assertTrue(a.exit_called) |
| 781 |
|
| 782 |
def testExceptionInEnter(self): |
| 783 |
try: |
| 784 |
with self.Dummy() as a, self.EnterRaises(): |
| 785 |
self.fail('body of bad with executed') |
| 786 |
except RuntimeError: |
| 787 |
pass |
| 788 |
else: |
| 789 |
self.fail('RuntimeError not reraised') |
| 790 |
self.assertTrue(a.enter_called) |
| 791 |
self.assertTrue(a.exit_called) |
| 792 |
|
| 793 |
def testExceptionInExit(self): |
| 794 |
body_executed = False |
| 795 |
with self.Dummy(gobble=True) as a, self.ExitRaises(): |
| 796 |
body_executed = True |
| 797 |
self.assertTrue(a.enter_called) |
| 798 |
self.assertTrue(a.exit_called) |
| 799 |
self.assertTrue(body_executed) |
| 800 |
self.assertNotEqual(a.exc_info[0], None) |
| 801 |
|
| 802 |
def testEnterReturnsTuple(self): |
| 803 |
with self.Dummy(value=(1,2)) as (a1, a2), \ |
| 804 |
self.Dummy(value=(10, 20)) as (b1, b2): |
| 805 |
self.assertEqual(1, a1) |
| 806 |
self.assertEqual(2, a2) |
| 807 |
self.assertEqual(10, b1) |
| 808 |
self.assertEqual(20, b2) |
| 809 |
|
| 810 |
def testExceptionLocation(self): |
| 811 |
# The location of an exception raised from |
| 812 |
# __init__, __enter__ or __exit__ of a context |
| 813 |
# manager should be just the context manager expression, |
| 814 |
# pinpointing the precise context manager in case there |
| 815 |
# is more than one. |
| 816 |
|
| 817 |
def init_raises(): |
| 818 |
try: |
| 819 |
with self.Dummy(), self.InitRaises() as cm, self.Dummy() as d: |
| 820 |
pass |
| 821 |
except Exception as e: |
| 822 |
return e |
| 823 |
|
| 824 |
def enter_raises(): |
| 825 |
try: |
| 826 |
with self.EnterRaises(), self.Dummy() as d: |
| 827 |
pass |
| 828 |
except Exception as e: |
| 829 |
return e |
| 830 |
|
| 831 |
def exit_raises(): |
| 832 |
try: |
| 833 |
with self.ExitRaises(), self.Dummy() as d: |
| 834 |
pass |
| 835 |
except Exception as e: |
| 836 |
return e |
| 837 |
|
| 838 |
for func, expected in [(init_raises, "self.InitRaises()"), |
| 839 |
(enter_raises, "self.EnterRaises()"), |
| 840 |
(exit_raises, "self.ExitRaises()"), |
| 841 |
]: |
| 842 |
with self.subTest(func): |
| 843 |
exc = func() |
| 844 |
f = traceback.extract_tb(exc.__traceback__)[0] |
| 845 |
indent = 16 |
| 846 |
co = func.__code__ |
| 847 |
self.assertEqual(f.lineno, co.co_firstlineno + 2) |
| 848 |
self.assertEqual(f.end_lineno, co.co_firstlineno + 2) |
| 849 |
self.assertEqual(f.line[f.colno - indent : f.end_colno - indent], |
| 850 |
expected) |
| 851 |
|
| 852 |
|
| 853 |
if __name__ == '__main__': |
| 854 |
unittest.main() |