ยปCore Development>Code coverage>Lib/test/test_typechecks.py

Python code coverage for Lib/test/test_typechecks.py

#countcontent
1n/a"""Unit tests for __instancecheck__ and __subclasscheck__."""
2n/a
3n/aimport unittest
4n/a
5n/a
6n/aclass ABC(type):
7n/a
8n/a def __instancecheck__(cls, inst):
9n/a """Implement isinstance(inst, cls)."""
10n/a return any(cls.__subclasscheck__(c)
11n/a for c in {type(inst), inst.__class__})
12n/a
13n/a def __subclasscheck__(cls, sub):
14n/a """Implement issubclass(sub, cls)."""
15n/a candidates = cls.__dict__.get("__subclass__", set()) | {cls}
16n/a return any(c in candidates for c in sub.mro())
17n/a
18n/a
19n/aclass Integer(metaclass=ABC):
20n/a __subclass__ = {int}
21n/a
22n/a
23n/aclass SubInt(Integer):
24n/a pass
25n/a
26n/a
27n/aclass TypeChecksTest(unittest.TestCase):
28n/a
29n/a def testIsSubclassInternal(self):
30n/a self.assertEqual(Integer.__subclasscheck__(int), True)
31n/a self.assertEqual(Integer.__subclasscheck__(float), False)
32n/a
33n/a def testIsSubclassBuiltin(self):
34n/a self.assertEqual(issubclass(int, Integer), True)
35n/a self.assertEqual(issubclass(int, (Integer,)), True)
36n/a self.assertEqual(issubclass(float, Integer), False)
37n/a self.assertEqual(issubclass(float, (Integer,)), False)
38n/a
39n/a def testIsInstanceBuiltin(self):
40n/a self.assertEqual(isinstance(42, Integer), True)
41n/a self.assertEqual(isinstance(42, (Integer,)), True)
42n/a self.assertEqual(isinstance(3.14, Integer), False)
43n/a self.assertEqual(isinstance(3.14, (Integer,)), False)
44n/a
45n/a def testIsInstanceActual(self):
46n/a self.assertEqual(isinstance(Integer(), Integer), True)
47n/a self.assertEqual(isinstance(Integer(), (Integer,)), True)
48n/a
49n/a def testIsSubclassActual(self):
50n/a self.assertEqual(issubclass(Integer, Integer), True)
51n/a self.assertEqual(issubclass(Integer, (Integer,)), True)
52n/a
53n/a def testSubclassBehavior(self):
54n/a self.assertEqual(issubclass(SubInt, Integer), True)
55n/a self.assertEqual(issubclass(SubInt, (Integer,)), True)
56n/a self.assertEqual(issubclass(SubInt, SubInt), True)
57n/a self.assertEqual(issubclass(SubInt, (SubInt,)), True)
58n/a self.assertEqual(issubclass(Integer, SubInt), False)
59n/a self.assertEqual(issubclass(Integer, (SubInt,)), False)
60n/a self.assertEqual(issubclass(int, SubInt), False)
61n/a self.assertEqual(issubclass(int, (SubInt,)), False)
62n/a self.assertEqual(isinstance(SubInt(), Integer), True)
63n/a self.assertEqual(isinstance(SubInt(), (Integer,)), True)
64n/a self.assertEqual(isinstance(SubInt(), SubInt), True)
65n/a self.assertEqual(isinstance(SubInt(), (SubInt,)), True)
66n/a self.assertEqual(isinstance(42, SubInt), False)
67n/a self.assertEqual(isinstance(42, (SubInt,)), False)
68n/a
69n/a
70n/aif __name__ == "__main__":
71n/a unittest.main()