summaryrefslogtreecommitdiffstats
path: root/Lib/test
diff options
context:
space:
mode:
authorBrett Cannon <brett@python.org>2016-04-08 19:15:27 (GMT)
committerBrett Cannon <brett@python.org>2016-04-08 19:15:27 (GMT)
commit9e080e0e741dd70cf86500f848eee19cf8b29efa (patch)
tree7d5a4fa6c9279df0c3c3bddd2d041619a6862fa7 /Lib/test
parentc5b5ba9bdafaf2542ac2e6939f025a01a10549c2 (diff)
downloadcpython-9e080e0e741dd70cf86500f848eee19cf8b29efa.zip
cpython-9e080e0e741dd70cf86500f848eee19cf8b29efa.tar.gz
cpython-9e080e0e741dd70cf86500f848eee19cf8b29efa.tar.bz2
Issue #25609: Introduce contextlib.AbstractContextManager and
typing.ContextManager.
Diffstat (limited to 'Lib/test')
-rw-r--r--Lib/test/test_contextlib.py33
-rw-r--r--Lib/test/test_typing.py18
2 files changed, 51 insertions, 0 deletions
diff --git a/Lib/test/test_contextlib.py b/Lib/test/test_contextlib.py
index 04fc875..5c8bc98 100644
--- a/Lib/test/test_contextlib.py
+++ b/Lib/test/test_contextlib.py
@@ -12,6 +12,39 @@ except ImportError:
threading = None
+class TestAbstractContextManager(unittest.TestCase):
+
+ def test_enter(self):
+ class DefaultEnter(AbstractContextManager):
+ def __exit__(self, *args):
+ super().__exit__(*args)
+
+ manager = DefaultEnter()
+ self.assertIs(manager.__enter__(), manager)
+
+ def test_exit_is_abstract(self):
+ class MissingExit(AbstractContextManager):
+ pass
+
+ with self.assertRaises(TypeError):
+ MissingExit()
+
+ def test_structural_subclassing(self):
+ class ManagerFromScratch:
+ def __enter__(self):
+ return self
+ def __exit__(self, exc_type, exc_value, traceback):
+ return None
+
+ self.assertTrue(issubclass(ManagerFromScratch, AbstractContextManager))
+
+ class DefaultEnter(AbstractContextManager):
+ def __exit__(self, *args):
+ super().__exit__(*args)
+
+ self.assertTrue(issubclass(DefaultEnter, AbstractContextManager))
+
+
class ContextManagerTestCase(unittest.TestCase):
def test_contextmanager_plain(self):
diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py
index f1c6e12..a360824 100644
--- a/Lib/test/test_typing.py
+++ b/Lib/test/test_typing.py
@@ -1,3 +1,4 @@
+import contextlib
import pickle
import re
import sys
@@ -1309,6 +1310,21 @@ class CollectionsAbcTests(TestCase):
assert len(MMB[KT, VT]()) == 0
+class OtherABCTests(TestCase):
+
+ @skipUnless(hasattr(typing, 'ContextManager'),
+ 'requires typing.ContextManager')
+ def test_contextmanager(self):
+ @contextlib.contextmanager
+ def manager():
+ yield 42
+
+ cm = manager()
+ assert isinstance(cm, typing.ContextManager)
+ assert isinstance(cm, typing.ContextManager[int])
+ assert not isinstance(42, typing.ContextManager)
+
+
class NamedTupleTests(TestCase):
def test_basics(self):
@@ -1447,6 +1463,8 @@ class AllTests(TestCase):
assert 'ValuesView' in a
assert 'cast' in a
assert 'overload' in a
+ if hasattr(contextlib, 'AbstractContextManager'):
+ assert 'ContextManager' in a
# Check that io and re are not exported.
assert 'io' not in a
assert 're' not in a