Guido van Rossum | adee45e | 2007-05-25 17:55:52 +0000 | [diff] [blame] | 1 | """Unit tests for __instancecheck__ and __subclasscheck__.""" |
| 2 | |
| 3 | import unittest |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 4 | from test import support |
Guido van Rossum | adee45e | 2007-05-25 17:55:52 +0000 | [diff] [blame] | 5 | |
| 6 | |
| 7 | class ABC(type): |
| 8 | |
| 9 | def __instancecheck__(cls, inst): |
| 10 | """Implement isinstance(inst, cls).""" |
| 11 | return any(cls.__subclasscheck__(c) |
| 12 | for c in {type(inst), inst.__class__}) |
| 13 | |
| 14 | def __subclasscheck__(cls, sub): |
| 15 | """Implement issubclass(sub, cls).""" |
| 16 | candidates = cls.__dict__.get("__subclass__", set()) | {cls} |
| 17 | return any(c in candidates for c in sub.mro()) |
| 18 | |
| 19 | |
| 20 | class Integer(metaclass=ABC): |
Guido van Rossum | adee45e | 2007-05-25 17:55:52 +0000 | [diff] [blame] | 21 | __subclass__ = {int} |
| 22 | |
| 23 | |
| 24 | class SubInt(Integer): |
Guido van Rossum | adee45e | 2007-05-25 17:55:52 +0000 | [diff] [blame] | 25 | pass |
| 26 | |
| 27 | |
Guido van Rossum | adee45e | 2007-05-25 17:55:52 +0000 | [diff] [blame] | 28 | class TypeChecksTest(unittest.TestCase): |
| 29 | |
| 30 | def testIsSubclassInternal(self): |
| 31 | self.assertEqual(Integer.__subclasscheck__(int), True) |
| 32 | self.assertEqual(Integer.__subclasscheck__(float), False) |
| 33 | |
| 34 | def testIsSubclassBuiltin(self): |
| 35 | self.assertEqual(issubclass(int, Integer), True) |
| 36 | self.assertEqual(issubclass(float, Integer), False) |
| 37 | |
| 38 | def testIsInstanceBuiltin(self): |
| 39 | self.assertEqual(isinstance(42, Integer), True) |
| 40 | self.assertEqual(isinstance(3.14, Integer), False) |
| 41 | |
| 42 | def testIsInstanceActual(self): |
| 43 | self.assertEqual(isinstance(Integer(), Integer), True) |
| 44 | |
| 45 | def testIsSubclassActual(self): |
| 46 | self.assertEqual(issubclass(Integer, Integer), True) |
| 47 | |
| 48 | def testSubclassBehavior(self): |
| 49 | self.assertEqual(issubclass(SubInt, Integer), True) |
| 50 | self.assertEqual(issubclass(SubInt, SubInt), True) |
| 51 | self.assertEqual(issubclass(Integer, SubInt), False) |
| 52 | self.assertEqual(issubclass(int, SubInt), False) |
| 53 | self.assertEqual(isinstance(SubInt(), Integer), True) |
| 54 | self.assertEqual(isinstance(SubInt(), SubInt), True) |
| 55 | self.assertEqual(isinstance(42, SubInt), False) |
| 56 | |
Guido van Rossum | adee45e | 2007-05-25 17:55:52 +0000 | [diff] [blame] | 57 | |
| 58 | def test_main(): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 59 | support.run_unittest(TypeChecksTest) |
Guido van Rossum | adee45e | 2007-05-25 17:55:52 +0000 | [diff] [blame] | 60 | |
| 61 | |
| 62 | if __name__ == "__main__": |
| 63 | unittest.main() |