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