summaryrefslogtreecommitdiffstats
path: root/Lib/test
diff options
context:
space:
mode:
Diffstat (limited to 'Lib/test')
-rw-r--r--Lib/test/test_argparse.py15
-rw-r--r--Lib/test/test_collections.py8
-rw-r--r--Lib/test/test_dictviews.py22
-rw-r--r--Lib/test/test_file.py2
-rw-r--r--Lib/test/test_inspect.py42
-rw-r--r--Lib/test/test_operator.py50
-rw-r--r--Lib/test/test_os.py19
-rw-r--r--Lib/test/test_symbol.py45
-rw-r--r--Lib/test/test_typing.py251
-rw-r--r--Lib/test/test_zipimport.py21
10 files changed, 201 insertions, 274 deletions
diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py
index 27bfad5..893ec39 100644
--- a/Lib/test/test_argparse.py
+++ b/Lib/test/test_argparse.py
@@ -4512,6 +4512,21 @@ class TestStrings(TestCase):
string = "Namespace(bar='spam', foo=42)"
self.assertStringEqual(ns, string)
+ def test_namespace_starkwargs_notidentifier(self):
+ ns = argparse.Namespace(**{'"': 'quote'})
+ string = """Namespace(**{'"': 'quote'})"""
+ self.assertStringEqual(ns, string)
+
+ def test_namespace_kwargs_and_starkwargs_notidentifier(self):
+ ns = argparse.Namespace(a=1, **{'"': 'quote'})
+ string = """Namespace(a=1, **{'"': 'quote'})"""
+ self.assertStringEqual(ns, string)
+
+ def test_namespace_starkwargs_identifier(self):
+ ns = argparse.Namespace(**{'valid': True})
+ string = "Namespace(valid=True)"
+ self.assertStringEqual(ns, string)
+
def test_parser(self):
parser = argparse.ArgumentParser(prog='PROG')
string = (
diff --git a/Lib/test/test_collections.py b/Lib/test/test_collections.py
index fbaf712..07420c6 100644
--- a/Lib/test/test_collections.py
+++ b/Lib/test/test_collections.py
@@ -1992,6 +1992,14 @@ class OrderedDictTests:
od = OrderedDict(**d)
self.assertGreater(sys.getsizeof(od), sys.getsizeof(d))
+ def test_views(self):
+ OrderedDict = self.module.OrderedDict
+ # See http://bugs.python.org/issue24286
+ s = 'the quick brown fox jumped over a lazy dog yesterday before dawn'.split()
+ od = OrderedDict.fromkeys(s)
+ self.assertEqual(od.keys(), dict(od).keys())
+ self.assertEqual(od.items(), dict(od).items())
+
def test_override_update(self):
OrderedDict = self.module.OrderedDict
# Verify that subclasses can override update() without breaking __init__()
diff --git a/Lib/test/test_dictviews.py b/Lib/test/test_dictviews.py
index 8d33801..fcb6814 100644
--- a/Lib/test/test_dictviews.py
+++ b/Lib/test/test_dictviews.py
@@ -1,3 +1,4 @@
+import collections
import unittest
class DictSetTest(unittest.TestCase):
@@ -197,6 +198,27 @@ class DictSetTest(unittest.TestCase):
d[42] = d.values()
self.assertRaises(RecursionError, repr, d)
+ def test_abc_registry(self):
+ d = dict(a=1)
+
+ self.assertIsInstance(d.keys(), collections.KeysView)
+ self.assertIsInstance(d.keys(), collections.MappingView)
+ self.assertIsInstance(d.keys(), collections.Set)
+ self.assertIsInstance(d.keys(), collections.Sized)
+ self.assertIsInstance(d.keys(), collections.Iterable)
+ self.assertIsInstance(d.keys(), collections.Container)
+
+ self.assertIsInstance(d.values(), collections.ValuesView)
+ self.assertIsInstance(d.values(), collections.MappingView)
+ self.assertIsInstance(d.values(), collections.Sized)
+
+ self.assertIsInstance(d.items(), collections.ItemsView)
+ self.assertIsInstance(d.items(), collections.MappingView)
+ self.assertIsInstance(d.items(), collections.Set)
+ self.assertIsInstance(d.items(), collections.Sized)
+ self.assertIsInstance(d.items(), collections.Iterable)
+ self.assertIsInstance(d.items(), collections.Container)
+
if __name__ == "__main__":
unittest.main()
diff --git a/Lib/test/test_file.py b/Lib/test/test_file.py
index 4e392b7..67c3d86 100644
--- a/Lib/test/test_file.py
+++ b/Lib/test/test_file.py
@@ -139,7 +139,7 @@ class OtherFileTests:
def testModeStrings(self):
# check invalid mode strings
- for mode in ("", "aU", "wU+"):
+ for mode in ("", "aU", "wU+", "U+", "+U", "rU+"):
try:
f = self.open(TESTFN, mode)
except ValueError:
diff --git a/Lib/test/test_inspect.py b/Lib/test/test_inspect.py
index 955b2ad..db15b39 100644
--- a/Lib/test/test_inspect.py
+++ b/Lib/test/test_inspect.py
@@ -38,7 +38,7 @@ from test.test_import import _ready_to_import
# ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode,
# isbuiltin, isroutine, isgenerator, isgeneratorfunction, getmembers,
# getdoc, getfile, getmodule, getsourcefile, getcomments, getsource,
-# getclasstree, getargspec, getargvalues, formatargspec, formatargvalues,
+# getclasstree, getargvalues, formatargspec, formatargvalues,
# currentframe, stack, trace, isdatadescriptor
# NOTE: There are some additional tests relating to interaction with
@@ -628,18 +628,6 @@ class TestClassesAndFunctions(unittest.TestCase):
got = inspect.getmro(D)
self.assertEqual(expected, got)
- def assertArgSpecEquals(self, routine, args_e, varargs_e=None,
- varkw_e=None, defaults_e=None, formatted=None):
- with self.assertWarns(DeprecationWarning):
- args, varargs, varkw, defaults = inspect.getargspec(routine)
- self.assertEqual(args, args_e)
- self.assertEqual(varargs, varargs_e)
- self.assertEqual(varkw, varkw_e)
- self.assertEqual(defaults, defaults_e)
- if formatted is not None:
- self.assertEqual(inspect.formatargspec(args, varargs, varkw, defaults),
- formatted)
-
def assertFullArgSpecEquals(self, routine, args_e, varargs_e=None,
varkw_e=None, defaults_e=None,
kwonlyargs_e=[], kwonlydefaults_e=None,
@@ -658,23 +646,6 @@ class TestClassesAndFunctions(unittest.TestCase):
kwonlyargs, kwonlydefaults, ann),
formatted)
- def test_getargspec(self):
- self.assertArgSpecEquals(mod.eggs, ['x', 'y'], formatted='(x, y)')
-
- self.assertArgSpecEquals(mod.spam,
- ['a', 'b', 'c', 'd', 'e', 'f'],
- 'g', 'h', (3, 4, 5),
- '(a, b, c, d=3, e=4, f=5, *g, **h)')
-
- self.assertRaises(ValueError, self.assertArgSpecEquals,
- mod2.keyworded, [])
-
- self.assertRaises(ValueError, self.assertArgSpecEquals,
- mod2.annotated, [])
- self.assertRaises(ValueError, self.assertArgSpecEquals,
- mod2.keyword_only_arg, [])
-
-
def test_getfullargspec(self):
self.assertFullArgSpecEquals(mod2.keyworded, [], varargs_e='arg1',
kwonlyargs_e=['arg2'],
@@ -688,20 +659,19 @@ class TestClassesAndFunctions(unittest.TestCase):
kwonlyargs_e=['arg'],
formatted='(*, arg)')
- def test_argspec_api_ignores_wrapped(self):
+ def test_fullargspec_api_ignores_wrapped(self):
# Issue 20684: low level introspection API must ignore __wrapped__
@functools.wraps(mod.spam)
def ham(x, y):
pass
# Basic check
- self.assertArgSpecEquals(ham, ['x', 'y'], formatted='(x, y)')
self.assertFullArgSpecEquals(ham, ['x', 'y'], formatted='(x, y)')
self.assertFullArgSpecEquals(functools.partial(ham),
['x', 'y'], formatted='(x, y)')
# Other variants
def check_method(f):
- self.assertArgSpecEquals(f, ['self', 'x', 'y'],
- formatted='(self, x, y)')
+ self.assertFullArgSpecEquals(f, ['self', 'x', 'y'],
+ formatted='(self, x, y)')
class C:
@functools.wraps(mod.spam)
def ham(self, x, y):
@@ -779,11 +749,11 @@ class TestClassesAndFunctions(unittest.TestCase):
with self.assertRaises(TypeError):
inspect.getfullargspec(builtin)
- def test_getargspec_method(self):
+ def test_getfullargspec_method(self):
class A(object):
def m(self):
pass
- self.assertArgSpecEquals(A.m, ['self'])
+ self.assertFullArgSpecEquals(A.m, ['self'])
def test_classify_newstyle(self):
class A(object):
diff --git a/Lib/test/test_operator.py b/Lib/test/test_operator.py
index da9c8ef..54fd1f4 100644
--- a/Lib/test/test_operator.py
+++ b/Lib/test/test_operator.py
@@ -120,63 +120,63 @@ class OperatorTestCase:
operator = self.module
self.assertRaises(TypeError, operator.add)
self.assertRaises(TypeError, operator.add, None, None)
- self.assertTrue(operator.add(3, 4) == 7)
+ self.assertEqual(operator.add(3, 4), 7)
def test_bitwise_and(self):
operator = self.module
self.assertRaises(TypeError, operator.and_)
self.assertRaises(TypeError, operator.and_, None, None)
- self.assertTrue(operator.and_(0xf, 0xa) == 0xa)
+ self.assertEqual(operator.and_(0xf, 0xa), 0xa)
def test_concat(self):
operator = self.module
self.assertRaises(TypeError, operator.concat)
self.assertRaises(TypeError, operator.concat, None, None)
- self.assertTrue(operator.concat('py', 'thon') == 'python')
- self.assertTrue(operator.concat([1, 2], [3, 4]) == [1, 2, 3, 4])
- self.assertTrue(operator.concat(Seq1([5, 6]), Seq1([7])) == [5, 6, 7])
- self.assertTrue(operator.concat(Seq2([5, 6]), Seq2([7])) == [5, 6, 7])
+ self.assertEqual(operator.concat('py', 'thon'), 'python')
+ self.assertEqual(operator.concat([1, 2], [3, 4]), [1, 2, 3, 4])
+ self.assertEqual(operator.concat(Seq1([5, 6]), Seq1([7])), [5, 6, 7])
+ self.assertEqual(operator.concat(Seq2([5, 6]), Seq2([7])), [5, 6, 7])
self.assertRaises(TypeError, operator.concat, 13, 29)
def test_countOf(self):
operator = self.module
self.assertRaises(TypeError, operator.countOf)
self.assertRaises(TypeError, operator.countOf, None, None)
- self.assertTrue(operator.countOf([1, 2, 1, 3, 1, 4], 3) == 1)
- self.assertTrue(operator.countOf([1, 2, 1, 3, 1, 4], 5) == 0)
+ self.assertEqual(operator.countOf([1, 2, 1, 3, 1, 4], 3), 1)
+ self.assertEqual(operator.countOf([1, 2, 1, 3, 1, 4], 5), 0)
def test_delitem(self):
operator = self.module
a = [4, 3, 2, 1]
self.assertRaises(TypeError, operator.delitem, a)
self.assertRaises(TypeError, operator.delitem, a, None)
- self.assertTrue(operator.delitem(a, 1) is None)
- self.assertTrue(a == [4, 2, 1])
+ self.assertIsNone(operator.delitem(a, 1))
+ self.assertEqual(a, [4, 2, 1])
def test_floordiv(self):
operator = self.module
self.assertRaises(TypeError, operator.floordiv, 5)
self.assertRaises(TypeError, operator.floordiv, None, None)
- self.assertTrue(operator.floordiv(5, 2) == 2)
+ self.assertEqual(operator.floordiv(5, 2), 2)
def test_truediv(self):
operator = self.module
self.assertRaises(TypeError, operator.truediv, 5)
self.assertRaises(TypeError, operator.truediv, None, None)
- self.assertTrue(operator.truediv(5, 2) == 2.5)
+ self.assertEqual(operator.truediv(5, 2), 2.5)
def test_getitem(self):
operator = self.module
a = range(10)
self.assertRaises(TypeError, operator.getitem)
self.assertRaises(TypeError, operator.getitem, a, None)
- self.assertTrue(operator.getitem(a, 2) == 2)
+ self.assertEqual(operator.getitem(a, 2), 2)
def test_indexOf(self):
operator = self.module
self.assertRaises(TypeError, operator.indexOf)
self.assertRaises(TypeError, operator.indexOf, None, None)
- self.assertTrue(operator.indexOf([4, 3, 2, 1], 3) == 1)
+ self.assertEqual(operator.indexOf([4, 3, 2, 1], 3), 1)
self.assertRaises(ValueError, operator.indexOf, [4, 3, 2, 1], 0)
def test_invert(self):
@@ -189,21 +189,21 @@ class OperatorTestCase:
operator = self.module
self.assertRaises(TypeError, operator.lshift)
self.assertRaises(TypeError, operator.lshift, None, 42)
- self.assertTrue(operator.lshift(5, 1) == 10)
- self.assertTrue(operator.lshift(5, 0) == 5)
+ self.assertEqual(operator.lshift(5, 1), 10)
+ self.assertEqual(operator.lshift(5, 0), 5)
self.assertRaises(ValueError, operator.lshift, 2, -1)
def test_mod(self):
operator = self.module
self.assertRaises(TypeError, operator.mod)
self.assertRaises(TypeError, operator.mod, None, 42)
- self.assertTrue(operator.mod(5, 2) == 1)
+ self.assertEqual(operator.mod(5, 2), 1)
def test_mul(self):
operator = self.module
self.assertRaises(TypeError, operator.mul)
self.assertRaises(TypeError, operator.mul, None, None)
- self.assertTrue(operator.mul(5, 2) == 10)
+ self.assertEqual(operator.mul(5, 2), 10)
def test_matmul(self):
operator = self.module
@@ -227,7 +227,7 @@ class OperatorTestCase:
operator = self.module
self.assertRaises(TypeError, operator.or_)
self.assertRaises(TypeError, operator.or_, None, None)
- self.assertTrue(operator.or_(0xa, 0x5) == 0xf)
+ self.assertEqual(operator.or_(0xa, 0x5), 0xf)
def test_pos(self):
operator = self.module
@@ -250,8 +250,8 @@ class OperatorTestCase:
operator = self.module
self.assertRaises(TypeError, operator.rshift)
self.assertRaises(TypeError, operator.rshift, None, 42)
- self.assertTrue(operator.rshift(5, 1) == 2)
- self.assertTrue(operator.rshift(5, 0) == 5)
+ self.assertEqual(operator.rshift(5, 1), 2)
+ self.assertEqual(operator.rshift(5, 0), 5)
self.assertRaises(ValueError, operator.rshift, 2, -1)
def test_contains(self):
@@ -266,15 +266,15 @@ class OperatorTestCase:
a = list(range(3))
self.assertRaises(TypeError, operator.setitem, a)
self.assertRaises(TypeError, operator.setitem, a, None, None)
- self.assertTrue(operator.setitem(a, 0, 2) is None)
- self.assertTrue(a == [2, 1, 2])
+ self.assertIsNone(operator.setitem(a, 0, 2))
+ self.assertEqual(a, [2, 1, 2])
self.assertRaises(IndexError, operator.setitem, a, 4, 2)
def test_sub(self):
operator = self.module
self.assertRaises(TypeError, operator.sub)
self.assertRaises(TypeError, operator.sub, None, None)
- self.assertTrue(operator.sub(5, 2) == 3)
+ self.assertEqual(operator.sub(5, 2), 3)
def test_truth(self):
operator = self.module
@@ -292,7 +292,7 @@ class OperatorTestCase:
operator = self.module
self.assertRaises(TypeError, operator.xor)
self.assertRaises(TypeError, operator.xor, None, None)
- self.assertTrue(operator.xor(0xb, 0xc) == 0x7)
+ self.assertEqual(operator.xor(0xb, 0xc), 0x7)
def test_is(self):
operator = self.module
diff --git a/Lib/test/test_os.py b/Lib/test/test_os.py
index d91f58c..b3cf207 100644
--- a/Lib/test/test_os.py
+++ b/Lib/test/test_os.py
@@ -213,15 +213,10 @@ class FileTests(unittest.TestCase):
# Test attributes on return values from os.*stat* family.
class StatAttributeTests(unittest.TestCase):
def setUp(self):
- os.mkdir(support.TESTFN)
- self.fname = os.path.join(support.TESTFN, "f1")
- f = open(self.fname, 'wb')
- f.write(b"ABC")
- f.close()
-
- def tearDown(self):
- os.unlink(self.fname)
- os.rmdir(support.TESTFN)
+ self.fname = support.TESTFN
+ self.addCleanup(support.unlink, self.fname)
+ with open(self.fname, 'wb') as fp:
+ fp.write(b"ABC")
@unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()')
def check_stat_attributes(self, fname):
@@ -413,7 +408,11 @@ class StatAttributeTests(unittest.TestCase):
0)
# test directory st_file_attributes (FILE_ATTRIBUTE_DIRECTORY set)
- result = os.stat(support.TESTFN)
+ dirname = support.TESTFN + "dir"
+ os.mkdir(dirname)
+ self.addCleanup(os.rmdir, dirname)
+
+ result = os.stat(dirname)
self.check_file_attributes(result)
self.assertEqual(
result.st_file_attributes & stat.FILE_ATTRIBUTE_DIRECTORY,
diff --git a/Lib/test/test_symbol.py b/Lib/test/test_symbol.py
new file mode 100644
index 0000000..4475bbc
--- /dev/null
+++ b/Lib/test/test_symbol.py
@@ -0,0 +1,45 @@
+import unittest
+from test import support
+import filecmp
+import os
+import sys
+import subprocess
+
+
+SYMBOL_FILE = support.findfile('symbol.py')
+GRAMMAR_FILE = os.path.join(os.path.dirname(__file__),
+ '..', '..', 'Include', 'graminit.h')
+TEST_PY_FILE = 'symbol_test.py'
+
+
+class TestSymbolGeneration(unittest.TestCase):
+
+ def _copy_file_without_generated_symbols(self, source_file, dest_file):
+ with open(source_file, 'rb') as fp:
+ lines = fp.readlines()
+ nl = lines[0][len(lines[0].rstrip()):]
+ with open(dest_file, 'wb') as fp:
+ fp.writelines(lines[:lines.index(b"#--start constants--" + nl) + 1])
+ fp.writelines(lines[lines.index(b"#--end constants--" + nl):])
+
+ def _generate_symbols(self, grammar_file, target_symbol_py_file):
+ proc = subprocess.Popen([sys.executable,
+ SYMBOL_FILE,
+ grammar_file,
+ target_symbol_py_file], stderr=subprocess.PIPE)
+ stderr = proc.communicate()[1]
+ return proc.returncode, stderr
+
+ @unittest.skipIf(not os.path.exists(GRAMMAR_FILE),
+ 'test only works from source build directory')
+ def test_real_grammar_and_symbol_file(self):
+ self._copy_file_without_generated_symbols(SYMBOL_FILE, TEST_PY_FILE)
+ self.addCleanup(support.unlink, TEST_PY_FILE)
+ self.assertFalse(filecmp.cmp(SYMBOL_FILE, TEST_PY_FILE))
+ self.assertEqual((0, b''), self._generate_symbols(GRAMMAR_FILE,
+ TEST_PY_FILE))
+ self.assertTrue(filecmp.cmp(SYMBOL_FILE, TEST_PY_FILE))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py
index c37e113..2bb21ed 100644
--- a/Lib/test/test_typing.py
+++ b/Lib/test/test_typing.py
@@ -41,11 +41,9 @@ class ManagingFounder(Manager, Founder):
class AnyTests(TestCase):
- def test_any_instance(self):
- self.assertIsInstance(Employee(), Any)
- self.assertIsInstance(42, Any)
- self.assertIsInstance(None, Any)
- self.assertIsInstance(object(), Any)
+ def test_any_instance_type_error(self):
+ with self.assertRaises(TypeError):
+ isinstance(42, Any)
def test_any_subclass(self):
self.assertTrue(issubclass(Employee, Any))
@@ -109,9 +107,6 @@ class TypeVarTests(TestCase):
def test_basic_plain(self):
T = TypeVar('T')
- # Nothing is an instance if T.
- with self.assertRaises(TypeError):
- isinstance('', T)
# Every class is a subclass of T.
assert issubclass(int, T)
assert issubclass(str, T)
@@ -119,12 +114,16 @@ class TypeVarTests(TestCase):
assert T == T
# T is a subclass of itself.
assert issubclass(T, T)
+ # T is an instance of TypeVar
+ assert isinstance(T, TypeVar)
+
+ def test_typevar_instance_type_error(self):
+ T = TypeVar('T')
+ with self.assertRaises(TypeError):
+ isinstance(42, T)
def test_basic_constrained(self):
A = TypeVar('A', str, bytes)
- # Nothing is an instance of A.
- with self.assertRaises(TypeError):
- isinstance('', A)
# Only str and bytes are subclasses of A.
assert issubclass(str, A)
assert issubclass(bytes, A)
@@ -213,8 +212,6 @@ class UnionTests(TestCase):
def test_basics(self):
u = Union[int, float]
self.assertNotEqual(u, Union)
- self.assertIsInstance(42, u)
- self.assertIsInstance(3.14, u)
self.assertTrue(issubclass(int, u))
self.assertTrue(issubclass(float, u))
@@ -247,7 +244,6 @@ class UnionTests(TestCase):
def test_subclass(self):
u = Union[int, Employee]
- self.assertIsInstance(Manager(), u)
self.assertTrue(issubclass(Manager, u))
def test_self_subclass(self):
@@ -256,7 +252,6 @@ class UnionTests(TestCase):
def test_multiple_inheritance(self):
u = Union[int, Employee]
- self.assertIsInstance(ManagingFounder(), u)
self.assertTrue(issubclass(ManagingFounder, u))
def test_single_class_disappears(self):
@@ -309,9 +304,6 @@ class UnionTests(TestCase):
o = Optional[int]
u = Union[int, None]
self.assertEqual(o, u)
- self.assertIsInstance(42, o)
- self.assertIsInstance(None, o)
- self.assertNotIsInstance(3.14, o)
def test_empty(self):
with self.assertRaises(TypeError):
@@ -321,11 +313,9 @@ class UnionTests(TestCase):
assert issubclass(Union[int, str], Union)
assert not issubclass(int, Union)
- def test_isinstance_union(self):
- # Nothing is an instance of bare Union.
- assert not isinstance(42, Union)
- assert not isinstance(int, Union)
- assert not isinstance(Union[int, str], Union)
+ def test_union_instance_type_error(self):
+ with self.assertRaises(TypeError):
+ isinstance(42, Union[int, str])
class TypeVarUnionTests(TestCase):
@@ -352,22 +342,11 @@ class TypeVarUnionTests(TestCase):
TU = TypeVar('TU', Union[int, float], None)
assert issubclass(int, TU)
assert issubclass(float, TU)
- with self.assertRaises(TypeError):
- isinstance(42, TU)
- with self.assertRaises(TypeError):
- isinstance('', TU)
class TupleTests(TestCase):
def test_basics(self):
- self.assertIsInstance((42, 3.14, ''), Tuple)
- self.assertIsInstance((42, 3.14, ''), Tuple[int, float, str])
- self.assertIsInstance((42,), Tuple[int])
- self.assertNotIsInstance((3.14,), Tuple[int])
- self.assertNotIsInstance((42, 3.14), Tuple[int, float, str])
- self.assertNotIsInstance((42, 3.14, 100), Tuple[int, float, str])
- self.assertNotIsInstance((42, 3.14, 100), Tuple[int, float])
self.assertTrue(issubclass(Tuple[int, str], Tuple))
self.assertTrue(issubclass(Tuple[int, str], Tuple[int, str]))
self.assertFalse(issubclass(int, Tuple))
@@ -382,14 +361,11 @@ class TupleTests(TestCase):
pass
self.assertTrue(issubclass(MyTuple, Tuple))
- def test_tuple_ellipsis(self):
- t = Tuple[int, ...]
- assert isinstance((), t)
- assert isinstance((1,), t)
- assert isinstance((1, 2), t)
- assert isinstance((1, 2, 3), t)
- assert not isinstance((3.14,), t)
- assert not isinstance((1, 2, 3.14,), t)
+ def test_tuple_instance_type_error(self):
+ with self.assertRaises(TypeError):
+ isinstance((0, 0), Tuple[int, int])
+ with self.assertRaises(TypeError):
+ isinstance((0, 0), Tuple)
def test_tuple_ellipsis_subclass(self):
@@ -419,18 +395,6 @@ class TupleTests(TestCase):
class CallableTests(TestCase):
- def test_basics(self):
- c = Callable[[int, float], str]
-
- def flub(a: int, b: float) -> str:
- return str(a * b)
-
- def flob(a: int, b: int) -> str:
- return str(a * b)
-
- self.assertIsInstance(flub, c)
- self.assertNotIsInstance(flob, c)
-
def test_self_subclass(self):
self.assertTrue(issubclass(Callable[[int], int], Callable))
self.assertFalse(issubclass(Callable, Callable[[int], int]))
@@ -453,91 +417,6 @@ class CallableTests(TestCase):
self.assertNotEqual(Callable[[int], int], Callable[[], int])
self.assertNotEqual(Callable[[int], int], Callable)
- def test_with_none(self):
- c = Callable[[None], None]
-
- def flub(self: None) -> None:
- pass
-
- def flab(self: Any) -> None:
- pass
-
- def flob(self: None) -> Any:
- pass
-
- self.assertIsInstance(flub, c)
- self.assertIsInstance(flab, c)
- self.assertNotIsInstance(flob, c) # Test contravariance.
-
- def test_with_subclasses(self):
- c = Callable[[Employee, Manager], Employee]
-
- def flub(a: Employee, b: Employee) -> Manager:
- return Manager()
-
- def flob(a: Manager, b: Manager) -> Employee:
- return Employee()
-
- self.assertIsInstance(flub, c)
- self.assertNotIsInstance(flob, c)
-
- def test_with_default_args(self):
- c = Callable[[int], int]
-
- def flub(a: int, b: float = 3.14) -> int:
- return a
-
- def flab(a: int, *, b: float = 3.14) -> int:
- return a
-
- def flob(a: int = 42) -> int:
- return a
-
- self.assertIsInstance(flub, c)
- self.assertIsInstance(flab, c)
- self.assertIsInstance(flob, c)
-
- def test_with_varargs(self):
- c = Callable[[int], int]
-
- def flub(*args) -> int:
- return 42
-
- def flab(*args: int) -> int:
- return 42
-
- def flob(*args: float) -> int:
- return 42
-
- self.assertIsInstance(flub, c)
- self.assertIsInstance(flab, c)
- self.assertNotIsInstance(flob, c)
-
- def test_with_method(self):
-
- class C:
-
- def imethod(self, arg: int) -> int:
- self.last_arg = arg
- return arg + 1
-
- @classmethod
- def cmethod(cls, arg: int) -> int:
- cls.last_cls_arg = arg
- return arg + 1
-
- @staticmethod
- def smethod(arg: int) -> int:
- return arg + 1
-
- ct = Callable[[int], int]
- self.assertIsInstance(C().imethod, ct)
- self.assertIsInstance(C().cmethod, ct)
- self.assertIsInstance(C.cmethod, ct)
- self.assertIsInstance(C().smethod, ct)
- self.assertIsInstance(C.smethod, ct)
- self.assertIsInstance(C.imethod, Callable[[Any, int], int])
-
def test_cannot_subclass(self):
with self.assertRaises(TypeError):
@@ -556,21 +435,21 @@ class CallableTests(TestCase):
with self.assertRaises(TypeError):
c()
- def test_varargs(self):
- ct = Callable[..., int]
-
- def foo(a, b) -> int:
- return 42
+ def test_callable_instance_works(self):
+ f = lambda: None
+ assert isinstance(f, Callable)
+ assert not isinstance(None, Callable)
- def bar(a=42) -> int:
- return a
-
- def baz(*, x, y, z) -> int:
- return 100
-
- self.assertIsInstance(foo, ct)
- self.assertIsInstance(bar, ct)
- self.assertIsInstance(baz, ct)
+ def test_callable_instance_type_error(self):
+ f = lambda: None
+ with self.assertRaises(TypeError):
+ assert isinstance(f, Callable[[], None])
+ with self.assertRaises(TypeError):
+ assert isinstance(f, Callable[[], Any])
+ with self.assertRaises(TypeError):
+ assert not isinstance(None, Callable[[], None])
+ with self.assertRaises(TypeError):
+ assert not isinstance(None, Callable[[], Any])
def test_repr(self):
ct0 = Callable[[], bool]
@@ -659,6 +538,10 @@ class ProtocolTests(TestCase):
assert issubclass(list, typing.Reversible)
assert not issubclass(int, typing.Reversible)
+ def test_protocol_instance_type_error(self):
+ with self.assertRaises(TypeError):
+ isinstance([], typing.Reversible)
+
class GenericTests(TestCase):
@@ -824,11 +707,11 @@ class VarianceTests(TestCase):
typing.Sequence[Manager])
def test_covariance_mapping(self):
- # Ditto for Mapping (a generic class with two parameters).
+ # Ditto for Mapping (covariant in the value, invariant in the key).
assert issubclass(typing.Mapping[Employee, Manager],
typing.Mapping[Employee, Employee])
- assert issubclass(typing.Mapping[Manager, Employee],
- typing.Mapping[Employee, Employee])
+ assert not issubclass(typing.Mapping[Manager, Employee],
+ typing.Mapping[Employee, Employee])
assert not issubclass(typing.Mapping[Employee, Manager],
typing.Mapping[Manager, Manager])
assert not issubclass(typing.Mapping[Manager, Employee],
@@ -889,6 +772,11 @@ class ForwardRefTests(TestCase):
right_hints = get_type_hints(t.add_right, globals(), locals())
assert right_hints['node'] == Optional[Node[T]]
+ def test_forwardref_instance_type_error(self):
+ fr = typing._ForwardRef('int')
+ with self.assertRaises(TypeError):
+ isinstance(42, fr)
+
def test_union_forward(self):
def foo(a: Union['T']):
@@ -1069,50 +957,17 @@ class CollectionsAbcTests(TestCase):
def test_list(self):
assert issubclass(list, typing.List)
- assert isinstance([], typing.List)
- assert not isinstance((), typing.List)
- t = typing.List[int]
- assert isinstance([], t)
- assert isinstance([42], t)
- assert not isinstance([''], t)
def test_set(self):
assert issubclass(set, typing.Set)
assert not issubclass(frozenset, typing.Set)
- assert isinstance(set(), typing.Set)
- assert not isinstance({}, typing.Set)
- t = typing.Set[int]
- assert isinstance(set(), t)
- assert isinstance({42}, t)
- assert not isinstance({''}, t)
def test_frozenset(self):
assert issubclass(frozenset, typing.FrozenSet)
assert not issubclass(set, typing.FrozenSet)
- assert isinstance(frozenset(), typing.FrozenSet)
- assert not isinstance({}, typing.FrozenSet)
- t = typing.FrozenSet[int]
- assert isinstance(frozenset(), t)
- assert isinstance(frozenset({42}), t)
- assert not isinstance(frozenset({''}), t)
- assert not isinstance({42}, t)
-
- def test_mapping_views(self):
- # TODO: These tests are kind of lame.
- assert isinstance({}.keys(), typing.KeysView)
- assert isinstance({}.items(), typing.ItemsView)
- assert isinstance({}.values(), typing.ValuesView)
def test_dict(self):
assert issubclass(dict, typing.Dict)
- assert isinstance({}, typing.Dict)
- assert not isinstance([], typing.Dict)
- t = typing.Dict[int, str]
- assert isinstance({}, t)
- assert isinstance({42: ''}, t)
- assert not isinstance({42: 42}, t)
- assert not isinstance({'': 42}, t)
- assert not isinstance({'': ''}, t)
def test_no_list_instantiation(self):
with self.assertRaises(TypeError):
@@ -1191,8 +1046,6 @@ class CollectionsAbcTests(TestCase):
yield 42
g = foo()
assert issubclass(type(g), typing.Generator)
- assert isinstance(g, typing.Generator)
- assert not isinstance(foo, typing.Generator)
assert issubclass(typing.Generator[Manager, Employee, Manager],
typing.Generator[Employee, Manager, Employee])
assert not issubclass(typing.Generator[Manager, Manager, Manager],
@@ -1228,12 +1081,6 @@ class CollectionsAbcTests(TestCase):
assert len(MMB[str, str]()) == 0
assert len(MMB[KT, VT]()) == 0
- def test_recursive_dict(self):
- D = typing.Dict[int, 'D'] # Uses a _ForwardRef
- assert isinstance({}, D) # Easy
- assert isinstance({0: {}}, D) # Touches _ForwardRef
- assert isinstance({0: {0: {}}}, D) # Etc...
-
class NamedTupleTests(TestCase):
@@ -1294,8 +1141,6 @@ class RETests(TestCase):
def test_basics(self):
pat = re.compile('[a-z]+', re.I)
assert issubclass(pat.__class__, Pattern)
- assert isinstance(pat, Pattern[str])
- assert not isinstance(pat, Pattern[bytes])
assert issubclass(type(pat), Pattern)
assert issubclass(type(pat), Pattern[str])
@@ -1307,12 +1152,10 @@ class RETests(TestCase):
assert issubclass(type(mat), Match[str])
p = Pattern[Union[str, bytes]]
- assert isinstance(pat, p)
assert issubclass(Pattern[str], Pattern)
assert issubclass(Pattern[str], p)
m = Match[Union[bytes, str]]
- assert isinstance(mat, m)
assert issubclass(Match[bytes], Match)
assert issubclass(Match[bytes], m)
@@ -1327,6 +1170,12 @@ class RETests(TestCase):
with self.assertRaises(TypeError):
# Too complicated?
m[str]
+ with self.assertRaises(TypeError):
+ # We don't support isinstance().
+ isinstance(42, Pattern)
+ with self.assertRaises(TypeError):
+ # We don't support isinstance().
+ isinstance(42, Pattern[str])
def test_repr(self):
assert repr(Pattern) == 'Pattern[~AnyStr]'
diff --git a/Lib/test/test_zipimport.py b/Lib/test/test_zipimport.py
index a97a778..4f19535 100644
--- a/Lib/test/test_zipimport.py
+++ b/Lib/test/test_zipimport.py
@@ -214,7 +214,8 @@ class UncompressedZipImportTestCase(ImportHooksBaseTestCase):
packdir2 = packdir + TESTPACK2 + os.sep
files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc),
packdir2 + "__init__" + pyc_ext: (NOW, test_pyc),
- packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)}
+ packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc),
+ "spam" + pyc_ext: (NOW, test_pyc)}
z = ZipFile(TEMP_ZIP, "w")
try:
@@ -228,6 +229,14 @@ class UncompressedZipImportTestCase(ImportHooksBaseTestCase):
zi = zipimport.zipimporter(TEMP_ZIP)
self.assertEqual(zi.archive, TEMP_ZIP)
self.assertEqual(zi.is_package(TESTPACK), True)
+
+ find_mod = zi.find_module('spam')
+ self.assertIsNotNone(find_mod)
+ self.assertIsInstance(find_mod, zipimport.zipimporter)
+ self.assertFalse(find_mod.is_package('spam'))
+ load_mod = find_mod.load_module('spam')
+ self.assertEqual(find_mod.get_filename('spam'), load_mod.__file__)
+
mod = zi.load_module(TESTPACK)
self.assertEqual(zi.get_filename(TESTPACK), mod.__file__)
@@ -287,6 +296,16 @@ class UncompressedZipImportTestCase(ImportHooksBaseTestCase):
self.assertEqual(
zi.is_package(TESTPACK2 + os.sep + TESTMOD), False)
+ pkg_path = TEMP_ZIP + os.sep + packdir + TESTPACK2
+ zi2 = zipimport.zipimporter(pkg_path)
+ find_mod_dotted = zi2.find_module(TESTMOD)
+ self.assertIsNotNone(find_mod_dotted)
+ self.assertIsInstance(find_mod_dotted, zipimport.zipimporter)
+ self.assertFalse(zi2.is_package(TESTMOD))
+ load_mod = find_mod_dotted.load_module(TESTMOD)
+ self.assertEqual(
+ find_mod_dotted.get_filename(TESTMOD), load_mod.__file__)
+
mod_path = TESTPACK2 + os.sep + TESTMOD
mod_name = module_path_to_dotted_name(mod_path)
__import__(mod_name)